-
Notifications
You must be signed in to change notification settings - Fork 58
feat: Async Journey: LiteLLM Removal from Async Engine #310
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
eric-tramel
wants to merge
6
commits into
async/async-facade
Choose a base branch
from
async/litellm-removal
base: async/async-facade
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7679741
Initialize alternate module path
eric-tramel 1c461c1
Fix tests
eric-tramel 1129ed6
Add a benchmark to track progress.
eric-tramel 4dbbef1
fix test patching
eric-tramel 35f4d71
feat(engine): add async model facade + async concurrent executor
eric-tramel 3b4524c
docs: add LiteLLM removal impact analysis and implementation plan
eric-tramel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
168 changes: 168 additions & 0 deletions
168
...data-designer-engine/src/data_designer/engine/dataset_builders/utils/async_concurrency.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import logging | ||
| import threading | ||
| from collections.abc import Coroutine | ||
| from dataclasses import dataclass | ||
| from typing import Any, Generic, TypeVar | ||
|
|
||
| from data_designer.engine.dataset_builders.utils.concurrency import ( | ||
| CallbackWithContext, | ||
| ErrorCallbackWithContext, | ||
| ExecutorResults, | ||
| ) | ||
| from data_designer.engine.errors import DataDesignerRuntimeError | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| T = TypeVar("T") | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class Success(Generic[T]): | ||
| index: int | ||
| value: T | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class Failure: | ||
| index: int | ||
| error: Exception | ||
|
|
||
|
|
||
| TaskResult = Success[T] | Failure | ||
|
|
||
| _loop: asyncio.AbstractEventLoop | None = None | ||
| _thread: threading.Thread | None = None | ||
| _lock = threading.Lock() | ||
|
|
||
|
|
||
| def _run_loop(loop: asyncio.AbstractEventLoop) -> None: | ||
| asyncio.set_event_loop(loop) | ||
| loop.run_forever() | ||
|
|
||
|
|
||
| def _ensure_async_engine_loop() -> asyncio.AbstractEventLoop: | ||
| """Get or create a persistent event loop for async engine work. | ||
|
|
||
| A single event loop is shared across all AsyncConcurrentExecutor instances | ||
| to avoid breaking libraries (like LiteLLM) that bind internal async state | ||
| to a specific event loop. | ||
| """ | ||
| global _loop, _thread | ||
| with _lock: | ||
| if _loop is None or not _loop.is_running(): | ||
| _loop = asyncio.new_event_loop() | ||
| _thread = threading.Thread(target=_run_loop, args=(_loop,), daemon=True, name="AsyncEngine-EventLoop") | ||
| _thread.start() | ||
| return _loop | ||
|
|
||
|
|
||
| class AsyncConcurrentExecutor: | ||
| """Async equivalent of ConcurrentThreadExecutor. | ||
|
|
||
| Executes a batch of coroutines with bounded concurrency, error rate | ||
| monitoring, and early shutdown semantics. Callers remain synchronous — | ||
| the ``run()`` method submits work to a persistent background event loop. | ||
|
|
||
| No locks are needed because asyncio tasks run cooperatively on a | ||
| single thread — mutations to ``_results`` are always sequential. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| max_workers: int, | ||
| column_name: str, | ||
| result_callback: CallbackWithContext | None = None, | ||
| error_callback: ErrorCallbackWithContext | None = None, | ||
| shutdown_error_rate: float = 0.50, | ||
| shutdown_error_window: int = 10, | ||
| disable_early_shutdown: bool = False, | ||
| ) -> None: | ||
| self._column_name = column_name | ||
| self._max_workers = max_workers | ||
| self._result_callback = result_callback | ||
| self._error_callback = error_callback | ||
| self._shutdown_error_rate = shutdown_error_rate | ||
| self._shutdown_window_size = shutdown_error_window | ||
| self._disable_early_shutdown = disable_early_shutdown | ||
| self._results = ExecutorResults(failure_threshold=shutdown_error_rate) | ||
|
|
||
| @property | ||
| def results(self) -> ExecutorResults: | ||
| return self._results | ||
|
|
||
| @property | ||
| def max_workers(self) -> int: | ||
| return self._max_workers | ||
|
|
||
| @property | ||
| def shutdown_error_rate(self) -> float: | ||
| return self._shutdown_error_rate | ||
|
|
||
| @property | ||
| def shutdown_window_size(self) -> int: | ||
| return self._shutdown_window_size | ||
|
|
||
| def run(self, work_items: list[tuple[Coroutine[Any, Any, Any], dict | None]]) -> None: | ||
| """Execute all work items concurrently. Callers remain synchronous.""" | ||
| logger.debug( | ||
| f"AsyncConcurrentExecutor: launching {len(work_items)} tasks " | ||
| f"with max_workers={self._max_workers} for column '{self._column_name}'" | ||
| ) | ||
| loop = _ensure_async_engine_loop() | ||
| future = asyncio.run_coroutine_threadsafe(self._run_all(work_items), loop) | ||
| future.result() | ||
|
|
||
| async def _run_all(self, work_items: list[tuple[Coroutine[Any, Any, Any], dict | None]]) -> None: | ||
| self._semaphore = asyncio.Semaphore(self._max_workers) | ||
| self._shutdown_event = asyncio.Event() | ||
|
|
||
| async with asyncio.TaskGroup() as tg: | ||
| for i, (coro, context) in enumerate(work_items): | ||
| tg.create_task(self._run_task(i, coro, context)) | ||
|
|
||
| if not self._disable_early_shutdown and self._results.early_shutdown: | ||
| self._raise_task_error() | ||
|
|
||
| async def _run_task(self, index: int, coro: Coroutine[Any, Any, Any], context: dict | None) -> None: | ||
| if self._shutdown_event.is_set(): | ||
| return | ||
|
|
||
| async with self._semaphore: | ||
| if self._shutdown_event.is_set(): | ||
| return | ||
|
|
||
| try: | ||
| result = await coro | ||
| self._results.completed_count += 1 | ||
| self._results.success_count += 1 | ||
| if self._result_callback is not None: | ||
| self._result_callback(result, context=context) | ||
| except Exception as err: | ||
| self._results.completed_count += 1 | ||
| self._results.error_trap.handle_error(err) | ||
| if not self._disable_early_shutdown and self._results.is_error_rate_exceeded( | ||
| self._shutdown_window_size | ||
| ): | ||
| if not self._results.early_shutdown: | ||
| self._results.early_shutdown = True | ||
| self._shutdown_event.set() | ||
| if self._error_callback is not None: | ||
| self._error_callback(err, context=context) | ||
|
|
||
| def _raise_task_error(self) -> None: | ||
| raise DataDesignerRuntimeError( | ||
| "\n".join( | ||
| [ | ||
| " |-- Data generation was terminated early due to error rate exceeding threshold.", | ||
| f" |-- The summary of encountered errors is: \n{json.dumps(self._results.summary, indent=4)}", | ||
| ] | ||
| ) | ||
| ) |
25 changes: 25 additions & 0 deletions
25
packages/data-designer-engine/src/data_designer/engine/models/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,27 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
| _ASYNC_ENGINE_ENV_VAR = "DATA_DESIGNER_ASYNC_ENGINE" | ||
| _TRUTHY_ENV_VALUES = {"1", "true", "yes"} | ||
|
|
||
|
|
||
| def _is_async_engine_enabled() -> bool: | ||
| return os.getenv(_ASYNC_ENGINE_ENV_VAR, "").lower() in _TRUTHY_ENV_VALUES | ||
|
|
||
|
|
||
| def _redirect_to_models_v2() -> None: | ||
| models_v2_path = Path(__file__).resolve().parent.parent / "models_v2" | ||
| # Set DATA_DESIGNER_ASYNC_ENGINE before importing this package for it to take effect. | ||
| global __path__ | ||
| __path__ = [str(models_v2_path)] | ||
| if __spec__ is not None: | ||
| __spec__.submodule_search_locations = [str(models_v2_path)] | ||
|
|
||
|
|
||
| if __name__ == "data_designer.engine.models" and _is_async_engine_enabled(): | ||
| _redirect_to_models_v2() |
2 changes: 2 additions & 0 deletions
2
packages/data-designer-engine/src/data_designer/engine/models_v2/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we put this in
plans/{gh-issue}/?