mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 04:59:37 +08:00
* fix(llm): close an evicted pooled provider on the loop that owns it The runtime provider pool is keyed per event loop and shared by the server loop and synchronous callers that run asyncio.run() in a worker thread, such as the exam question extractor. Two cross-loop problems followed: - When a worker loop's lookup evicted a server-loop client, the client's aclose() was scheduled on the worker loop. It ran on the wrong thread, or never ran when asyncio.run() cancelled it on exit. For Claude Code this tears down the server loop's persistent CLI sessions from a foreign thread. - Every finished worker loop left its entry behind. With a pool of two, that stale entry could push the server loop's live client out, discarding warm CLI sessions. Each entry now records its loop. Evictions close on that loop: directly when it is the running loop, otherwise through run_coroutine_threadsafe. Entries whose loop is closed are dropped before a new client is added. Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com> * fix(llm): close every retired pooled provider on its own loop close_runtime_provider_pool() awaited aclose() of every pooled client on the caller's loop, and reset_runtime_provider_pool() scheduled them on the caller's loop or ran each on a fresh asyncio.run() loop. A client built on another loop, such as a long-lived worker loop, was therefore closed on a loop that does not own its sockets or tasks. The bulk paths now keep each retired entry's loop. close awaits only the clients owned by the current loop and hands the rest to their owner loop; reset routes every client through the same owner-loop close. The final release of a leased client also uses the entry's recorded loop. Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com> * fix(llm): create a cross-loop close coroutine on the owner loop run_coroutine_threadsafe() builds the close coroutine on the calling thread. When the owner loop is stopped but not yet closed and never runs again, that coroutine is dropped unawaited and Python warns "coroutine was never awaited". Schedule a callback instead that creates the close task on the owner loop, so a loop that never runs again leaves nothing behind. A closed loop rejects the callback, which also replaces the separate is_closed() check. Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com> --------- Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
311 lines
11 KiB
Python
311 lines
11 KiB
Python
"""Factory for services-layer provider runtime objects."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections import OrderedDict
|
|
from collections.abc import Iterator
|
|
import contextlib
|
|
from dataclasses import dataclass
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import threading
|
|
from typing import Any
|
|
|
|
from deeptutor.services.llm.config import LLMConfig, get_llm_config
|
|
from deeptutor.services.llm.provider_core.base import GenerationSettings, LLMProvider
|
|
from deeptutor.services.provider_registry import effective_backend, find_by_name
|
|
|
|
_PROVIDER_POOL_MAXSIZE = 2
|
|
|
|
|
|
@dataclass
|
|
class _ProviderEntry:
|
|
provider: LLMProvider
|
|
loop: asyncio.AbstractEventLoop
|
|
users: int = 0
|
|
retired: bool = False
|
|
|
|
|
|
_provider_pool: "OrderedDict[tuple[Any, ...], _ProviderEntry]" = OrderedDict()
|
|
_provider_pool_lock = threading.RLock()
|
|
|
|
|
|
def _secret_fingerprint(value: str | list[str] | None) -> str:
|
|
if not value:
|
|
return ""
|
|
serialized = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
|
return hashlib.sha256(serialized.encode("utf-8")).hexdigest()[:16]
|
|
|
|
|
|
def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> tuple[Any, ...]:
|
|
headers = json.dumps(config.extra_headers or {}, sort_keys=True, separators=(",", ":"))
|
|
owner_identity = ""
|
|
spec = find_by_name(config.provider_name or config.binding)
|
|
if spec and spec.backend == "github_copilot":
|
|
from deeptutor.services.github_copilot_storage import get_github_copilot_storage
|
|
|
|
owner_identity = str(get_github_copilot_storage().credentials_path)
|
|
return (
|
|
loop,
|
|
os.getenv("DEEPTUTOR_CHAT_ENGINE", "python"),
|
|
config.provider_name or config.binding,
|
|
config.provider_mode,
|
|
config.model,
|
|
_secret_fingerprint(config.api_key),
|
|
config.effective_url or config.base_url or "",
|
|
config.api_version or "",
|
|
headers,
|
|
config.wire_api,
|
|
config.api_format,
|
|
config.temperature,
|
|
config.max_tokens,
|
|
config.reasoning_effort,
|
|
config.max_concurrency,
|
|
config.requests_per_minute,
|
|
owner_identity,
|
|
)
|
|
|
|
|
|
def _build_runtime_provider(
|
|
llm_config: LLMConfig,
|
|
*,
|
|
configure_env: bool = True,
|
|
native_enabled: bool = True,
|
|
) -> LLMProvider:
|
|
"""Construct one provider, importing only the selected backend SDK."""
|
|
provider_name = llm_config.provider_name or llm_config.binding
|
|
api_key = llm_config.get_api_key()
|
|
spec = find_by_name(provider_name)
|
|
backend = effective_backend(spec, llm_config.api_format)
|
|
if backend == "openai_compat" and provider_name == "openai" and llm_config.api_version:
|
|
# An OpenAI profile carrying an api_version is an Azure deployment typed
|
|
# under the generic vendor. The agentic client has always sent those to
|
|
# the Azure SDK; the services path must make the same call.
|
|
backend = "azure_openai"
|
|
|
|
native = False
|
|
if native_enabled and os.getenv("DEEPTUTOR_CHAT_ENGINE") == "typescript-native":
|
|
from deeptutor.runtime.ts_engine.config import compatibility_reason
|
|
|
|
native = not compatibility_reason(llm_config)
|
|
# These profiles attach SDK-specific prompt caching or model rewrites.
|
|
if spec and (spec.supports_prompt_caching or spec.strip_model_prefix):
|
|
native = False
|
|
provider: LLMProvider
|
|
if native:
|
|
from deeptutor.services.llm.provider_core.typescript_provider import TypeScriptProvider
|
|
|
|
provider = TypeScriptProvider(llm_config)
|
|
elif backend == "openai_codex":
|
|
from deeptutor.services.llm.provider_core.openai_codex_provider import (
|
|
OpenAICodexProvider,
|
|
)
|
|
|
|
provider = OpenAICodexProvider(
|
|
default_model=llm_config.model, extra_headers=llm_config.extra_headers
|
|
)
|
|
elif backend == "github_copilot":
|
|
from deeptutor.services.llm.provider_core.github_copilot_provider import (
|
|
GitHubCopilotProvider,
|
|
)
|
|
|
|
provider = GitHubCopilotProvider(
|
|
default_model=llm_config.model,
|
|
configure_env=configure_env,
|
|
)
|
|
elif backend == "codebuddy":
|
|
from deeptutor.services.llm.provider_core.codebuddy_http_provider import (
|
|
build_codebuddy_provider,
|
|
)
|
|
|
|
provider = build_codebuddy_provider(
|
|
api_key=api_key or None,
|
|
default_model=llm_config.model,
|
|
configure_env=configure_env,
|
|
)
|
|
elif backend == "claude_code":
|
|
from deeptutor.services.llm.provider_core.claude_code_provider import ClaudeCodeProvider
|
|
|
|
provider = ClaudeCodeProvider(default_model=llm_config.model)
|
|
elif backend == "azure_openai":
|
|
from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider
|
|
|
|
provider = AzureOpenAIProvider(
|
|
api_key=api_key,
|
|
api_base=llm_config.effective_url or llm_config.base_url or "",
|
|
default_model=llm_config.model,
|
|
extra_headers=llm_config.extra_headers or None,
|
|
api_version=llm_config.api_version,
|
|
)
|
|
elif backend == "anthropic":
|
|
from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider
|
|
|
|
provider = AnthropicProvider(
|
|
api_key=api_key or None,
|
|
api_base=llm_config.effective_url or llm_config.base_url or None,
|
|
default_model=llm_config.model,
|
|
extra_headers=llm_config.extra_headers or None,
|
|
supports_prompt_caching=bool(spec and spec.supports_prompt_caching),
|
|
binding=spec.name if spec else llm_config.binding,
|
|
)
|
|
else:
|
|
from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider
|
|
|
|
provider = OpenAICompatProvider(
|
|
api_key=llm_config.api_key or None,
|
|
api_base=llm_config.effective_url or llm_config.base_url or None,
|
|
default_model=llm_config.model,
|
|
extra_headers=llm_config.extra_headers or None,
|
|
spec=spec,
|
|
provider_name=provider_name,
|
|
wire_api=llm_config.wire_api,
|
|
configure_env=configure_env,
|
|
)
|
|
|
|
provider.generation = GenerationSettings(
|
|
temperature=llm_config.temperature,
|
|
max_tokens=llm_config.max_tokens,
|
|
reasoning_effort=llm_config.reasoning_effort,
|
|
)
|
|
return provider
|
|
|
|
|
|
def build_isolated_provider(config: LLMConfig) -> LLMProvider:
|
|
"""Build an unpooled provider without mutating process-global provider env."""
|
|
return _build_runtime_provider(config, configure_env=False)
|
|
|
|
|
|
def _schedule_close(provider: LLMProvider, loop: asyncio.AbstractEventLoop) -> None:
|
|
"""Close *provider* on *loop*, the loop whose tasks and sockets it owns.
|
|
|
|
A worker thread running its own loop (``asyncio.run``) shares this pool, so
|
|
the closing caller may be on another thread. A closed loop has nothing left
|
|
to await on; its client is simply dropped. The close coroutine is created
|
|
on *loop* itself, so a loop that never runs again leaves none unawaited.
|
|
"""
|
|
|
|
async def _close() -> None:
|
|
with contextlib.suppress(Exception):
|
|
await provider.aclose()
|
|
|
|
try:
|
|
running = asyncio.get_running_loop()
|
|
except RuntimeError:
|
|
running = None
|
|
if running is loop:
|
|
loop.create_task(_close())
|
|
return
|
|
with contextlib.suppress(RuntimeError): # the loop is (or just got) closed
|
|
loop.call_soon_threadsafe(lambda: loop.create_task(_close()))
|
|
|
|
|
|
def get_runtime_provider(config: LLMConfig | None = None) -> LLMProvider:
|
|
"""Return a small event-loop-local pool entry for the supplied config.
|
|
|
|
A provider owns an SDK HTTP connection pool. Recreating it for every token
|
|
request steadily raises the process high-water mark and forfeits keep-alive.
|
|
Calls made outside an event loop remain uncached for cross-loop safety.
|
|
Request execution should use ``acquire_runtime_provider`` to keep the
|
|
client alive across awaits, even when its cache entry is evicted.
|
|
"""
|
|
llm_config = config or get_llm_config()
|
|
try:
|
|
loop = asyncio.get_running_loop()
|
|
except RuntimeError:
|
|
return _build_runtime_provider(llm_config)
|
|
|
|
with _provider_pool_lock:
|
|
return _get_runtime_entry(llm_config, loop).provider
|
|
|
|
|
|
def _get_runtime_entry(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> _ProviderEntry:
|
|
"""Look up an entry while holding ``_provider_pool_lock``."""
|
|
key = _provider_cache_key(config, loop)
|
|
cached = _provider_pool.get(key)
|
|
if cached is not None:
|
|
_provider_pool.move_to_end(key)
|
|
return cached
|
|
|
|
# Entries of loops that have finished (each ``asyncio.run`` in a worker
|
|
# thread leaves one) must not push live clients out of the pool.
|
|
for stale_key in [k for k, item in _provider_pool.items() if item.loop.is_closed()]:
|
|
_provider_pool.pop(stale_key).retired = True
|
|
|
|
entry = _ProviderEntry(_build_runtime_provider(config), loop)
|
|
_provider_pool[key] = entry
|
|
while len(_provider_pool) > _PROVIDER_POOL_MAXSIZE:
|
|
_, evicted = _provider_pool.popitem(last=False)
|
|
evicted.retired = True
|
|
if not evicted.users:
|
|
_schedule_close(evicted.provider, evicted.loop)
|
|
return entry
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def acquire_runtime_provider(config: LLMConfig | None = None) -> Iterator[LLMProvider]:
|
|
"""Lease a pooled client for the entire request, including retries.
|
|
|
|
Retirement removes the cache entry immediately; the last request releases
|
|
its client on success, error, or cancellation. Idle cached clients remain
|
|
bounded, while active requests may temporarily retain retired clients.
|
|
"""
|
|
loop = asyncio.get_running_loop()
|
|
llm_config = config or get_llm_config()
|
|
with _provider_pool_lock:
|
|
entry = _get_runtime_entry(llm_config, loop)
|
|
entry.users += 1
|
|
try:
|
|
yield entry.provider
|
|
finally:
|
|
with _provider_pool_lock:
|
|
entry.users -= 1
|
|
if entry.retired and not entry.users:
|
|
_schedule_close(entry.provider, entry.loop)
|
|
|
|
|
|
def _retire_runtime_provider_pool() -> list[_ProviderEntry]:
|
|
"""Remove all entries and return only those safe to close immediately."""
|
|
with _provider_pool_lock:
|
|
entries = list(_provider_pool.values())
|
|
_provider_pool.clear()
|
|
for entry in entries:
|
|
entry.retired = True
|
|
return [entry for entry in entries if not entry.users]
|
|
|
|
|
|
async def close_runtime_provider_pool() -> None:
|
|
"""Retire pooled clients; active requests close theirs on final release."""
|
|
loop = asyncio.get_running_loop()
|
|
owned = []
|
|
for entry in _retire_runtime_provider_pool():
|
|
if entry.loop is loop:
|
|
owned.append(entry.provider.aclose())
|
|
else:
|
|
_schedule_close(entry.provider, entry.loop)
|
|
if owned:
|
|
await asyncio.gather(*owned, return_exceptions=True)
|
|
|
|
|
|
def reset_runtime_provider_pool() -> None:
|
|
"""Clear the pool from synchronous cache-invalidation call sites."""
|
|
for entry in _retire_runtime_provider_pool():
|
|
_schedule_close(entry.provider, entry.loop)
|
|
|
|
|
|
def runtime_provider_pool_size() -> int:
|
|
"""Expose the bounded size for diagnostics and regression tests."""
|
|
with _provider_pool_lock:
|
|
return len(_provider_pool)
|
|
|
|
|
|
__all__ = [
|
|
"acquire_runtime_provider",
|
|
"build_isolated_provider",
|
|
"close_runtime_provider_pool",
|
|
"get_runtime_provider",
|
|
"reset_runtime_provider_pool",
|
|
"runtime_provider_pool_size",
|
|
]
|