-
Notifications
You must be signed in to change notification settings - Fork 1
Isolate Cloud AI local-file offloads from default executor #1735
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
99f6a3c
Initial plan
Copilot 4322629
fix: isolate cloud ai local file reads to dedicated io pool
Copilot e551419
fix: harden cloud ai io worker env parsing
Copilot a8be54f
Merge branch 'main' into copilot/fix-shared-default-executor-leak
groupthinking 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
81 changes: 81 additions & 0 deletions
81
src/youtube_extension/integrations/cloud_ai/blocking_io.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,81 @@ | ||
| """Dedicated executor for potentially blocking Cloud AI local file I/O.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
| import threading | ||
| from concurrent.futures import ThreadPoolExecutor | ||
| from typing import Any, Callable, TypeVar | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _T = TypeVar("_T") | ||
| _DEFAULT_IO_WORKERS = max(1, min(8, (os.cpu_count() or 1))) | ||
|
|
||
|
|
||
| def _io_max_workers_from_env() -> int: | ||
| raw = os.environ.get("CLOUD_AI_IO_MAX_WORKERS") | ||
| if raw is None or not raw.strip(): | ||
| return _DEFAULT_IO_WORKERS | ||
| try: | ||
| return max(1, int(raw)) | ||
| except ValueError: | ||
| logger.warning( | ||
| "Invalid CLOUD_AI_IO_MAX_WORKERS=%r; using default=%d", | ||
| raw, | ||
| _DEFAULT_IO_WORKERS, | ||
| ) | ||
| return _DEFAULT_IO_WORKERS | ||
|
|
||
|
|
||
| _IO_MAX_WORKERS = _io_max_workers_from_env() | ||
| _IO_EXECUTOR = ThreadPoolExecutor( | ||
| max_workers=_IO_MAX_WORKERS, | ||
| thread_name_prefix="cloud-ai-io", | ||
| ) | ||
| _IO_ACTIVE = 0 | ||
| _IO_QUEUED = 0 | ||
| _IO_STATE_LOCK = threading.Lock() | ||
|
|
||
|
|
||
| def _log_pool_pressure(*, active: int, queued: int) -> None: | ||
| if active + queued < _IO_MAX_WORKERS: | ||
| return | ||
| logger.warning( | ||
| "blocking_io_pool_near_capacity active=%d queued=%d max_workers=%d", | ||
| active, | ||
| queued, | ||
| _IO_MAX_WORKERS, | ||
| ) | ||
|
|
||
|
|
||
| async def run_blocking( | ||
| func: Callable[..., _T], *args: Any, timeout: float | None = None, **kwargs: Any | ||
| ) -> _T: | ||
| """Run blocking work on the Cloud AI local-I/O pool.""" | ||
| loop = asyncio.get_running_loop() | ||
|
|
||
| with _IO_STATE_LOCK: | ||
| global _IO_QUEUED | ||
| _IO_QUEUED += 1 | ||
| active = _IO_ACTIVE | ||
| queued = _IO_QUEUED | ||
| _log_pool_pressure(active=active, queued=queued) | ||
|
|
||
| def _invoke() -> _T: | ||
| global _IO_ACTIVE, _IO_QUEUED | ||
| with _IO_STATE_LOCK: | ||
| _IO_QUEUED -= 1 | ||
| _IO_ACTIVE += 1 | ||
| try: | ||
| return func(*args, **kwargs) | ||
| finally: | ||
| with _IO_STATE_LOCK: | ||
| _IO_ACTIVE -= 1 | ||
|
|
||
| future = loop.run_in_executor(_IO_EXECUTOR, _invoke) | ||
| if timeout is None: | ||
| return await future | ||
| return await asyncio.wait_for(future, timeout=timeout) | ||
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import sys | ||
| import threading | ||
| from concurrent.futures import ThreadPoolExecutor | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| _SRC = Path(__file__).resolve().parents[2] / "src" | ||
| sys.path.insert(0, str(_SRC)) | ||
|
|
||
| import youtube_extension.integrations.cloud_ai.blocking_io as blocking_io | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def isolated_pool(monkeypatch): | ||
| original_executor = blocking_io._IO_EXECUTOR | ||
| original_limit = blocking_io._IO_MAX_WORKERS | ||
| gate = threading.Event() | ||
| executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cloud-ai-io") | ||
| monkeypatch.setattr(blocking_io, "_IO_EXECUTOR", executor) | ||
| monkeypatch.setattr(blocking_io, "_IO_MAX_WORKERS", 1) | ||
| try: | ||
| yield gate | ||
| finally: | ||
| gate.set() | ||
| executor.shutdown(wait=True) | ||
| monkeypatch.setattr(blocking_io, "_IO_EXECUTOR", original_executor) | ||
| monkeypatch.setattr(blocking_io, "_IO_MAX_WORKERS", original_limit) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_saturated_io_pool_does_not_starve_default_to_thread(isolated_pool): | ||
| entered = threading.Event() | ||
|
|
||
| def blocker(): | ||
| entered.set() | ||
| isolated_pool.wait() | ||
| return "released" | ||
|
|
||
| first = asyncio.create_task(blocking_io.run_blocking(blocker, timeout=0.05)) | ||
| await asyncio.wait_for(asyncio.to_thread(entered.wait, 1), timeout=1) | ||
| second = asyncio.create_task(blocking_io.run_blocking(blocker, timeout=0.05)) | ||
|
|
||
| with pytest.raises(asyncio.TimeoutError): | ||
| await first | ||
| with pytest.raises(asyncio.TimeoutError): | ||
| await second | ||
|
|
||
| result = await asyncio.wait_for(asyncio.to_thread(lambda: "default-ok"), timeout=0.5) | ||
| assert result == "default-ok" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_logs_warning_when_io_pool_is_at_capacity(isolated_pool, caplog): | ||
| entered = threading.Event() | ||
|
|
||
| def blocker(): | ||
| entered.set() | ||
| isolated_pool.wait() | ||
| return "released" | ||
|
|
||
| with caplog.at_level(logging.WARNING): | ||
| first = asyncio.create_task(blocking_io.run_blocking(blocker, timeout=0.05)) | ||
| await asyncio.wait_for(asyncio.to_thread(entered.wait, 1), timeout=1) | ||
| second = asyncio.create_task(blocking_io.run_blocking(blocker, timeout=0.05)) | ||
|
|
||
| with pytest.raises(asyncio.TimeoutError): | ||
| await first | ||
| with pytest.raises(asyncio.TimeoutError): | ||
| await second | ||
|
|
||
| assert any( | ||
| "blocking_io_pool_near_capacity" in record.getMessage() for record in caplog.records | ||
| ) |
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
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
_IO_QUEUEDcounter permanently leaks by 1 whenever a queued blocking-I/O work item is cancelled (viatimeoutor task cancellation) before it starts running.