-
Notifications
You must be signed in to change notification settings - Fork 39
Add opt-in upstream pooling and account capacity limits #29
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
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
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,156 @@ | ||
| """Own bounded upstream clients and account capacity for each inference request.""" | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from contextlib import asynccontextmanager | ||
| from contextvars import ContextVar | ||
| from http.cookiejar import CookieJar, DefaultCookiePolicy | ||
| import threading | ||
|
|
||
| import httpx | ||
|
|
||
| from app.site_routing import PROFILE_ENDPOINTS | ||
|
|
||
|
|
||
| class _RejectCookies(DefaultCookiePolicy): | ||
| def set_ok(self, cookie, request): | ||
| return False | ||
|
|
||
| def return_ok(self, cookie, request): | ||
| return False | ||
|
|
||
|
|
||
| class UpstreamClients: | ||
| """Keep at most one cookie-free HTTP/1.1 client per trusted origin and event loop.""" | ||
|
|
||
| def __init__(self): | ||
| self._clients = {} | ||
| self._loop = asyncio.get_running_loop() | ||
| self._closed = False | ||
| self._origins = {self._origin(url) for url in PROFILE_ENDPOINTS.values()} | ||
|
|
||
| @staticmethod | ||
| def _origin(url): | ||
| value = httpx.URL(url) | ||
| return value.scheme, value.host, value.port | ||
|
|
||
| def get(self, url): | ||
| origin = self._origin(url) | ||
| if self._closed or asyncio.get_running_loop() is not self._loop or origin not in self._origins: | ||
| return None | ||
| if origin not in self._clients: | ||
| self._clients[origin] = httpx.AsyncClient( | ||
| cookies=CookieJar(policy=_RejectCookies()), http2=False, | ||
| limits=httpx.Limits(max_connections=64, max_keepalive_connections=16, keepalive_expiry=30)) | ||
| return self._clients[origin] | ||
|
|
||
| async def aclose(self): | ||
| self._closed = True | ||
| clients, self._clients = list(self._clients.values()), {} | ||
| results = await asyncio.gather(*(client.aclose() for client in clients), return_exceptions=True) | ||
| errors = [result for result in results if isinstance(result, BaseException)] | ||
| if errors: | ||
| raise BaseExceptionGroup("Upstream client shutdown failed", errors) | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def inference_lifespan(app): | ||
| clients = UpstreamClients() | ||
| try: | ||
| yield {"upstream_clients": clients} | ||
| finally: | ||
| await clients.aclose() | ||
|
|
||
|
|
||
| class CredentialLease(tuple): | ||
| """Retain the existing (manager, generation) lease shape with idempotent capacity release.""" | ||
|
|
||
| def __new__(cls, manager, generation, release): | ||
| lease = super().__new__(cls, (manager, generation)) | ||
| lease._release = release | ||
| lease._lock = threading.Lock() | ||
| return lease | ||
|
|
||
| def release(self): | ||
| with self._lock: | ||
| release, self._release = self._release, None | ||
| if release is not None: | ||
| release() | ||
|
|
||
|
|
||
| def release_credential(credential): | ||
| if isinstance(credential, CredentialLease): | ||
| credential.release() | ||
|
|
||
|
|
||
| class AccountCapacity: | ||
| """Count account leases independently of credential I/O locks.""" | ||
|
|
||
| def __init__(self): | ||
| self._lock = threading.Lock() | ||
| self._counts = {} | ||
|
|
||
| def count(self, identity): | ||
| with self._lock: | ||
| return self._counts.get(identity, 0) | ||
|
|
||
| def acquire(self, identity, limit, manager, generation): | ||
| with self._lock: | ||
| count = self._counts.get(identity, 0) | ||
| if limit and count >= limit: | ||
| return None | ||
| self._counts[identity] = count + 1 | ||
| return CredentialLease(manager, generation, lambda: self._release(identity)) | ||
|
|
||
| def _release(self, identity): | ||
| with self._lock: | ||
| count = self._counts[identity] - 1 | ||
| if count: | ||
| self._counts[identity] = count | ||
| else: | ||
| del self._counts[identity] | ||
|
|
||
|
|
||
| class RequestResources: | ||
| """Release even leases acquired by a worker after its request has already closed.""" | ||
|
|
||
| def __init__(self, clients=None): | ||
| self.clients = clients | ||
| self._lock = threading.Lock() | ||
| self._leases = [] | ||
| self._closed = False | ||
|
|
||
| def add(self, lease): | ||
| with self._lock: | ||
| if not self._closed: | ||
| self._leases.append(lease) | ||
| return | ||
| release_credential(lease) | ||
| raise asyncio.CancelledError() | ||
|
|
||
| def close(self): | ||
| with self._lock: | ||
| self._closed = True | ||
| leases, self._leases = self._leases, [] | ||
| for lease in leases: | ||
| release_credential(lease) | ||
|
|
||
|
|
||
| request_resources = ContextVar("inference_resources", default=None) | ||
|
|
||
|
|
||
| class InferenceResourcesMiddleware: | ||
| def __init__(self, app): | ||
| self.app = app | ||
|
|
||
| async def __call__(self, scope, receive, send): | ||
| if (scope["type"] != "http" or scope.get("method") != "POST" or | ||
| scope.get("path") not in ("/v1/chat/completions", "/v1/responses", "/v1/messages")): | ||
| return await self.app(scope, receive, send) | ||
| resources = RequestResources(scope.get("state", {}).get("upstream_clients")) | ||
| token = request_resources.set(resources) | ||
| try: | ||
| await self.app(scope, receive, send) | ||
| finally: | ||
| resources.close() | ||
| request_resources.reset(token) |
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
Oops, something went wrong.
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.
nitpick: .env.example is not updated with CODEBUDDY2API_UPSTREAM_KEEPALIVE or CODEBUDDY2API_MAX_INFLIGHT_PER_ACCOUNT, so the environment template does not document the two newly exposed runtime settings despite the PR claiming the template is synchronized.
Triggers: When operators configure the service from the supplied environment template.
Suggested fix: Add both environment variables, with their false/0 defaults, to
.env.example.