-
Notifications
You must be signed in to change notification settings - Fork 176
feat(BA-6155): add metadata-driven chunk-store upload session engine #11766
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
jopemachine
wants to merge
1
commit into
main
Choose a base branch
from
fix/BA-6155-tus-upload-session-class
base: main
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Introduce `TusUploadSession`, a concurrency-safe upload engine for resumable (TUS) uploads that keeps session metadata and a per-session lock in Valkey (via `ValkeyTusClient`) while storing chunk payloads on the shared filesystem, so multiple storage-proxy replicas can accept chunks without corruption and without relying on filesystem lock semantics. |
5 changes: 5 additions & 0 deletions
5
src/ai/backend/common/clients/valkey_client/valkey_tus/__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,5 @@ | ||
| """Valkey client for TUS resumable-upload session metadata.""" | ||
|
|
||
| from .client import ValkeyTusClient | ||
|
|
||
| __all__ = ["ValkeyTusClient"] |
116 changes: 116 additions & 0 deletions
116
src/ai/backend/common/clients/valkey_client/valkey_tus/client.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,116 @@ | ||
| """ | ||
| Valkey client for TUS resumable-upload sessions. | ||
|
|
||
| Stores per-session upload metadata (the source of truth) on the Glide-based | ||
| valkey connection so that multiple Storage Proxy replicas share one view of an | ||
| upload's progress without relying on shared-filesystem semantics. This client is | ||
| metadata-only; the per-session distributed lock that serializes the | ||
| read-modify-write window is a separate :class:`DistributedLockFactory` resource | ||
| (see :mod:`ai.backend.storage.services.upload.tus_session`). The payload bytes | ||
| stay on the shared filesystem; only this small metadata lives in Valkey. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from typing import Final, Self | ||
|
|
||
| from glide import ExpirySet, ExpiryType | ||
|
|
||
| from ai.backend.common.clients.valkey_client.client import ( | ||
| AbstractValkeyClient, | ||
| create_valkey_client, | ||
| ) | ||
| from ai.backend.common.exception import BackendAIError | ||
| from ai.backend.common.metrics.metric import DomainType, LayerType | ||
| from ai.backend.common.resilience import ( | ||
| BackoffStrategy, | ||
| MetricArgs, | ||
| MetricPolicy, | ||
| Resilience, | ||
| RetryArgs, | ||
| RetryPolicy, | ||
| ) | ||
| from ai.backend.common.types import TusSessionId, ValkeyTarget | ||
| from ai.backend.logging import BraceStyleAdapter | ||
|
|
||
| log = BraceStyleAdapter(logging.getLogger(__spec__.name)) | ||
|
|
||
| valkey_tus_resilience = Resilience( | ||
| policies=[ | ||
| MetricPolicy(MetricArgs(domain=DomainType.VALKEY, layer=LayerType.VALKEY_TUS)), | ||
| RetryPolicy( | ||
| RetryArgs( | ||
| max_retries=3, | ||
| retry_delay=0.1, | ||
| backoff_strategy=BackoffStrategy.FIXED, | ||
| non_retryable_exceptions=(BackendAIError,), | ||
| ) | ||
| ), | ||
| ] | ||
| ) | ||
|
|
||
| _STATE_KEY_PREFIX: Final = "tus.upload.session" # tus.upload.session:{session_id} | ||
|
|
||
| # Stale (never-completed / abandoned) sessions are reclaimed by this TTL, so no | ||
| # separate GC sweep is needed. | ||
| _DEFAULT_STATE_TTL_SECONDS: Final = 24 * 60 * 60 | ||
|
|
||
|
|
||
| class ValkeyTusClient: | ||
| """Valkey-backed metadata store for TUS uploads.""" | ||
|
|
||
| _client: AbstractValkeyClient | ||
|
|
||
| def __init__(self, client: AbstractValkeyClient) -> None: | ||
| self._client = client | ||
|
|
||
| @classmethod | ||
| async def create( | ||
| cls, | ||
| valkey_target: ValkeyTarget, | ||
| *, | ||
| db_id: int, | ||
| human_readable_name: str, | ||
| ) -> Self: | ||
| client = create_valkey_client( | ||
| valkey_target=valkey_target, | ||
| db_id=db_id, | ||
| human_readable_name=human_readable_name, | ||
| ) | ||
| await client.connect() | ||
| return cls(client=client) | ||
|
|
||
| @valkey_tus_resilience.apply() | ||
| async def close(self) -> None: | ||
| await self._client.disconnect() | ||
|
|
||
| @staticmethod | ||
| def _state_key(session_id: TusSessionId) -> str: | ||
| return f"{_STATE_KEY_PREFIX}:{session_id}" | ||
|
|
||
| @valkey_tus_resilience.apply() | ||
| async def get_session_state(self, session_id: TusSessionId) -> bytes | None: | ||
| """Return the raw serialized session state, or ``None`` if absent.""" | ||
| async with self._client.client() as conn: | ||
| return await conn.get(self._state_key(session_id)) | ||
|
|
||
| @valkey_tus_resilience.apply() | ||
| async def set_session_state( | ||
| self, | ||
| session_id: TusSessionId, | ||
| payload: str | bytes, | ||
| *, | ||
| ttl_seconds: int = _DEFAULT_STATE_TTL_SECONDS, | ||
| ) -> None: | ||
| async with self._client.client() as conn: | ||
| await conn.set( | ||
| self._state_key(session_id), | ||
| payload, | ||
| expiry=ExpirySet(ExpiryType.SEC, ttl_seconds), | ||
| ) | ||
|
|
||
| @valkey_tus_resilience.apply() | ||
| async def delete_session_state(self, session_id: TusSessionId) -> None: | ||
| async with self._client.client() as conn: | ||
| await conn.delete([self._state_key(session_id)]) |
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
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,49 @@ | ||
| """ | ||
| Upload session related exceptions. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from aiohttp import web | ||
|
|
||
| from ai.backend.common.exception import ( | ||
| BackendAIError, | ||
| ErrorCode, | ||
| ErrorDetail, | ||
| ErrorDomain, | ||
| ErrorOperation, | ||
| ) | ||
|
|
||
|
|
||
| class ChunkConflictError(BackendAIError, web.HTTPConflict): | ||
| """ | ||
| Raised when an incoming chunk targets an offset that already holds a | ||
| different chunk in the upload session (409 Conflict). | ||
| """ | ||
|
|
||
| error_type = "https://api.backend.ai/probs/storage/chunk-conflict" | ||
| error_title = "Upload Chunk Conflict" | ||
|
|
||
| def error_code(self) -> ErrorCode: | ||
| return ErrorCode( | ||
| domain=ErrorDomain.STORAGE_PROXY, | ||
| operation=ErrorOperation.UPDATE, | ||
| error_detail=ErrorDetail.CONFLICT, | ||
| ) | ||
|
|
||
|
|
||
| class UploadSessionCorruptedError(BackendAIError, web.HTTPInternalServerError): | ||
| """ | ||
| Raised when the on-disk upload session metadata cannot be parsed or is | ||
| structurally invalid. | ||
| """ | ||
|
|
||
| error_type = "https://api.backend.ai/probs/storage/upload-session-corrupted" | ||
| error_title = "Upload Session Corrupted" | ||
|
|
||
| def error_code(self) -> ErrorCode: | ||
| return ErrorCode( | ||
| domain=ErrorDomain.STORAGE_PROXY, | ||
| operation=ErrorOperation.READ, | ||
| error_detail=ErrorDetail.INTERNAL_ERROR, | ||
| ) |
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,3 @@ | ||
| """ | ||
| Chunk-based TUS upload session services. | ||
| """ |
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,37 @@ | ||
| """TUS upload session locking β distributed lock factory and constants.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from ai.backend.common.lock import DistributedLockFactory, RedisLock | ||
| from ai.backend.common.types import RedisConnectionInfo | ||
|
|
||
| # Public β used by the engine to build session lock keys and pass lifetime to | ||
| # the factory. | ||
| LOCK_KEY_PREFIX = "tus.upload.lock" # tus.upload.lock:{session_id} | ||
| LOCK_LIFETIME_SECONDS = 30.0 # lock auto-expires after this (crash safety) | ||
|
|
||
| _ACQUIRE_TIMEOUT_SECONDS = 10.0 # max wait to acquire the per-session lock | ||
| # Poll interval while waiting for the lock; the RedisLock default (1s) is far | ||
| # too coarse for the short, highly-contended per-chunk critical section. | ||
| _RETRY_INTERVAL_SECONDS = 0.05 | ||
|
|
||
|
|
||
| def create_tus_lock_factory(redis: RedisConnectionInfo) -> DistributedLockFactory: | ||
| """ | ||
| Build the per-session lock factory backed by :class:`RedisLock` over ``redis``. | ||
|
|
||
| Mirrors the manager's ``create_lock_factory``: the caller owns ``redis`` | ||
| (lifecycle/close) and the returned factory closes over it, producing a fresh | ||
| lock per ``lock_id`` so the factory can live as a standalone resource. | ||
| """ | ||
|
|
||
| def _factory(lock_id: str, lifetime_hint: float) -> RedisLock: | ||
| return RedisLock( | ||
| lock_id, | ||
| redis, | ||
| timeout=_ACQUIRE_TIMEOUT_SECONDS, | ||
| lifetime=lifetime_hint, | ||
| lock_retry_interval=_RETRY_INTERVAL_SECONDS, | ||
| ) | ||
|
|
||
| return _factory |
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.
Uh oh!
There was an error while loading. Please reload this page.