From 8de166c88fb1da2dd20dfdfaa08d919055bb4f04 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Wed, 2 Dec 2026 11:47:47 +0200 Subject: [PATCH 1/7] feat(buckets): open a bucket file as a streamed, seekable file `sdk.buckets.open()` and `open_async()` return a read-only binary file over a file in a bucket. The file is downloaded as it is read, so it can be handed to anything that takes a file, such as `file=` of `sdk.documents.start_ixp_extraction`, without saving it to disk or holding it in memory first. Co-Authored-By: Claude Opus 5.5 --- packages/uipath-platform/pyproject.toml | 2 +- .../orchestrator/_bucket_file_reader.py | 139 +++++++++ .../platform/orchestrator/_buckets_service.py | 270 +++++++++++++++--- .../tests/services/test_buckets_service.py | 200 +++++++++++++ packages/uipath-platform/uv.lock | 2 +- packages/uipath/docs/core/functions.md | 13 + packages/uipath/uv.lock | 2 +- 7 files changed, 581 insertions(+), 47 deletions(-) create mode 100644 packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index 611fea927..cb22f5c61 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py new file mode 100644 index 000000000..675d3a269 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -0,0 +1,139 @@ +"""A read-only, seekable file over a bucket file, streamed from storage as it's read.""" + +import io +from typing import TYPE_CHECKING, Callable, Iterator, Optional + +import httpx + +if TYPE_CHECKING: + from _typeshed import WriteableBuffer + +CHUNK_SIZE = 64 * 1024 + + +class BucketFileReader(io.RawIOBase): + """Raw binary file over a bucket file, downloaded as it is read. + + Only the chunk being read is in memory. Seeking only moves the position: the + next read continues the open download when it is already there, and starts a + new download from that position otherwise. The size comes from the + download's headers, so asking for it starts the download that the first + read then continues. + """ + + def __init__( + self, name: str, open_download: Callable[[int], httpx.Response] + ) -> None: + """Create a reader. + + Args: + name: The file name, without the bucket path. + open_download: Starts a streamed GET of the file from a byte offset. + """ + super().__init__() + self._response: Optional[httpx.Response] = None + self._chunks: Iterator[bytes] = iter(()) + self._pending = b"" + self._download_position = 0 # offset of the next byte in _pending/_chunks + self._position = 0 + self._size: Optional[int] = None + self._size_checked = False + self._open_download = open_download + self.name = name + + def readable(self) -> bool: + """Return True: the file can be read.""" + return True + + def seekable(self) -> bool: + """Return True: the file supports seek and tell.""" + return True + + def tell(self) -> int: + """Return the current position.""" + self._checkClosed() + return self._position + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + """Move to a new position; nothing is downloaded until the next read.""" + self._checkClosed() + if whence == io.SEEK_SET: + position = offset + elif whence == io.SEEK_CUR: + position = self._position + offset + elif whence == io.SEEK_END: + position = self._file_size() + offset + else: + raise ValueError(f"invalid whence ({whence}, should be 0, 1 or 2)") + if position < 0: + raise ValueError(f"negative seek position {position}") + self._position = position + return position + + def readinto(self, buffer: "WriteableBuffer", /) -> int: + """Read the next bytes of the file into `buffer`.""" + self._checkClosed() + if self._size is not None and self._position >= self._size: + self._release() + return 0 + if self._response is None or self._download_position != self._position: + self._start(self._position) + if not self._pending: + self._pending = next(self._chunks, b"") + if not self._pending: + self._release() + return 0 + view = memoryview(buffer).cast("B") + count = min(len(view), len(self._pending)) + view[:count] = self._pending[:count] + self._pending = self._pending[count:] + self._position += count + self._download_position += count + return count + + def close(self) -> None: + """Close the file and any download still open.""" + self._release() + super().close() + + def _file_size(self) -> int: + if not self._size_checked: + self._start(self._position) + if self._size is None: + raise io.UnsupportedOperation("the storage did not report the file size") + return self._size + + def _start(self, start: int) -> None: + self._release() + response = self._open_download(start) + partial = response.status_code == 206 + if not self._size_checked: + self._size = _total_size(response, partial) + self._size_checked = True + self._response = response + # Raw bytes: the size the storage reports is the size of the stored bytes. + self._chunks = response.iter_raw(CHUNK_SIZE) + self._download_position = start if partial else 0 + # The storage ignored the Range header and sent the whole file: skip ahead. + while self._download_position < start: + chunk = next(self._chunks, b"") + if not chunk: + break + skipped = min(len(chunk), start - self._download_position) + self._download_position += skipped + self._pending = chunk[skipped:] + + def _release(self) -> None: + if self._response is not None: + self._response.close() + self._response = None + self._chunks = iter(()) + self._pending = b"" + + +def _total_size(response: httpx.Response, partial: bool) -> Optional[int]: + if partial: # Content-Range: bytes -/ + total = response.headers.get("Content-Range", "").rpartition("/")[2] + else: + total = response.headers.get("Content-Length", "") + return int(total) if total.isdigit() else None diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index eb352f8d4..f1101a0a2 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -1,11 +1,13 @@ import asyncio +import io import mimetypes import uuid -from pathlib import Path -from typing import Any, Dict, Optional, Union +from pathlib import Path, PurePosixPath +from typing import Any, BinaryIO, Dict, NamedTuple, Optional, Union import httpx from anyio import to_thread +from tenacity import retry, retry_if_exception, stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -16,7 +18,14 @@ from ..common._http_config import get_httpx_client_kwargs from ..common._models import Endpoint, RequestSpec from ..common.paging import PagedResult +from ..common.retry import ( + MAX_RETRY_ATTEMPTS, + is_retryable_platform_exception, + platform_wait_strategy, +) from ..common.validation import validate_pagination_params +from ..errors import EnrichedException +from ._bucket_file_reader import CHUNK_SIZE, BucketFileReader from .buckets import Bucket, BucketFile # Pagination limits @@ -24,6 +33,14 @@ MAX_SKIP_OFFSET = 10000 # Maximum skip offset for offset-based pagination +class _ReadAccess(NamedTuple): + """Where and how to download a bucket file, from Orchestrator's GetReadUri.""" + + uri: str + headers: Dict[str, str] + requires_auth: bool + + class BucketsService(FolderContext, BaseService): """Service for managing UiPath storage buckets. @@ -429,30 +446,19 @@ def download( bucket = self.retrieve( name=name, key=key, folder_key=folder_key, folder_path=folder_path ) - spec = self._retrieve_readUri_spec( - bucket.id, blob_file_path, folder_key=folder_key, folder_path=folder_path + access = self._get_read_access( + bucket.id, blob_file_path, folder_key, folder_path ) - result = self.request( - spec.method, - url=spec.endpoint, - params=spec.params, - headers=spec.headers, - ).json() - - read_uri = result["Uri"] - - headers = { - key: value - for key, value in zip( - result["Headers"]["Keys"], result["Headers"]["Values"], strict=False - ) - } with open(destination_path, "wb") as file: - if result["RequiresAuth"]: - file_content = self.request("GET", read_uri, headers=headers).content + if access.requires_auth: + file_content = self.request( + "GET", access.uri, headers=access.headers + ).content else: - file_content = self.custom_client.get(read_uri, headers=headers).content + file_content = self.custom_client.get( + access.uri, headers=access.headers + ).content file.write(file_content) @resource_override(resource_type="bucket") @@ -484,38 +490,126 @@ async def download_async( bucket = await self.retrieve_async( name=name, key=key, folder_key=folder_key, folder_path=folder_path ) - spec = self._retrieve_readUri_spec( - bucket.id, blob_file_path, folder_key=folder_key, folder_path=folder_path + access = await self._get_read_access_async( + bucket.id, blob_file_path, folder_key, folder_path ) - result = ( - await self.request_async( - spec.method, - url=spec.endpoint, - params=spec.params, - headers=spec.headers, - ) - ).json() - - read_uri = result["Uri"] - - headers = { - key: value - for key, value in zip( - result["Headers"]["Keys"], result["Headers"]["Values"], strict=False - ) - } - if result["RequiresAuth"]: + if access.requires_auth: file_content = ( - await self.request_async("GET", read_uri, headers=headers) + await self.request_async("GET", access.uri, headers=access.headers) ).content else: file_content = ( - await self.custom_client_async.get(read_uri, headers=headers) + await self.custom_client_async.get(access.uri, headers=access.headers) ).content await asyncio.to_thread(Path(destination_path).write_bytes, file_content) + @resource_override(resource_type="bucket") + @traced(name="buckets_open", run_type="uipath") + def open( + self, + *, + name: Optional[str] = None, + key: Optional[str] = None, + blob_file_path: str, + folder_key: Optional[str] = None, + folder_path: Optional[str] = None, + ) -> BinaryIO: + """Open a file in a bucket for reading, without downloading it first. + + The file is downloaded as it is read, so it is never held whole in memory + or written to disk. The result is a regular read-only binary file, like one + opened with `open(path, "rb")`: it can be read, seeked and passed wherever + such a file is accepted, such as `file=` of + `sdk.documents.start_ixp_extraction`. Moving back, as a retried upload + does, downloads the file again from that position. + + Args: + key (Optional[str]): The key of the bucket. + name (Optional[str]): The name of the bucket. + blob_file_path (str): The path to the file in the bucket. + folder_key (Optional[str]): The key of the folder where the bucket resides. + folder_path (Optional[str]): The path of the folder where the bucket resides. + + Returns: + BinaryIO: The opened file. Close it, or use it in a `with` block, when done. + + Raises: + ValueError: If neither key nor name is provided. + Exception: If the bucket with the specified key or name is not found. + + Examples: + ```python + with sdk.buckets.open( + name="Loans", blob_file_path="loan-123/application.pdf" + ) as file: + extraction = sdk.documents.start_ixp_extraction( + project_name="LoanQAQC", tag="live", file=file + ) + ``` + """ + bucket = self.retrieve( + name=name, key=key, folder_key=folder_key, folder_path=folder_path + ) + access = self._get_read_access( + bucket.id, blob_file_path, folder_key, folder_path + ) + return self._open_reader( + bucket.id, blob_file_path, folder_key, folder_path, access + ) + + @resource_override(resource_type="bucket") + @traced(name="buckets_open", run_type="uipath") + async def open_async( + self, + *, + name: Optional[str] = None, + key: Optional[str] = None, + blob_file_path: str, + folder_key: Optional[str] = None, + folder_path: Optional[str] = None, + ) -> BinaryIO: + """Open a file in a bucket for reading, without downloading it first. + + Looks up the bucket and the file asynchronously and returns the same file + as `open`. Reading the file is synchronous, as with any file object; httpx + also reads upload files synchronously, in async requests too. + + Args: + key (Optional[str]): The key of the bucket. + name (Optional[str]): The name of the bucket. + blob_file_path (str): The path to the file in the bucket. + folder_key (Optional[str]): The key of the folder where the bucket resides. + folder_path (Optional[str]): The path of the folder where the bucket resides. + + Returns: + BinaryIO: The opened file. Close it, or use it in a `with` block, when done. + + Raises: + ValueError: If neither key nor name is provided. + Exception: If the bucket with the specified key or name is not found. + + Examples: + ```python + with await sdk.buckets.open_async( + name="Loans", blob_file_path="loan-123/application.pdf" + ) as file: + extraction = await sdk.documents.start_ixp_extraction_async( + project_name="LoanQAQC", tag="live", file=file + ) + ``` + """ + bucket = await self.retrieve_async( + name=name, key=key, folder_key=folder_key, folder_path=folder_path + ) + access = await self._get_read_access_async( + bucket.id, blob_file_path, folder_key, folder_path + ) + return self._open_reader( + bucket.id, blob_file_path, folder_key, folder_path, access + ) + @resource_override(resource_type="bucket") @traced(name="buckets_upload", run_type="uipath") def upload( @@ -1654,6 +1748,87 @@ def _retrieve_spec( }, ) + def _get_read_access( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + ) -> _ReadAccess: + spec = self._retrieve_readUri_spec( + bucket_id, blob_file_path, folder_key=folder_key, folder_path=folder_path + ) + result = self.request( + spec.method, url=spec.endpoint, params=spec.params, headers=spec.headers + ).json() + return _read_access(result) + + async def _get_read_access_async( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + ) -> _ReadAccess: + spec = self._retrieve_readUri_spec( + bucket_id, blob_file_path, folder_key=folder_key, folder_path=folder_path + ) + response = await self.request_async( + spec.method, url=spec.endpoint, params=spec.params, headers=spec.headers + ) + return _read_access(response.json()) + + def _open_reader( + self, + bucket_id: int, + blob_file_path: str, + folder_key: Optional[str], + folder_path: Optional[str], + access: _ReadAccess, + ) -> BinaryIO: + unused_access: Optional[_ReadAccess] = access + + def open_download(start: int) -> httpx.Response: + # The first download uses the URL looked up by open(). The URL + # expires, so a later download (a rewind, a retried upload) looks up + # a new one. + nonlocal unused_access + current = unused_access or self._get_read_access( + bucket_id, blob_file_path, folder_key, folder_path + ) + unused_access = None + return self._start_download(current, start) + + name = PurePosixPath(blob_file_path.replace("\\", "/")).name + reader = BucketFileReader(name, open_download) + return io.BufferedReader(reader, buffer_size=CHUNK_SIZE) + + @retry( + retry=retry_if_exception(is_retryable_platform_exception), + wait=platform_wait_strategy, + stop=stop_after_attempt(MAX_RETRY_ATTEMPTS), + reraise=True, + ) + def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: + """Start a streamed GET of a bucket file from a byte offset.""" + # No compression: the bytes read must be the stored bytes, so that they + # match the size the storage reports. + headers = {**access.headers, "Accept-Encoding": "identity"} + if start: + headers["Range"] = f"bytes={start}-" + client = self._client if access.requires_auth else self.custom_client + response = client.send( + client.build_request("GET", access.uri, headers=headers), stream=True + ) + if response.is_error: + response.read() + response.close() + try: + response.raise_for_status() + except httpx.HTTPStatusError as error: + raise EnrichedException(error) from error + return response + def _retrieve_readUri_spec( self, bucket_id: int, @@ -1814,3 +1989,10 @@ def _get_files_spec( **header_folder(folder_key, folder_path), }, ) + + +def _read_access(result: Dict[str, Any]) -> _ReadAccess: + headers = dict( + zip(result["Headers"]["Keys"], result["Headers"]["Values"], strict=False) + ) + return _ReadAccess(result["Uri"], headers, result["RequiresAuth"]) diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index 2ec273972..d9ef04418 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -1,10 +1,12 @@ import os from pathlib import Path +import httpx import pytest from pytest_httpx import HTTPXMock from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.errors import EnrichedException from uipath.platform.orchestrator._buckets_service import BucketsService @@ -2037,3 +2039,201 @@ def test_combined_max_skip_and_top( ) result = service.list(skip=10000, top=1000) assert result is not None + + +class TestOpen: + BUCKET_KEY = "bucket-key" + BLOB_FILE_PATH = "loans/loan-123.pdf" + BLOB_URL = "https://test-storage.com/loans/loan-123.pdf" + UPLOAD_URL = "https://test-du.com/digitization/start" + CONTENT = b"%PDF-1.7\n" + bytes(range(256)) * 1024 # spans several 64 KiB chunks + + @pytest.fixture + def read_uri_url(self, base_url: str, org: str, tenant: str) -> str: + return ( + f"{base_url}{org}{tenant}/orchestrator_/odata/Buckets(123)" + f"/UiPath.Server.Configuration.OData.GetReadUri?path={self.BLOB_FILE_PATH}" + ) + + @pytest.fixture + def orchestrator( + self, + httpx_mock: HTTPXMock, + base_url: str, + org: str, + tenant: str, + read_uri_url: str, + ): + """Mock the bucket lookup and the read-URL lookups for the file.""" + + def mock(*, requires_auth: bool = False, read_uri_lookups: int = 1) -> None: + httpx_mock.add_response( + url=f"{base_url}{org}{tenant}/orchestrator_/odata/Buckets/UiPath.Server.Configuration.OData.GetByKey(identifier='{self.BUCKET_KEY}')", + json={ + "value": [{"Id": 123, "Name": "Loans", "Identifier": "bucket-key"}] + }, + ) + for _ in range(read_uri_lookups): + httpx_mock.add_response( + url=read_uri_url, + json={ + "Uri": self.BLOB_URL, + "Headers": { + "Keys": ["x-ms-blob-type"], + "Values": ["BlockBlob"], + }, + "RequiresAuth": requires_auth, + }, + ) + + return mock + + def open(self, service: BucketsService): + return service.open(key=self.BUCKET_KEY, blob_file_path=self.BLOB_FILE_PATH) + + def test_reads_the_file_from_one_download( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.name == "loan-123.pdf" + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert "range" not in download.headers + assert "authorization" not in download.headers + assert download.headers["accept-encoding"] == "identity" + assert download.headers["x-ms-blob-type"] == "BlockBlob" + + async def test_open_async( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with await service.open_async( + key=self.BUCKET_KEY, blob_file_path=self.BLOB_FILE_PATH + ) as file: + assert file.read() == self.CONTENT + + def test_the_size_comes_from_the_download_the_read_continues( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.seek(0, os.SEEK_END) == len(self.CONTENT) + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + + def test_rewinding_downloads_again_from_a_new_url( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + assert len(httpx_mock.get_requests(url=read_uri_url)) == 2 + + def test_seeking_ahead_downloads_a_range( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + file.seek(start) + assert file.read() == self.CONTENT[start:] + assert file.seek(0, os.SEEK_END) == size + + def test_seeking_ahead_when_the_storage_ignores_the_range( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + start = 70_000 + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + content=self.CONTENT, + ) + + with self.open(service) as file: + file.seek(start) + assert file.read() == self.CONTENT[start:] + + def test_storage_that_requires_auth_gets_the_platform_credentials( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + secret: str, + ): + orchestrator(requires_auth=True) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert download.headers["authorization"] == f"Bearer {secret}" + + def test_a_failed_download_raises( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response(url=self.BLOB_URL, status_code=404, text="BlobNotFound") + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert error.value.status_code == 404 + + def test_uploads_with_its_size_and_resends_whole_on_retry( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """The way `sdk.documents` uploads it: httpx `files=`, sent again on a retry.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + ) + httpx_mock.add_response(url=self.UPLOAD_URL, method="POST", status_code=503) + httpx_mock.add_response(url=self.UPLOAD_URL, method="POST") + + with self.open(service) as file, httpx.Client() as client: + for status_code in (503, 200): + response = client.post(self.UPLOAD_URL, files={"File": file}) + assert response.status_code == status_code + + uploads = httpx_mock.get_requests(url=self.UPLOAD_URL) + assert len(uploads) == 2 + for upload in uploads: + body = upload.read() + assert "transfer-encoding" not in upload.headers + assert int(upload.headers["content-length"]) == len(body) + assert self.CONTENT in body + assert b'filename="loan-123.pdf"' in body + assert b"Content-Type: application/pdf" in body diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 249f0a23b..6e32115d0 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/docs/core/functions.md b/packages/uipath/docs/core/functions.md index 598f0df3b..400c70cbb 100644 --- a/packages/uipath/docs/core/functions.md +++ b/packages/uipath/docs/core/functions.md @@ -244,6 +244,19 @@ sdk.buckets.upload( ) ``` +To pass a bucket file on without saving it first, open it. It is downloaded as it is read, so a large file uses neither disk nor memory: + +```python +with sdk.buckets.open( + name="Invoices", + blob_file_path="incoming/acme-001.pdf", + folder_path="Shared", +) as file: + extraction = sdk.documents.start_ixp_extraction( + project_name="Invoices", tag="live", file=file + ) +``` + See [Buckets](./buckets.md) for the full API reference. ### Connections diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index a1839c99e..ee06f3d06 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.22" +version = "0.3.23" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" }, From 58d907c2f38af8a47e0cd0c05b1e0592c49d84d0 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Wed, 2 Dec 2026 13:05:47 +0200 Subject: [PATCH 2/7] fix(buckets): restart failed downloads and send the current token From review of the bucket file reader: - A download that fails is dropped, so the next read starts a new one. Before, a rewind after a failure before the first chunk read as the end of the file, so a retried upload sent no file bytes. - When the storage reports no size, the size is known once a download reaches the end of the file, so reading again at the end returns b"". - A seek past the end before any read returns end of file: a 416 response gives the size instead of raising. - A download that needs platform credentials sends the current token, which may have been renewed since the client was created. Co-Authored-By: Claude Opus 5.5 --- .../orchestrator/_bucket_file_reader.py | 26 +++++- .../platform/orchestrator/_buckets_service.py | 8 +- .../tests/services/test_buckets_service.py | 82 ++++++++++++++++++- 3 files changed, 111 insertions(+), 5 deletions(-) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py index 675d3a269..ee0f51a7d 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -18,7 +18,8 @@ class BucketFileReader(io.RawIOBase): next read continues the open download when it is already there, and starts a new download from that position otherwise. The size comes from the download's headers, so asking for it starts the download that the first - read then continues. + read then continues. When the storage reports no size, it is known once a + download reaches the end of the file. """ def __init__( @@ -78,9 +79,13 @@ def readinto(self, buffer: "WriteableBuffer", /) -> int: return 0 if self._response is None or self._download_position != self._position: self._start(self._position) + if self._response is None: # the position is past the end of the file + return 0 if not self._pending: - self._pending = next(self._chunks, b"") + self._pending = self._next_chunk() if not self._pending: + if self._size is None: # the download ran to the end of the file + self._size = self._download_position self._release() return 0 view = memoryview(buffer).cast("B") @@ -106,6 +111,12 @@ def _file_size(self) -> int: def _start(self, start: int) -> None: self._release() response = self._open_download(start) + if response.status_code == 416: # Range Not Satisfiable: start is past the end + response.close() + # Content-Range: bytes */ + self._size = _total_size(response, partial=True) + self._size_checked = True + return partial = response.status_code == 206 if not self._size_checked: self._size = _total_size(response, partial) @@ -116,13 +127,22 @@ def _start(self, start: int) -> None: self._download_position = start if partial else 0 # The storage ignored the Range header and sent the whole file: skip ahead. while self._download_position < start: - chunk = next(self._chunks, b"") + chunk = self._next_chunk() if not chunk: break skipped = min(len(chunk), start - self._download_position) self._download_position += skipped self._pending = chunk[skipped:] + def _next_chunk(self) -> bytes: + """Return the download's next chunk, or b"" at its end.""" + try: + return next(self._chunks, b"") + except BaseException: + # Drop the failed download, so that the next read starts a new one. + self._release() + raise + def _release(self) -> None: if self._response is not None: self._response.close() diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index f1101a0a2..9aa298afd 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -1816,11 +1816,17 @@ def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: headers = {**access.headers, "Accept-Encoding": "identity"} if start: headers["Range"] = f"bytes={start}-" + if access.requires_auth: + # The current token, as request() sends: it may have been renewed + # since the client was created. + self._add_authorization(headers) client = self._client if access.requires_auth else self.custom_client response = client.send( client.build_request("GET", access.uri, headers=headers), stream=True ) - if response.is_error: + # 416: the start is past the end of the file, which the reader turns + # into end of file. + if response.is_error and response.status_code != 416: response.read() response.close() try: diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index d9ef04418..e8a9e17ca 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -1,9 +1,10 @@ +import io import os from pathlib import Path import httpx import pytest -from pytest_httpx import HTTPXMock +from pytest_httpx import HTTPXMock, IteratorStream from uipath.platform import UiPathApiConfig, UiPathExecutionContext from uipath.platform.errors import EnrichedException @@ -2237,3 +2238,82 @@ def test_uploads_with_its_size_and_resends_whole_on_retry( assert self.CONTENT in body assert b'filename="loan-123.pdf"' in body assert b"Content-Type: application/pdf" in body + + def test_a_failed_download_is_started_again_by_the_next_read( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """A rewind after a failure before the first chunk must not read as the end.""" + + class ResetBeforeFirstChunk(httpx.SyncByteStream): + def __iter__(self): + raise httpx.ReadError("connection reset") + yield b"" # makes this a generator + + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={"Content-Length": str(len(self.CONTENT))}, + stream=ResetBeforeFirstChunk(), + ) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + with pytest.raises(httpx.ReadError): + file.read() + file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_without_a_reported_size_the_end_is_found_by_reading( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + + with self.open(service) as file: + with pytest.raises(io.UnsupportedOperation): # no size reported yet + file.seek(0, os.SEEK_END) + assert file.read() == self.CONTENT + assert file.read() == b"" + assert file.seek(0, os.SEEK_END) == len(self.CONTENT) + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + + def test_reading_past_the_end_before_any_read_returns_nothing( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator() + size = len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={size + 10}-"}, + status_code=416, + headers={"Content-Range": f"bytes */{size}"}, + ) + + with self.open(service) as file: + file.seek(size + 10) + assert file.read() == b"" + assert file.seek(0, os.SEEK_END) == size + + def test_storage_that_requires_auth_gets_the_current_token( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + monkeypatch: pytest.MonkeyPatch, + ): + """A token renewed during the job replaces the one the client was built with.""" + orchestrator(requires_auth=True) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + service._config.secret_from_environment = True + monkeypatch.setattr(service, "_current_secret", lambda: "renewed-token") + + with self.open(service) as file: + assert file.read() == self.CONTENT + + [download] = httpx_mock.get_requests(url=self.BLOB_URL) + assert download.headers["authorization"] == "Bearer renewed-token" From ac464e1920950f32dc4dc236a8c41af150c49c48 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Wed, 2 Dec 2026 19:40:42 +0200 Subject: [PATCH 3/7] fix(buckets): address review of open - Remove open_async. Reading the file waits on the storage, like reading any file waits on the disk, so an async method would suggest otherwise. From async code, read the file in a worker thread. - Do not retry downloads in the reader. The code that reads the file retries, such as the sdk.documents upload, so a storage failure is retried once instead of up to 25 times. - Raise BucketFileChangedError when a later download returns another version of the file, by ETag or size, instead of cutting it off or mixing two versions. Take the size from the first response reporting it. - Look up a new read URL before every download, the first one included: the URL expires, and a new one misses responses cached for an older one. - Close an error response even when reading its body fails. Co-Authored-By: Claude Opus 5.5 --- .../src/uipath/platform/errors/__init__.py | 3 + .../errors/_bucket_file_changed_error.py | 17 +++ .../orchestrator/_bucket_file_reader.py | 37 ++++-- .../platform/orchestrator/_buckets_service.py | 111 +++++------------ .../tests/services/test_buckets_service.py | 113 +++++++++++++++++- 5 files changed, 187 insertions(+), 94 deletions(-) create mode 100644 packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py diff --git a/packages/uipath-platform/src/uipath/platform/errors/__init__.py b/packages/uipath-platform/src/uipath/platform/errors/__init__.py index 012209a0f..db3d950e4 100644 --- a/packages/uipath-platform/src/uipath/platform/errors/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/errors/__init__.py @@ -4,6 +4,7 @@ Available exceptions: - BaseUrlMissingError: Raised when base URL is not configured +- BucketFileChangedError: Raised when a bucket file changes while it is being read - SecretMissingError: Raised when access token is not configured - FolderNotFoundException: Raised when a folder cannot be found - UnsupportedDataSourceException: Raised when an operation is attempted on an unsupported data source type @@ -20,6 +21,7 @@ from ._base_url_missing_error import BaseUrlMissingError from ._batch_transform_failed_exception import BatchTransformFailedException from ._batch_transform_not_complete_exception import BatchTransformNotCompleteException +from ._bucket_file_changed_error import BucketFileChangedError from ._context_grounding_index_not_found_exception import ( ContextGroundingIndexNotFoundError, ) @@ -40,6 +42,7 @@ "DataFabricErrorCategory", "BatchTransformFailedException", "BatchTransformNotCompleteException", + "BucketFileChangedError", "ContextGroundingIndexNotFoundError", "EnrichedException", "ExtractedErrorInfo", diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py new file mode 100644 index 000000000..86b322e16 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py @@ -0,0 +1,17 @@ +class BucketFileChangedError(Exception): + """Raised when a bucket file changes while it is being read. + + A file opened with `sdk.buckets.open` is downloaded again when it is read from + another position, as a retried upload does. If the file in the bucket was + replaced in the meantime, the new download would return another version, so + the read fails instead of mixing bytes of the two versions. Open the file + again to read its current version. + """ + + def __init__(self, name: str) -> None: + self.name = name + self.message = ( + f"The bucket file '{name}' changed while it was being read. " + "Open it again to read its current version." + ) + super().__init__(self.message) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py index ee0f51a7d..12f252f3d 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -5,6 +5,8 @@ import httpx +from ..errors import BucketFileChangedError + if TYPE_CHECKING: from _typeshed import WriteableBuffer @@ -19,7 +21,9 @@ class BucketFileReader(io.RawIOBase): new download from that position otherwise. The size comes from the download's headers, so asking for it starts the download that the first read then continues. When the storage reports no size, it is known once a - download reaches the end of the file. + download reaches the end of the file. Every download must return the same + version of the file, by ETag and size; if the file was replaced in the + bucket, the read raises `BucketFileChangedError`. """ def __init__( @@ -38,7 +42,8 @@ def __init__( self._download_position = 0 # offset of the next byte in _pending/_chunks self._position = 0 self._size: Optional[int] = None - self._size_checked = False + self._size_checked = False # a download has reported its headers + self._etag: Optional[str] = None self._open_download = open_download self.name = name @@ -114,13 +119,14 @@ def _start(self, start: int) -> None: if response.status_code == 416: # Range Not Satisfiable: start is past the end response.close() # Content-Range: bytes */ - self._size = _total_size(response, partial=True) - self._size_checked = True + self._check_version(response, _total_size(response, partial=True)) return partial = response.status_code == 206 - if not self._size_checked: - self._size = _total_size(response, partial) - self._size_checked = True + try: + self._check_version(response, _total_size(response, partial)) + except BucketFileChangedError: + response.close() + raise self._response = response # Raw bytes: the size the storage reports is the size of the stored bytes. self._chunks = response.iter_raw(CHUNK_SIZE) @@ -134,6 +140,23 @@ def _start(self, start: int) -> None: self._download_position += skipped self._pending = chunk[skipped:] + def _check_version(self, response: httpx.Response, size: Optional[int]) -> None: + """Keep the first ETag and size reported; fail if a later download differs. + + Every download of the file must return the same version: a rewind or a + retried upload after the file was replaced would otherwise cut a larger + file off at the old size, or mix bytes of the two versions. + """ + etag = response.headers.get("ETag") + if (etag and self._etag and etag != self._etag) or ( + size is not None and self._size is not None and size != self._size + ): + raise BucketFileChangedError(self.name) + self._etag = self._etag or etag + if self._size is None: + self._size = size + self._size_checked = True + def _next_chunk(self) -> bytes: """Return the download's next chunk, or b"" at its end.""" try: diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index 9aa298afd..675e7d263 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -7,7 +7,6 @@ import httpx from anyio import to_thread -from tenacity import retry, retry_if_exception, stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -18,11 +17,6 @@ from ..common._http_config import get_httpx_client_kwargs from ..common._models import Endpoint, RequestSpec from ..common.paging import PagedResult -from ..common.retry import ( - MAX_RETRY_ATTEMPTS, - is_retryable_platform_exception, - platform_wait_strategy, -) from ..common.validation import validate_pagination_params from ..errors import EnrichedException from ._bucket_file_reader import CHUNK_SIZE, BucketFileReader @@ -523,7 +517,13 @@ def open( opened with `open(path, "rb")`: it can be read, seeked and passed wherever such a file is accepted, such as `file=` of `sdk.documents.start_ixp_extraction`. Moving back, as a retried upload - does, downloads the file again from that position. + does, downloads the file again from that position. If the file is + replaced in the bucket while it is being read, a read raises + `BucketFileChangedError` rather than mixing the two versions. + + Reading waits on the storage, as reading any file waits on the disk. From + async code, do the reading in a worker thread, for example by running + `open` and the call that reads the file in `asyncio.to_thread`. Args: key (Optional[str]): The key of the bucket. @@ -548,67 +548,22 @@ def open( project_name="LoanQAQC", tag="live", file=file ) ``` - """ - bucket = self.retrieve( - name=name, key=key, folder_key=folder_key, folder_path=folder_path - ) - access = self._get_read_access( - bucket.id, blob_file_path, folder_key, folder_path - ) - return self._open_reader( - bucket.id, blob_file_path, folder_key, folder_path, access - ) - - @resource_override(resource_type="bucket") - @traced(name="buckets_open", run_type="uipath") - async def open_async( - self, - *, - name: Optional[str] = None, - key: Optional[str] = None, - blob_file_path: str, - folder_key: Optional[str] = None, - folder_path: Optional[str] = None, - ) -> BinaryIO: - """Open a file in a bucket for reading, without downloading it first. - - Looks up the bucket and the file asynchronously and returns the same file - as `open`. Reading the file is synchronous, as with any file object; httpx - also reads upload files synchronously, in async requests too. - - Args: - key (Optional[str]): The key of the bucket. - name (Optional[str]): The name of the bucket. - blob_file_path (str): The path to the file in the bucket. - folder_key (Optional[str]): The key of the folder where the bucket resides. - folder_path (Optional[str]): The path of the folder where the bucket resides. - - Returns: - BinaryIO: The opened file. Close it, or use it in a `with` block, when done. - - Raises: - ValueError: If neither key nor name is provided. - Exception: If the bucket with the specified key or name is not found. - Examples: + From async code: ```python - with await sdk.buckets.open_async( - name="Loans", blob_file_path="loan-123/application.pdf" - ) as file: - extraction = await sdk.documents.start_ixp_extraction_async( - project_name="LoanQAQC", tag="live", file=file - ) + def extract(path): + with sdk.buckets.open(name="Loans", blob_file_path=path) as file: + return sdk.documents.start_ixp_extraction( + project_name="LoanQAQC", tag="live", file=file + ) + + extraction = await asyncio.to_thread(extract, "loan-123/application.pdf") ``` """ - bucket = await self.retrieve_async( + bucket = self.retrieve( name=name, key=key, folder_key=folder_key, folder_path=folder_path ) - access = await self._get_read_access_async( - bucket.id, blob_file_path, folder_key, folder_path - ) - return self._open_reader( - bucket.id, blob_file_path, folder_key, folder_path, access - ) + return self._open_reader(bucket.id, blob_file_path, folder_key, folder_path) @resource_override(resource_type="bucket") @traced(name="buckets_upload", run_type="uipath") @@ -1784,33 +1739,26 @@ def _open_reader( blob_file_path: str, folder_key: Optional[str], folder_path: Optional[str], - access: _ReadAccess, ) -> BinaryIO: - unused_access: Optional[_ReadAccess] = access - def open_download(start: int) -> httpx.Response: - # The first download uses the URL looked up by open(). The URL - # expires, so a later download (a rewind, a retried upload) looks up - # a new one. - nonlocal unused_access - current = unused_access or self._get_read_access( + # A new read URL for every download: the URL expires (after an hour + # on Orchestrator storage), and a new one also misses any cached + # response for an older URL. + access = self._get_read_access( bucket_id, blob_file_path, folder_key, folder_path ) - unused_access = None - return self._start_download(current, start) + return self._start_download(access, start) name = PurePosixPath(blob_file_path.replace("\\", "/")).name reader = BucketFileReader(name, open_download) return io.BufferedReader(reader, buffer_size=CHUNK_SIZE) - @retry( - retry=retry_if_exception(is_retryable_platform_exception), - wait=platform_wait_strategy, - stop=stop_after_attempt(MAX_RETRY_ATTEMPTS), - reraise=True, - ) def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: - """Start a streamed GET of a bucket file from a byte offset.""" + """Start a streamed GET of a bucket file from a byte offset. + + Not retried: whoever reads the file retries, such as the retry of the + `sdk.documents` upload that reads it, so failures are retried once. + """ # No compression: the bytes read must be the stored bytes, so that they # match the size the storage reports. headers = {**access.headers, "Accept-Encoding": "identity"} @@ -1827,12 +1775,13 @@ def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: # 416: the start is past the end of the file, which the reader turns # into end of file. if response.is_error and response.status_code != 416: - response.read() - response.close() try: + response.read() response.raise_for_status() except httpx.HTTPStatusError as error: raise EnrichedException(error) from error + finally: + response.close() return response def _retrieve_readUri_spec( diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index e8a9e17ca..4b981daf8 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -1,13 +1,14 @@ import io import os from pathlib import Path +from typing import Any import httpx import pytest from pytest_httpx import HTTPXMock, IteratorStream from uipath.platform import UiPathApiConfig, UiPathExecutionContext -from uipath.platform.errors import EnrichedException +from uipath.platform.errors import BucketFileChangedError, EnrichedException from uipath.platform.orchestrator._buckets_service import BucketsService @@ -2108,17 +2109,23 @@ def test_reads_the_file_from_one_download( assert download.headers["accept-encoding"] == "identity" assert download.headers["x-ms-blob-type"] == "BlockBlob" - async def test_open_async( - self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + def test_the_read_url_is_looked_up_when_the_download_starts( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, ): + """A URL looked up by open() could expire before the first read.""" orchestrator() httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) - with await service.open_async( - key=self.BUCKET_KEY, blob_file_path=self.BLOB_FILE_PATH - ) as file: + with self.open(service) as file: + assert httpx_mock.get_requests(url=read_uri_url) == [] assert file.read() == self.CONTENT + assert len(httpx_mock.get_requests(url=read_uri_url)) == 1 + def test_the_size_comes_from_the_download_the_read_continues( self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator ): @@ -2213,6 +2220,21 @@ def test_a_failed_download_raises( assert error.value.status_code == 404 + def test_a_download_is_not_retried_by_the_reader( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """Whoever reads the file retries, so a storage 503 is retried at one layer.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response(url=self.BLOB_URL, status_code=503) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + assert error.value.status_code == 503 + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 1 + assert file.read() == self.CONTENT # the caller's retry + def test_uploads_with_its_size_and_resends_whole_on_retry( self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator ): @@ -2317,3 +2339,82 @@ def test_storage_that_requires_auth_gets_the_current_token( [download] = httpx_mock.get_requests(url=self.BLOB_URL) assert download.headers["authorization"] == "Bearer renewed-token" + + @pytest.mark.parametrize( + "replacement", + [ + pytest.param({"ETag": '"v2"'}, id="new-etag"), + pytest.param({"ETag": '"v1"', "size": 999}, id="new-size"), + ], + ) + def test_a_file_replaced_in_the_bucket_fails_the_next_download( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + replacement: dict[str, Any], + ): + """A rewind or retried upload must not cut off or mix two versions.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, headers={"ETag": '"v1"'}, content=self.CONTENT + ) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={"ETag": replacement["ETag"]}, + content=b"%" * replacement.get("size", len(self.CONTENT) + 10), + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + with pytest.raises(BucketFileChangedError, match="loan-123.pdf"): + file.read() + + def test_a_later_download_gives_the_size_when_the_first_did_not( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + orchestrator(read_uri_lookups=2) + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + assert file.read(10) == self.CONTENT[:10] + with pytest.raises(io.UnsupportedOperation): # no size reported yet + file.seek(0, os.SEEK_END) + file.seek(start) + assert file.read(10) == self.CONTENT[start : start + 10] + # Known from the 206's Content-Range, before reaching the end. + assert file.seek(0, os.SEEK_END) == size + + def test_an_error_response_is_closed_when_reading_its_body_fails( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + class TimesOutWhileReading(httpx.SyncByteStream): + closed = False + + def __iter__(self): + raise httpx.ReadTimeout("timed out reading the error body") + yield b"" # makes this a generator + + def close(self): + self.closed = True + + orchestrator() + body = TimesOutWhileReading() + httpx_mock.add_response(url=self.BLOB_URL, status_code=503, stream=body) + + with self.open(service) as file: + with pytest.raises(httpx.ReadTimeout): + file.read() + + assert body.closed From fa4f69fff5f5d0d33fd7f008b5ea1fc032b0f0d7 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Thu, 3 Dec 2026 12:37:08 +0200 Subject: [PATCH 4/7] fix(buckets): retry failed reads at the upload, keep read URLs out of errors - A download that fails, or that the storage ends before the end of the file, raises BucketFileReadError. The platform retry treats it as transient: the request sending the file was cut short, so a documents upload sends the whole file again from a new download. Errors from the service itself keep the existing retry policy. - The read-URL lookup of an opened file makes a single attempt, like the download: whoever reads the file retries, at one layer. - A storage error carries the read URL without its query string, which is its signature; the status and headers stay for the retry. - A download after the first needs the first one's ETag. A storage that reports none can't show a replacement of the same size, so such a file isn't downloaded a second time (BucketFileChangedError, verified=False). Co-Authored-By: Claude Opus 5.5 --- .../src/uipath/platform/common/retry.py | 7 +- .../src/uipath/platform/errors/__init__.py | 3 + .../errors/_bucket_file_changed_error.py | 16 +- .../errors/_bucket_file_read_error.py | 20 ++ .../orchestrator/_bucket_file_reader.py | 52 ++++- .../platform/orchestrator/_buckets_service.py | 54 ++++- .../tests/services/test_buckets_service.py | 195 ++++++++++++++++-- .../tests/services/test_retry.py | 13 +- 8 files changed, 325 insertions(+), 35 deletions(-) create mode 100644 packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py diff --git a/packages/uipath-platform/src/uipath/platform/common/retry.py b/packages/uipath-platform/src/uipath/platform/common/retry.py index 4bbe561a6..f521df872 100644 --- a/packages/uipath-platform/src/uipath/platform/common/retry.py +++ b/packages/uipath-platform/src/uipath/platform/common/retry.py @@ -15,7 +15,7 @@ ) from tenacity import RetryCallState -from ..errors import EnrichedException +from ..errors import BucketFileReadError, EnrichedException RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({408, 429, 502, 503, 504, 524}) NON_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({400, 401, 403, 404, 413, 422}) @@ -76,6 +76,11 @@ def is_retryable_platform_exception(exception: BaseException) -> bool: # A failed connect never sent the request, so any method is safe to retry. if isinstance(exception, (ConnectError, TimeoutException)): return True + # Reading the bucket file the request was sending failed, so the request + # was not sent in full: sending it again is safe, and sends the whole file + # from a new download. + if isinstance(exception, BucketFileReadError): + return True if isinstance(exception, EnrichedException): return exception.status_code in RETRYABLE_STATUS_CODES return False diff --git a/packages/uipath-platform/src/uipath/platform/errors/__init__.py b/packages/uipath-platform/src/uipath/platform/errors/__init__.py index db3d950e4..bb0a39575 100644 --- a/packages/uipath-platform/src/uipath/platform/errors/__init__.py +++ b/packages/uipath-platform/src/uipath/platform/errors/__init__.py @@ -5,6 +5,7 @@ Available exceptions: - BaseUrlMissingError: Raised when base URL is not configured - BucketFileChangedError: Raised when a bucket file changes while it is being read +- BucketFileReadError: Raised when downloading a bucket file fails while it is read - SecretMissingError: Raised when access token is not configured - FolderNotFoundException: Raised when a folder cannot be found - UnsupportedDataSourceException: Raised when an operation is attempted on an unsupported data source type @@ -22,6 +23,7 @@ from ._batch_transform_failed_exception import BatchTransformFailedException from ._batch_transform_not_complete_exception import BatchTransformNotCompleteException from ._bucket_file_changed_error import BucketFileChangedError +from ._bucket_file_read_error import BucketFileReadError from ._context_grounding_index_not_found_exception import ( ContextGroundingIndexNotFoundError, ) @@ -43,6 +45,7 @@ "BatchTransformFailedException", "BatchTransformNotCompleteException", "BucketFileChangedError", + "BucketFileReadError", "ContextGroundingIndexNotFoundError", "EnrichedException", "ExtractedErrorInfo", diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py index 86b322e16..3f030c947 100644 --- a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py @@ -6,12 +6,24 @@ class BucketFileChangedError(Exception): replaced in the meantime, the new download would return another version, so the read fails instead of mixing bytes of the two versions. Open the file again to read its current version. + + Only an ETag tells two versions of the same size apart, so when the storage + reports no ETag, the file is not downloaded a second time: that read fails + with this error too, with `verified` False. """ - def __init__(self, name: str) -> None: + def __init__(self, name: str, *, verified: bool = True) -> None: self.name = name + self.verified = verified + if verified: + reason = "changed while it was being read" + else: + reason = ( + "can't be downloaded again while it is being read: the storage " + "reports no version (ETag) for it, so a change could not be detected" + ) self.message = ( - f"The bucket file '{name}' changed while it was being read. " + f"The bucket file '{name}' {reason}. " "Open it again to read its current version." ) super().__init__(self.message) diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py new file mode 100644 index 000000000..3908a13b7 --- /dev/null +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_read_error.py @@ -0,0 +1,20 @@ +class BucketFileReadError(Exception): + """Raised when downloading a bucket file from storage fails while it is read. + + A file opened with `sdk.buckets.open` is downloaded as it is read. If the + connection to the storage fails, or the storage ends a download before the + end of the file, the read raises this error, with the network error, if + any, as its cause. + + Reading the file again starts a new download. The platform retry treats + this error as transient: a request that was sending the file, such as a + `sdk.documents` upload, failed before it was sent in full, so it is sent + again, with the whole file. + """ + + def __init__( + self, name: str, reason: str = "the connection to the storage failed" + ) -> None: + self.name = name + self.message = f"Downloading the bucket file '{name}' failed: {reason}." + super().__init__(self.message) diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py index 12f252f3d..43707e636 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -5,7 +5,7 @@ import httpx -from ..errors import BucketFileChangedError +from ..errors import BucketFileChangedError, BucketFileReadError if TYPE_CHECKING: from _typeshed import WriteableBuffer @@ -23,7 +23,9 @@ class BucketFileReader(io.RawIOBase): read then continues. When the storage reports no size, it is known once a download reaches the end of the file. Every download must return the same version of the file, by ETag and size; if the file was replaced in the - bucket, the read raises `BucketFileChangedError`. + bucket, the read raises `BucketFileChangedError`. A failed download raises + `BucketFileReadError`; the reader doesn't retry it, whoever reads the file + does. """ def __init__( @@ -44,6 +46,7 @@ def __init__( self._size: Optional[int] = None self._size_checked = False # a download has reported its headers self._etag: Optional[str] = None + self._downloaded = False # a download with content has started self._open_download = open_download self.name = name @@ -89,9 +92,15 @@ def readinto(self, buffer: "WriteableBuffer", /) -> int: if not self._pending: self._pending = self._next_chunk() if not self._pending: + self._release() if self._size is None: # the download ran to the end of the file self._size = self._download_position - self._release() + elif self._download_position < self._size: + # A storage can send less than the range asked for. + raise BucketFileReadError( + self.name, + "the storage ended the download before the end of the file", + ) return 0 view = memoryview(buffer).cast("B") count = min(len(view), len(self._pending)) @@ -115,15 +124,20 @@ def _file_size(self) -> int: def _start(self, start: int) -> None: self._release() - response = self._open_download(start) + try: + response = self._open_download(start) + except httpx.TransportError as error: + raise BucketFileReadError(self.name) from error if response.status_code == 416: # Range Not Satisfiable: start is past the end response.close() # Content-Range: bytes */ - self._check_version(response, _total_size(response, partial=True)) + self._check_version( + response, _total_size(response, partial=True), content=False + ) return partial = response.status_code == 206 try: - self._check_version(response, _total_size(response, partial)) + self._check_version(response, _total_size(response, partial), content=True) except BucketFileChangedError: response.close() raise @@ -140,19 +154,32 @@ def _start(self, start: int) -> None: self._download_position += skipped self._pending = chunk[skipped:] - def _check_version(self, response: httpx.Response, size: Optional[int]) -> None: - """Keep the first ETag and size reported; fail if a later download differs. + def _check_version( + self, response: httpx.Response, size: Optional[int], *, content: bool + ) -> None: + """Keep the first download's version; fail if a later download differs. Every download of the file must return the same version: a rewind or a retried upload after the file was replaced would otherwise cut a larger - file off at the old size, or mix bytes of the two versions. + file off at the old size, or mix bytes of the two versions. Only an + ETag tells two versions of the same size apart, so without one the + file is not downloaded again. + + Args: + response: The download's response. + size: The file size the response reports, if any. + content: Whether the response has the file's bytes, unlike a 416. """ etag = response.headers.get("ETag") if (etag and self._etag and etag != self._etag) or ( size is not None and self._size is not None and size != self._size ): raise BucketFileChangedError(self.name) - self._etag = self._etag or etag + if content: + if self._downloaded and not (etag and self._etag): + raise BucketFileChangedError(self.name, verified=False) + self._etag = etag + self._downloaded = True if self._size is None: self._size = size self._size_checked = True @@ -161,8 +188,11 @@ def _next_chunk(self) -> bytes: """Return the download's next chunk, or b"" at its end.""" try: return next(self._chunks, b"") - except BaseException: + except httpx.TransportError as error: # Drop the failed download, so that the next read starts a new one. + self._release() + raise BucketFileReadError(self.name) from error + except BaseException: self._release() raise diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index 675e7d263..c81a6effb 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -2,11 +2,13 @@ import io import mimetypes import uuid +from functools import partial from pathlib import Path, PurePosixPath from typing import Any, BinaryIO, Dict, NamedTuple, Optional, Union import httpx from anyio import to_thread +from tenacity import stop_after_attempt from uipath.core.tracing import traced from ..common._base_service import BaseService @@ -27,6 +29,11 @@ MAX_SKIP_OFFSET = 10000 # Maximum skip offset for offset-based pagination +# `request` with a single attempt, for the read-URL lookup of an opened file: +# whoever reads the file retries, so the lookup is retried at that one layer. +_request_once = BaseService.request.retry_with(stop=stop_after_attempt(1)) # type: ignore[attr-defined] + + class _ReadAccess(NamedTuple): """Where and how to download a bucket file, from Orchestrator's GetReadUri.""" @@ -519,7 +526,15 @@ def open( `sdk.documents.start_ixp_extraction`. Moving back, as a retried upload does, downloads the file again from that position. If the file is replaced in the bucket while it is being read, a read raises - `BucketFileChangedError` rather than mixing the two versions. + `BucketFileChangedError` rather than mixing the two versions. A storage + that reports no ETag can't show a replacement, so there the file is not + downloaded a second time: that read raises `BucketFileChangedError` too. + + A read is not retried: whoever reads the file retries. If a download + fails, the read raises `BucketFileReadError`, or `EnrichedException` for + an error status. The platform retry treats `BucketFileReadError` and + statuses such as 503 as transient, so a `sdk.documents` upload sends the + file again. Reading waits on the storage, as reading any file waits on the disk. From async code, do the reading in a worker thread, for example by running @@ -538,6 +553,9 @@ def open( Raises: ValueError: If neither key nor name is provided. Exception: If the bucket with the specified key or name is not found. + BucketFileReadError: When reading, if a download from the storage fails. + BucketFileChangedError: When reading, if the file was replaced in the + bucket, or a replacement can't be ruled out. Examples: ```python @@ -1709,11 +1727,14 @@ def _get_read_access( blob_file_path: str, folder_key: Optional[str], folder_path: Optional[str], + *, + retry: bool = True, ) -> _ReadAccess: spec = self._retrieve_readUri_spec( bucket_id, blob_file_path, folder_key=folder_key, folder_path=folder_path ) - result = self.request( + send = self.request if retry else partial(_request_once, self) + result = send( spec.method, url=spec.endpoint, params=spec.params, headers=spec.headers ).json() return _read_access(result) @@ -1745,7 +1766,7 @@ def open_download(start: int) -> httpx.Response: # on Orchestrator storage), and a new one also misses any cached # response for an older URL. access = self._get_read_access( - bucket_id, blob_file_path, folder_key, folder_path + bucket_id, blob_file_path, folder_key, folder_path, retry=False ) return self._start_download(access, start) @@ -1756,8 +1777,9 @@ def open_download(start: int) -> httpx.Response: def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: """Start a streamed GET of a bucket file from a byte offset. - Not retried: whoever reads the file retries, such as the retry of the - `sdk.documents` upload that reads it, so failures are retried once. + Not retried, like the read-URL lookup: whoever reads the file retries, + such as the retry of the `sdk.documents` upload that reads it, so + failures are retried at one layer. """ # No compression: the bytes read must be the stored bytes, so that they # match the size the storage reports. @@ -1777,11 +1799,10 @@ def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: if response.is_error and response.status_code != 416: try: response.read() - response.raise_for_status() - except httpx.HTTPStatusError as error: - raise EnrichedException(error) from error finally: response.close() + error = _status_error_without_query(response) + raise EnrichedException(error) from error return response def _retrieve_readUri_spec( @@ -1946,6 +1967,23 @@ def _get_files_spec( ) +def _status_error_without_query(response: httpx.Response) -> httpx.HTTPStatusError: + """The error for a failed download, with no query string in its URL. + + The query string of a read URL is its signature, which gives access to the + file, so it must not reach error messages, logs or traces. The status and + the headers stay, for the retry of whoever reads the file. + """ + url = response.request.url.copy_with(query=None, fragment=None) + response.request = httpx.Request(response.request.method, url) + return httpx.HTTPStatusError( + f"Bucket storage returned {response.status_code} {response.reason_phrase} " + f"for {url}", + request=response.request, + response=response, + ) + + def _read_access(result: Dict[str, Any]) -> _ReadAccess: headers = dict( zip(result["Headers"]["Keys"], result["Headers"]["Values"], strict=False) diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index 4b981daf8..ef745fe39 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -1,14 +1,25 @@ import io import os +import traceback from pathlib import Path -from typing import Any +from typing import Any, Optional import httpx import pytest from pytest_httpx import HTTPXMock, IteratorStream +from tenacity import wait_none from uipath.platform import UiPathApiConfig, UiPathExecutionContext -from uipath.platform.errors import BucketFileChangedError, EnrichedException +from uipath.platform.common._base_service import BaseService +from uipath.platform.common.retry import ( + extract_retry_after_from_chain, + is_retryable_platform_exception, +) +from uipath.platform.errors import ( + BucketFileChangedError, + BucketFileReadError, + EnrichedException, +) from uipath.platform.orchestrator._buckets_service import BucketsService @@ -2049,6 +2060,7 @@ class TestOpen: BLOB_URL = "https://test-storage.com/loans/loan-123.pdf" UPLOAD_URL = "https://test-du.com/digitization/start" CONTENT = b"%PDF-1.7\n" + bytes(range(256)) * 1024 # spans several 64 KiB chunks + ETAG = {"ETag": '"v1"'} @pytest.fixture def read_uri_url(self, base_url: str, org: str, tenant: str) -> str: @@ -2068,7 +2080,12 @@ def orchestrator( ): """Mock the bucket lookup and the read-URL lookups for the file.""" - def mock(*, requires_auth: bool = False, read_uri_lookups: int = 1) -> None: + def mock( + *, + requires_auth: bool = False, + read_uri_lookups: int = 1, + uri: Optional[str] = None, + ) -> None: httpx_mock.add_response( url=f"{base_url}{org}{tenant}/orchestrator_/odata/Buckets/UiPath.Server.Configuration.OData.GetByKey(identifier='{self.BUCKET_KEY}')", json={ @@ -2079,7 +2096,7 @@ def mock(*, requires_auth: bool = False, read_uri_lookups: int = 1) -> None: httpx_mock.add_response( url=read_uri_url, json={ - "Uri": self.BLOB_URL, + "Uri": uri or self.BLOB_URL, "Headers": { "Keys": ["x-ms-blob-type"], "Values": ["BlockBlob"], @@ -2148,7 +2165,7 @@ def test_rewinding_downloads_again_from_a_new_url( ): orchestrator(read_uri_lookups=2) httpx_mock.add_response( - url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT, is_reusable=True ) with self.open(service) as file: @@ -2241,7 +2258,7 @@ def test_uploads_with_its_size_and_resends_whole_on_retry( """The way `sdk.documents` uploads it: httpx `files=`, sent again on a retry.""" orchestrator(read_uri_lookups=2) httpx_mock.add_response( - url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT, is_reusable=True ) httpx_mock.add_response(url=self.UPLOAD_URL, method="POST", status_code=503) httpx_mock.add_response(url=self.UPLOAD_URL, method="POST") @@ -2274,14 +2291,17 @@ def __iter__(self): orchestrator(read_uri_lookups=2) httpx_mock.add_response( url=self.BLOB_URL, - headers={"Content-Length": str(len(self.CONTENT))}, + headers={**self.ETAG, "Content-Length": str(len(self.CONTENT))}, stream=ResetBeforeFirstChunk(), ) - httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT + ) with self.open(service) as file: - with pytest.raises(httpx.ReadError): + with pytest.raises(BucketFileReadError, match="loan-123.pdf") as error: file.read() + assert isinstance(error.value.__cause__, httpx.ReadError) file.seek(0) assert file.read() == self.CONTENT @@ -2377,13 +2397,13 @@ def test_a_later_download_gives_the_size_when_the_first_did_not( orchestrator(read_uri_lookups=2) start, size = 70_000, len(self.CONTENT) httpx_mock.add_response( - url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + url=self.BLOB_URL, headers=self.ETAG, stream=IteratorStream([self.CONTENT]) ) httpx_mock.add_response( url=self.BLOB_URL, match_headers={"Range": f"bytes={start}-"}, status_code=206, - headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + headers={**self.ETAG, "Content-Range": f"bytes {start}-{size - 1}/{size}"}, content=self.CONTENT[start:], ) @@ -2414,7 +2434,158 @@ def close(self): httpx_mock.add_response(url=self.BLOB_URL, status_code=503, stream=body) with self.open(service) as file: - with pytest.raises(httpx.ReadTimeout): + with pytest.raises(BucketFileReadError) as error: file.read() + assert isinstance(error.value.__cause__, httpx.ReadTimeout) assert body.closed + + def test_a_failed_download_keeps_the_signature_out_of_the_error( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """The query string of a read URL is its signature, which gives access.""" + signed_url = f"{self.BLOB_URL}?sv=2024&se=2099&sig=SECRET" + orchestrator(uri=signed_url) + httpx_mock.add_response( + url=signed_url, status_code=503, headers={"Retry-After": "7"} + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert "SECRET" not in "".join(traceback.format_exception(error.value)) + assert error.value.url == self.BLOB_URL + cause = error.value.__cause__ + assert isinstance(cause, httpx.HTTPStatusError) + assert cause.request.url == self.BLOB_URL + # What the retry of whoever reads the file needs. + assert error.value.status_code == 503 + assert is_retryable_platform_exception(error.value) + assert extract_retry_after_from_chain(error.value) == 7 + + def test_the_read_url_lookup_is_not_retried_by_the_reader( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + """Whoever reads the file retries, so a lookup 503 is retried at one layer.""" + orchestrator(read_uri_lookups=0) + httpx_mock.add_response( + url=read_uri_url, status_code=503, headers={"Retry-After": "0"} + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException) as error: + file.read() + + assert error.value.status_code == 503 + assert len(httpx_mock.get_requests(url=read_uri_url)) == 1 + + def test_a_lookup_failure_is_retried_at_one_layer_by_an_upload( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + read_uri_url: str, + ): + """The upload's five attempts make five lookups, not five each.""" + orchestrator(read_uri_lookups=0) + httpx_mock.add_response( + url=read_uri_url, + status_code=503, + headers={"Retry-After": "0"}, + is_reusable=True, + ) + + with self.open(service) as file: + with pytest.raises(EnrichedException): + service.request( + "POST", "/du_/api/digitization/start", files={"File": file} + ) + + assert len(httpx_mock.get_requests(url=read_uri_url)) == 5 + + def test_an_upload_retries_a_dropped_download_with_the_whole_file( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + base_url: str, + org: str, + tenant: str, + monkeypatch: pytest.MonkeyPatch, + ): + """A platform upload, as `sdk.documents` makes, sends the file again.""" + + class ResetAfterFirstChunk(httpx.SyncByteStream): + def __init__(self, content: bytes): + self.content = content + + def __iter__(self): + yield self.content[:1000] + raise httpx.ReadError("connection reset") + + monkeypatch.setattr(BaseService.request.retry, "wait", wait_none()) # type: ignore[attr-defined] + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, + headers={**self.ETAG, "Content-Length": str(len(self.CONTENT))}, + stream=ResetAfterFirstChunk(self.CONTENT), + ) + httpx_mock.add_response( + url=self.BLOB_URL, headers=self.ETAG, content=self.CONTENT + ) + upload_url = f"{base_url}{org}{tenant}/du_/api/digitization/start" + httpx_mock.add_response(url=upload_url, method="POST", is_reusable=True) + + with self.open(service) as file: + service.request("POST", "/du_/api/digitization/start", files={"File": file}) + + upload = httpx_mock.get_requests(url=upload_url)[-1] + body = upload.read() + assert int(upload.headers["content-length"]) == len(body) + assert self.CONTENT in body + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_a_download_that_ends_before_the_end_of_the_file_raises( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """A storage can send less of the file than the range asked for.""" + orchestrator() + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={ + **self.ETAG, + "Content-Range": f"bytes {start}-{start + 999}/{size}", + }, + content=self.CONTENT[start : start + 1000], + ) + + with self.open(service) as file: + file.seek(start) + with pytest.raises(BucketFileReadError, match="before the end of the file"): + file.read() + + def test_without_an_etag_the_file_is_not_downloaded_again( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """Without an ETag, a replacement of the same size can't be detected.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, content=self.CONTENT, is_reusable=True + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + with pytest.raises(BucketFileChangedError) as error: + file.read() + + assert not error.value.verified + assert "ETag" in str(error.value) diff --git a/packages/uipath-platform/tests/services/test_retry.py b/packages/uipath-platform/tests/services/test_retry.py index f9a4e7741..f1e433ca2 100644 --- a/packages/uipath-platform/tests/services/test_retry.py +++ b/packages/uipath-platform/tests/services/test_retry.py @@ -12,7 +12,7 @@ parse_retry_after, platform_wait_strategy, ) -from uipath.platform.errors import EnrichedException +from uipath.platform.errors import BucketFileReadError, EnrichedException class TestParseRetryAfter: @@ -154,6 +154,17 @@ def test_connect_error(self): err = httpx.ConnectError("[Errno 104] Connection reset by peer") assert is_retryable_platform_exception(err) is True + def test_bucket_file_read_error(self): + """The request sending the file was cut short, so it can be sent again.""" + err = BucketFileReadError("loan-123.pdf") + err.__cause__ = httpx.ReadError("connection reset") + assert is_retryable_platform_exception(err) is True + + def test_read_error_not_retryable(self): + """The service may have the request: only a source read failure retries.""" + err = httpx.ReadError("connection reset") + assert is_retryable_platform_exception(err) is False + def test_enriched_408(self): http_err = _make_http_status_error(408) err = EnrichedException(http_err) From 30ca8f3d148223f8fa4f21f04fff91c19963fe34 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Thu, 3 Dec 2026 12:47:17 +0200 Subject: [PATCH 5/7] fix(buckets): read again from the start on storage without an ETag Native Orchestrator storage can stream a file with no ETag or size. The previous rule refused any second download there, so a retried upload failed instead of sending the file again. A download from the start of the file has the whole file, so it can't mix two versions: without an ETag it is now allowed, and checked by its length against the size already known, from its headers or, when it reports none, as it is read (no extra bytes, no early end). A download from the middle still needs the ETag. Reads also stop at the known size. Checked live on alpha with the ETag and size headers removed and the first download dropped halfway: the documents upload retried, chunked, and the extraction finished. Co-Authored-By: Claude Opus 5.5 --- .../errors/_bucket_file_changed_error.py | 12 ++- .../orchestrator/_bucket_file_reader.py | 54 ++++++++--- .../platform/orchestrator/_buckets_service.py | 8 +- .../tests/services/test_buckets_service.py | 94 ++++++++++++++++++- 4 files changed, 144 insertions(+), 24 deletions(-) diff --git a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py index 3f030c947..e89db668f 100644 --- a/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py +++ b/packages/uipath-platform/src/uipath/platform/errors/_bucket_file_changed_error.py @@ -7,9 +7,10 @@ class BucketFileChangedError(Exception): the read fails instead of mixing bytes of the two versions. Open the file again to read its current version. - Only an ETag tells two versions of the same size apart, so when the storage - reports no ETag, the file is not downloaded a second time: that read fails - with this error too, with `verified` False. + Only an ETag tells two versions of the same size apart. When the storage + reports no ETag, a new download from the start of the file is checked by + its length, and a new download from the middle of the file is refused: that + read fails with this error too, with `verified` False. """ def __init__(self, name: str, *, verified: bool = True) -> None: @@ -19,8 +20,9 @@ def __init__(self, name: str, *, verified: bool = True) -> None: reason = "changed while it was being read" else: reason = ( - "can't be downloaded again while it is being read: the storage " - "reports no version (ETag) for it, so a change could not be detected" + "can't be downloaded again from the middle while it is being read: " + "the storage reports no version (ETag) for it, so a change could " + "not be detected" ) self.message = ( f"The bucket file '{name}' {reason}. " diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py index 43707e636..768ebcff0 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_bucket_file_reader.py @@ -23,9 +23,10 @@ class BucketFileReader(io.RawIOBase): read then continues. When the storage reports no size, it is known once a download reaches the end of the file. Every download must return the same version of the file, by ETag and size; if the file was replaced in the - bucket, the read raises `BucketFileChangedError`. A failed download raises - `BucketFileReadError`; the reader doesn't retry it, whoever reads the file - does. + bucket, the read raises `BucketFileChangedError`. Without an ETag, a new + download from the start of the file is checked by its length, and one from + the middle is refused. A failed download raises `BucketFileReadError`; the + reader doesn't retry it, whoever reads the file does. """ def __init__( @@ -47,6 +48,7 @@ def __init__( self._size_checked = False # a download has reported its headers self._etag: Optional[str] = None self._downloaded = False # a download with content has started + self._download_sized = False # the open download reported the file size self._open_download = open_download self.name = name @@ -83,6 +85,16 @@ def readinto(self, buffer: "WriteableBuffer", /) -> int: """Read the next bytes of the file into `buffer`.""" self._checkClosed() if self._size is not None and self._position >= self._size: + if ( + self._response is not None + and not self._download_sized + and self._download_position == self._size + and (self._pending or self._next_chunk()) + ): + # A download that reported no size has more bytes than the file + # had: it is another version. + self._release() + raise BucketFileChangedError(self.name) self._release() return 0 if self._response is None or self._download_position != self._position: @@ -96,6 +108,10 @@ def readinto(self, buffer: "WriteableBuffer", /) -> int: if self._size is None: # the download ran to the end of the file self._size = self._download_position elif self._download_position < self._size: + if not self._download_sized: + # The storage sent all of the file, and it is shorter + # than it was: it is another version. + raise BucketFileChangedError(self.name) # A storage can send less than the range asked for. raise BucketFileReadError( self.name, @@ -104,6 +120,8 @@ def readinto(self, buffer: "WriteableBuffer", /) -> int: return 0 view = memoryview(buffer).cast("B") count = min(len(view), len(self._pending)) + if self._size is not None: # never past the end of the file + count = min(count, self._size - self._position) view[:count] = self._pending[:count] self._pending = self._pending[count:] self._position += count @@ -131,17 +149,17 @@ def _start(self, start: int) -> None: if response.status_code == 416: # Range Not Satisfiable: start is past the end response.close() # Content-Range: bytes */ - self._check_version( - response, _total_size(response, partial=True), content=False - ) + self._check_version(response, _total_size(response, partial=True)) return partial = response.status_code == 206 + size = _total_size(response, partial) try: - self._check_version(response, _total_size(response, partial), content=True) + self._check_version(response, size, start=start) except BucketFileChangedError: response.close() raise self._response = response + self._download_sized = size is not None # Raw bytes: the size the storage reports is the size of the stored bytes. self._chunks = response.iter_raw(CHUNK_SIZE) self._download_position = start if partial else 0 @@ -155,30 +173,38 @@ def _start(self, start: int) -> None: self._pending = chunk[skipped:] def _check_version( - self, response: httpx.Response, size: Optional[int], *, content: bool + self, + response: httpx.Response, + size: Optional[int], + *, + start: Optional[int] = None, ) -> None: """Keep the first download's version; fail if a later download differs. Every download of the file must return the same version: a rewind or a retried upload after the file was replaced would otherwise cut a larger file off at the old size, or mix bytes of the two versions. Only an - ETag tells two versions of the same size apart, so without one the - file is not downloaded again. + ETag tells two versions of the same size apart. Without one, a new + download from the start can't mix versions, as it has the whole file, + so it is only checked by its size; its length is checked as it is read + when it reports none. A new download from the middle is refused. Args: response: The download's response. size: The file size the response reports, if any. - content: Whether the response has the file's bytes, unlike a 416. + start: Where the download's bytes are read from; None for a + response without the file's bytes, a 416. """ etag = response.headers.get("ETag") if (etag and self._etag and etag != self._etag) or ( size is not None and self._size is not None and size != self._size ): raise BucketFileChangedError(self.name) - if content: - if self._downloaded and not (etag and self._etag): + if start is not None: + if self._downloaded and start and not (etag and self._etag): raise BucketFileChangedError(self.name, verified=False) - self._etag = etag + if not self._downloaded: + self._etag = etag self._downloaded = True if self._size is None: self._size = size diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index c81a6effb..95a6c8f79 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -527,8 +527,9 @@ def open( does, downloads the file again from that position. If the file is replaced in the bucket while it is being read, a read raises `BucketFileChangedError` rather than mixing the two versions. A storage - that reports no ETag can't show a replacement, so there the file is not - downloaded a second time: that read raises `BucketFileChangedError` too. + that reports no ETag can't show a replacement of the same size: there, a + new download from the start of the file is checked by its length, and + a new download from the middle raises `BucketFileChangedError` too. A read is not retried: whoever reads the file retries. If a download fails, the read raises `BucketFileReadError`, or `EnrichedException` for @@ -555,7 +556,8 @@ def open( Exception: If the bucket with the specified key or name is not found. BucketFileReadError: When reading, if a download from the storage fails. BucketFileChangedError: When reading, if the file was replaced in the - bucket, or a replacement can't be ruled out. + bucket, or a replacement can't be ruled out for a download from + the middle of the file. Examples: ```python diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index ef745fe39..ce6ab9751 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -2572,10 +2572,10 @@ def test_a_download_that_ends_before_the_end_of_the_file_raises( with pytest.raises(BucketFileReadError, match="before the end of the file"): file.read() - def test_without_an_etag_the_file_is_not_downloaded_again( + def test_without_an_etag_a_rewind_downloads_the_whole_file_again( self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator ): - """Without an ETag, a replacement of the same size can't be detected.""" + """A download from the start has the whole file, so it can't mix versions.""" orchestrator(read_uri_lookups=2) httpx_mock.add_response( url=self.BLOB_URL, content=self.CONTENT, is_reusable=True @@ -2584,8 +2584,98 @@ def test_without_an_etag_the_file_is_not_downloaded_again( with self.open(service) as file: assert file.read() == self.CONTENT file.seek(0) + assert file.read() == self.CONTENT + + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 + + def test_without_an_etag_the_file_is_not_downloaded_again_from_the_middle( + self, httpx_mock: HTTPXMock, service: BucketsService, orchestrator + ): + """Bytes of two versions of the same size can't be told apart.""" + orchestrator(read_uri_lookups=2) + start, size = 70_000, len(self.CONTENT) + httpx_mock.add_response(url=self.BLOB_URL, content=self.CONTENT) + httpx_mock.add_response( + url=self.BLOB_URL, + match_headers={"Range": f"bytes={start}-"}, + status_code=206, + headers={"Content-Range": f"bytes {start}-{size - 1}/{size}"}, + content=self.CONTENT[start:], + ) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(start) with pytest.raises(BucketFileChangedError) as error: file.read() assert not error.value.verified assert "ETag" in str(error.value) + + @pytest.mark.parametrize( + "replacement", + [ + pytest.param(CONTENT + b"%" * 10, id="larger"), + pytest.param(CONTENT[:-10], id="shorter"), + ], + ) + def test_without_an_etag_or_size_a_replacement_of_another_length_fails( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + replacement: bytes, + ): + """The length is checked as the download is read: neither cut nor short.""" + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + httpx_mock.add_response(url=self.BLOB_URL, stream=IteratorStream([replacement])) + + with self.open(service) as file: + assert file.read() == self.CONTENT + file.seek(0) + with pytest.raises(BucketFileChangedError) as error: + file.read() + + assert error.value.verified + + def test_an_upload_retries_a_dropped_download_without_a_version_or_size( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + base_url: str, + org: str, + tenant: str, + monkeypatch: pytest.MonkeyPatch, + ): + """A storage that streams with no ETag or size still gets the retry.""" + + class ResetAfterFirstChunk(httpx.SyncByteStream): + def __init__(self, content: bytes): + self.content = content + + def __iter__(self): + yield self.content[:1000] + raise httpx.ReadError("connection reset") + + monkeypatch.setattr(BaseService.request.retry, "wait", wait_none()) # type: ignore[attr-defined] + orchestrator(read_uri_lookups=2) + httpx_mock.add_response( + url=self.BLOB_URL, stream=ResetAfterFirstChunk(self.CONTENT) + ) + httpx_mock.add_response( + url=self.BLOB_URL, stream=IteratorStream([self.CONTENT]) + ) + upload_url = f"{base_url}{org}{tenant}/du_/api/digitization/start" + httpx_mock.add_response(url=upload_url, method="POST", is_reusable=True) + + with self.open(service) as file: + service.request("POST", "/du_/api/digitization/start", files={"File": file}) + + upload = httpx_mock.get_requests(url=upload_url)[-1] + assert upload.headers["transfer-encoding"] == "chunked" # no size to send + assert self.CONTENT in upload.read() + assert len(httpx_mock.get_requests(url=self.BLOB_URL)) == 2 From ebdb5c117888ca3282f451cff4d52842580feadc Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Thu, 3 Dec 2026 13:49:55 +0200 Subject: [PATCH 6/7] fix(buckets): keep the read URL out of HTTP client spans The read URL's query string is its signature, and httpx instrumentation, as the agents runtime sets it up, records each request's URL. It redacts `sig` and `Signature`, not every storage's signature, such as `X-Amz-Signature`. The download now runs under `suppress_http_instrumentation()`. Co-Authored-By: Claude Opus 5.5 --- packages/uipath-platform/pyproject.toml | 1 + .../platform/orchestrator/_buckets_service.py | 10 ++-- .../tests/services/test_buckets_service.py | 50 +++++++++++++++++++ packages/uipath-platform/uv.lock | 27 ++++++++++ 4 files changed, 85 insertions(+), 3 deletions(-) diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index cb22f5c61..9f9970eed 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -50,6 +50,7 @@ dev = [ "pytest-mock>=3.11.1", "pre-commit>=4.1.0", "types-PyYAML>=6.0", + "opentelemetry-instrumentation-httpx>=0.60b0", ] [tool.hatch.build.targets.wheel] diff --git a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py index 95a6c8f79..0bc343eab 100644 --- a/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py +++ b/packages/uipath-platform/src/uipath/platform/orchestrator/_buckets_service.py @@ -8,6 +8,7 @@ import httpx from anyio import to_thread +from opentelemetry.instrumentation.utils import suppress_http_instrumentation from tenacity import stop_after_attempt from uipath.core.tracing import traced @@ -1793,9 +1794,12 @@ def _start_download(self, access: _ReadAccess, start: int) -> httpx.Response: # since the client was created. self._add_authorization(headers) client = self._client if access.requires_auth else self.custom_client - response = client.send( - client.build_request("GET", access.uri, headers=headers), stream=True - ) + # The read URL's query string is its signature: keep the download out + # of the spans of HTTP client instrumentation, which record its URL. + with suppress_http_instrumentation(): + response = client.send( + client.build_request("GET", access.uri, headers=headers), stream=True + ) # 416: the start is past the end of the file, which the reader turns # into end of file. if response.is_error and response.status_code != 416: diff --git a/packages/uipath-platform/tests/services/test_buckets_service.py b/packages/uipath-platform/tests/services/test_buckets_service.py index ce6ab9751..ef1ba721d 100644 --- a/packages/uipath-platform/tests/services/test_buckets_service.py +++ b/packages/uipath-platform/tests/services/test_buckets_service.py @@ -6,6 +6,12 @@ import httpx import pytest +from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, +) from pytest_httpx import HTTPXMock, IteratorStream from tenacity import wait_none @@ -2107,6 +2113,22 @@ def mock( return mock + @pytest.fixture + def http_spans(self, httpx_mock: HTTPXMock): + """The spans of httpx instrumentation, as the agents runtime sets it up. + + Instrumented after `httpx_mock`, so that it wraps the mocked transport. + """ + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + instrumentor = HTTPXClientInstrumentor() + instrumentor.instrument(tracer_provider=provider) + try: + yield exporter + finally: + instrumentor.uninstrument() + def open(self, service: BucketsService): return service.open(key=self.BUCKET_KEY, blob_file_path=self.BLOB_FILE_PATH) @@ -2464,6 +2486,34 @@ def test_a_failed_download_keeps_the_signature_out_of_the_error( assert is_retryable_platform_exception(error.value) assert extract_retry_after_from_chain(error.value) == 7 + @pytest.mark.parametrize("status_code", [200, 403]) + def test_the_signature_stays_out_of_http_spans( + self, + httpx_mock: HTTPXMock, + service: BucketsService, + orchestrator, + http_spans: InMemorySpanExporter, + status_code: int, + ): + """HTTP client spans record the URL; OTel redacts `sig`, not every signature.""" + signed_url = f"{self.BLOB_URL}?X-Amz-Credential=KEY&X-Amz-Signature=SECRET" + orchestrator(uri=signed_url) + httpx_mock.add_response( + url=signed_url, status_code=status_code, content=self.CONTENT + ) + + with self.open(service) as file: + if status_code == 200: + assert file.read() == self.CONTENT + else: + with pytest.raises(EnrichedException): + file.read() + + spans = [span.to_json() for span in http_spans.get_finished_spans()] + # The other requests are traced: the instrumentation is on. + assert any("GetReadUri" in span for span in spans) + assert not any("SECRET" in span for span in spans) + def test_the_read_url_lookup_is_not_retried_by_the_reader( self, httpx_mock: HTTPXMock, diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 6e32115d0..c18724fc7 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -472,6 +472,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3b/41/014d40e2b08a5d9d9058ed4967ad992657c203ce0c292ded97364ee7b82a/opentelemetry_instrumentation-0.66b2-py3-none-any.whl", hash = "sha256:fa9ccfdab147a14af8107d19ef0a7b5015675273c5adced7a1fc38f28b42ec4c", size = 36902, upload-time = "2026-10-29T17:37:06.994Z" }, ] +[[package]] +name = "opentelemetry-instrumentation-httpx" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-instrumentation" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "opentelemetry-util-http" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/3204ca7e7d91bd9e1b569a98a5f9252c98ae70ba3bb562d2770c34e21d49/opentelemetry_instrumentation_httpx-0.66b2.tar.gz", hash = "sha256:b4c81e4a6dc7b8d7cb2d3088eb8848f6db6bd4abdc443ac9586ec176f1460187", size = 26638, upload-time = "2026-10-29T17:38:31.46Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/40/37d6161dcd95285c9c3eb75e2dbeb1dbc6e868551532735374918a22e298/opentelemetry_instrumentation_httpx-0.66b2-py3-none-any.whl", hash = "sha256:93e2b6ab1a505d76ec3d98abcf7e8527d4712167d6c3b5ebbb9c68d9309d9ba5", size = 17723, upload-time = "2026-10-29T17:37:33.735Z" }, +] + [[package]] name = "opentelemetry-sdk" version = "1.45.2" @@ -499,6 +515,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, ] +[[package]] +name = "opentelemetry-util-http" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/57/33566966a7bced4d02fbc672f92029184e4a743f5b531e44b4c0dc4c999b/opentelemetry_util_http-0.66b2.tar.gz", hash = "sha256:7ba066ea609202e474679ddf1d0f753a1e6619bd206b36afaecba4bbb86e25d0", size = 11587, upload-time = "2026-10-29T17:38:56.043Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/8d/39885564eefa43f6181acfa3d698af2f6b5fe3e64c86dce3f1b955f6397f/opentelemetry_util_http-0.66b2-py3-none-any.whl", hash = "sha256:c4bb5d6744e60353bcaa3e325bc529a1515346b51cb4d9c8e5b730579337e06d", size = 8383, upload-time = "2026-10-29T17:38:07.462Z" }, +] + [[package]] name = "outcome" version = "1.3.0.post0" @@ -1108,6 +1133,7 @@ dependencies = [ dev = [ { name = "bandit" }, { name = "mypy" }, + { name = "opentelemetry-instrumentation-httpx" }, { name = "pre-commit" }, { name = "pytest" }, { name = "pytest-asyncio" }, @@ -1136,6 +1162,7 @@ requires-dist = [ dev = [ { name = "bandit", specifier = ">=1.8.2" }, { name = "mypy", specifier = ">=1.19.0" }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.60b0" }, { name = "pre-commit", specifier = ">=4.1.0" }, { name = "pytest", specifier = ">=7.4.0" }, { name = "pytest-asyncio", specifier = ">=1.0.0" }, From 70485dfc3198cdb05b2c45231ef85d09ad94d4f4 Mon Sep 17 00:00:00 2001 From: Alexandru Jircan Date: Thu, 3 Dec 2026 13:56:36 +0200 Subject: [PATCH 7/7] chore(platform): bump uipath-platform to 0.3.24 0.3.23 was released from main. The uipath lock also records uipath-platform's new dev dependency. Co-Authored-By: Claude Opus 5.5 --- packages/uipath-platform/pyproject.toml | 2 +- packages/uipath-platform/uv.lock | 2 +- packages/uipath/uv.lock | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index 9f9970eed..da92a1a85 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index c18724fc7..2bc5a556e 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1116,7 +1116,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ee06f3d06..9f4febbbf 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" }, @@ -2912,6 +2912,7 @@ requires-dist = [ dev = [ { name = "bandit", specifier = ">=1.8.2" }, { name = "mypy", specifier = ">=1.19.0" }, + { name = "opentelemetry-instrumentation-httpx", specifier = ">=0.60b0" }, { name = "pre-commit", specifier = ">=4.1.0" }, { name = "pytest", specifier = ">=7.4.0" }, { name = "pytest-asyncio", specifier = ">=1.0.0" },