From 867e5e0bdbe70c010ef9192c5dce4e55166fe295 Mon Sep 17 00:00:00 2001 From: Furkan Coban Date: Wed, 18 Nov 2026 21:40:28 +0300 Subject: [PATCH 1/5] feat: retry unprocessed requests in batch_add_requests --- src/apify_client/_consts.py | 6 + .../_resource_clients/request_queue.py | 203 +++++++++++++----- tests/unit/test_client_request_queue.py | 154 ++++++++++++- 3 files changed, 304 insertions(+), 59 deletions(-) diff --git a/src/apify_client/_consts.py b/src/apify_client/_consts.py index 5e6db6dd..1b06f4a5 100644 --- a/src/apify_client/_consts.py +++ b/src/apify_client/_consts.py @@ -26,6 +26,12 @@ DEFAULT_MIN_DELAY_BETWEEN_RETRIES = timedelta(milliseconds=500) """Default minimum delay between retries.""" +DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS = 3 +"""Default maximum number of retries for unprocessed requests in `batch_add_requests`.""" + +DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES = timedelta(milliseconds=500) +"""Default minimum delay between retries for unprocessed requests in `batch_add_requests`.""" + DEFAULT_WAIT_FOR_FINISH = timedelta(seconds=999999) """Default maximum wait time for job completion (effectively infinite).""" diff --git a/src/apify_client/_resource_clients/request_queue.py b/src/apify_client/_resource_clients/request_queue.py index baa1bf30..d1b537ef 100644 --- a/src/apify_client/_resource_clients/request_queue.py +++ b/src/apify_client/_resource_clients/request_queue.py @@ -3,12 +3,18 @@ import asyncio import json import math +import random +import time from collections.abc import Iterable from queue import Queue from typing import TYPE_CHECKING, Any, Literal from more_itertools import constrained_batches +from apify_client._consts import ( + DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES, + DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS, +) from apify_client._docs import docs_group from apify_client._models import ( AddedRequest, @@ -48,6 +54,7 @@ from datetime import timedelta from apify_client._literals import GeneralAccess + from apify_client._statistics import ClientStatistics from apify_client._typeddicts import ( RequestResourceCamelDict, RequestResourceDict, @@ -70,26 +77,51 @@ def _serialize_requests( requests: list[RequestWithoutId] | list[RequestWithoutIdDict] | list[RequestWithoutIdCamelDict], -) -> list[bytes]: - """Validate requests and serialize each one into the JSON bytes it will occupy in the batch request body. +) -> list[tuple[str, bytes]]: + """Validate requests and serialize each one into `(unique_key, json_bytes)` for batch upload. Each request is serialized exactly once: the same bytes are measured when splitting requests into batches and - then assembled into the request body, so batch sizes are computed on exactly the bytes that get sent. Validation - and serialization happen in a single pass, so each intermediate dict stays transient instead of a whole dict list - being held in memory alongside the serialized requests. Uses the same `json.dumps` options as + then assembled into the request body, so batch sizes are computed on exactly the bytes that get sent. Pairing each + payload with its validated `unique_key` lets unprocessed-request retry rounds reassemble only the remaining items + without re-serializing or decoding payloads. Uses the same `json.dumps` options as `HttpClientBase._prepare_request_call` to keep the wire format consistent with other endpoints. """ - return [ - json.dumps( - (request if isinstance(request, RequestWithoutId) else RequestWithoutId.model_validate(request)).model_dump( - mode='json', by_alias=True, exclude_none=True, fallback=str - ), + serialized = list[tuple[str, bytes]]() + for request in requests: + validated = request if isinstance(request, RequestWithoutId) else RequestWithoutId.model_validate(request) + payload = json.dumps( + validated.model_dump(mode='json', by_alias=True, exclude_none=True, fallback=str), ensure_ascii=False, allow_nan=False, default=str, ).encode('utf-8') - for request in requests - ] + serialized.append((validated.unique_key, payload)) + return serialized + + +def _compute_retry_delay_seconds(attempt: int, min_delay: timedelta) -> float: + """Compute exponential backoff delay with jitter for an unprocessed-requests retry round.""" + return random.uniform(1.0, 2.0) * (2**attempt) * to_seconds(min_delay) + + +def _record_batch_attempt_result( + *, + batch_items: list[tuple[str, bytes]], + batch_response: BatchAddResponse, + processed_unique_keys: set[str], + processed_requests: list[AddedRequest], + attempt: int, + statistics: ClientStatistics, +) -> tuple[list[tuple[str, bytes]], list[UnprocessedRequest]]: + """Accumulate processed requests, record rate limits when needed, and return remaining items to retry.""" + processed_requests.extend(batch_response.data.processed_requests) + unprocessed = batch_response.data.unprocessed_requests + if not unprocessed: + return [], unprocessed + statistics.add_rate_limit_error(attempt + 1) + processed_unique_keys.update(req.unique_key for req in batch_response.data.processed_requests) + remaining = [item for item in batch_items if item[0] not in processed_unique_keys] + return remaining, unprocessed @docs_group('Resource clients') @@ -417,11 +449,16 @@ def batch_add_requests( *, forefront: bool = False, max_parallel: int = 1, + max_unprocessed_requests_retries: int = DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS, + min_delay_between_unprocessed_requests_retries: timedelta = ( + DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES + ), timeout: Timeout = 'medium', ) -> BatchAddResult: """Add requests to the request queue in batches. - Requests are split into batches based on size and processed in parallel. + Requests are split into batches based on size and processed in parallel. Any requests reported as unprocessed + by the API are retried with exponential backoff. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests @@ -431,6 +468,9 @@ def batch_add_requests( max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable to the async client. For the sync client, this value must be set to 1, as parallel execution is not supported. + max_unprocessed_requests_retries: Maximum number of retry attempts for requests returned as unprocessed + by the API. + min_delay_between_unprocessed_requests_retries: Minimum delay before retrying unprocessed requests. timeout: Timeout for the API HTTP request. Returns: @@ -438,8 +478,12 @@ def batch_add_requests( """ if max_parallel != 1: raise NotImplementedError('max_parallel is only supported in async client') + if max_unprocessed_requests_retries < 0: + raise ValueError( + f'max_unprocessed_requests_retries must be non-negative, got {max_unprocessed_requests_retries}' + ) - # Validate the requests and serialize each of them into JSON bytes. + # Validate the requests and serialize each of them into `(unique_key, json_bytes)`. serialized_requests = _serialize_requests(requests) # Build the query parameters shared by all the batch API calls. @@ -453,12 +497,12 @@ def batch_add_requests( serialized_requests, max_size=payload_size_limit_bytes - len(b'[]'), max_count=_RQ_MAX_REQUESTS_PER_BATCH, - get_len=lambda serialized: len(serialized) + len(b','), + get_len=lambda item: len(item[1]) + len(b','), strict=False, ) # Put the batches into the queue for processing. - batch_queue = Queue[Iterable[bytes]]() + batch_queue = Queue[Iterable[tuple[str, bytes]]]() for batch in batches: batch_queue.put(batch) @@ -468,22 +512,40 @@ def batch_add_requests( # Process all batches in the queue sequentially. while not batch_queue.empty(): - request_batch = batch_queue.get() + batch_items = list(batch_queue.get()) + remaining_items = batch_items + processed_unique_keys = set[str]() + batch_processed_requests = list[AddedRequest]() + batch_unprocessed_requests = list[UnprocessedRequest]() + + for attempt in range(1 + max_unprocessed_requests_retries): + response = self._http_client.call( + url=self._build_url('requests/batch'), + method='POST', + headers={'content-type': 'application/json'}, + params=request_params, + data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', + timeout=timeout, + ) - # Send the batch to the API, assembling the body from the already serialized requests. - response = self._http_client.call( - url=self._build_url('requests/batch'), - method='POST', - headers={'content-type': 'application/json'}, - params=request_params, - data=b'[' + b','.join(request_batch) + b']', - timeout=timeout, - ) + result = response_to_dict(response) + batch_response = BatchAddResponse.model_validate(result) + remaining_items, batch_unprocessed_requests = _record_batch_attempt_result( + batch_items=batch_items, + batch_response=batch_response, + processed_unique_keys=processed_unique_keys, + processed_requests=batch_processed_requests, + attempt=attempt, + statistics=self._http_client.stats, + ) + if not remaining_items: + break - result = response_to_dict(response) - batch_response = BatchAddResponse.model_validate(result) - processed_requests.extend(batch_response.data.processed_requests) - unprocessed_requests.extend(batch_response.data.unprocessed_requests) + if attempt < max_unprocessed_requests_retries: + time.sleep(_compute_retry_delay_seconds(attempt, min_delay_between_unprocessed_requests_retries)) + + processed_requests.extend(batch_processed_requests) + unprocessed_requests.extend(batch_unprocessed_requests) return BatchAddResponse.model_construct( data=BatchAddResult.model_construct( @@ -945,13 +1007,15 @@ async def delete_request_lock( async def _batch_add_requests_worker( self, *, - queue: asyncio.Queue[Iterable[bytes]], + queue: asyncio.Queue[Iterable[tuple[str, bytes]]], request_params: QueryParams, + max_unprocessed_requests_retries: int, + min_delay_between_unprocessed_requests_retries: timedelta, timeout: Timeout, ) -> BatchAddResponse: """Worker function to process a batch of requests. - This worker will process batches from the queue. + This worker will process batches from the queue, retrying any unprocessed requests with exponential backoff. Return result containing lists of processed and unprocessed requests by the worker. """ @@ -966,20 +1030,42 @@ async def _batch_add_requests_worker( break try: - # Send the batch to the API, assembling the body from the already serialized requests. - response = await self._http_client.call( - url=self._build_url('requests/batch'), - method='POST', - headers={'content-type': 'application/json'}, - params=request_params, - data=b'[' + b','.join(request_batch) + b']', - timeout=timeout, - ) + batch_items = list(request_batch) + remaining_items = batch_items + processed_unique_keys = set[str]() + batch_processed_requests = list[AddedRequest]() + batch_unprocessed_requests = list[UnprocessedRequest]() + + for attempt in range(1 + max_unprocessed_requests_retries): + response = await self._http_client.call( + url=self._build_url('requests/batch'), + method='POST', + headers={'content-type': 'application/json'}, + params=request_params, + data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', + timeout=timeout, + ) - result = response_to_dict(response) - batch_response = BatchAddResponse.model_validate(result) - processed_requests.extend(batch_response.data.processed_requests) - unprocessed_requests.extend(batch_response.data.unprocessed_requests) + result = response_to_dict(response) + batch_response = BatchAddResponse.model_validate(result) + remaining_items, batch_unprocessed_requests = _record_batch_attempt_result( + batch_items=batch_items, + batch_response=batch_response, + processed_unique_keys=processed_unique_keys, + processed_requests=batch_processed_requests, + attempt=attempt, + statistics=self._http_client.stats, + ) + if not remaining_items: + break + + if attempt < max_unprocessed_requests_retries: + await asyncio.sleep( + _compute_retry_delay_seconds(attempt, min_delay_between_unprocessed_requests_retries) + ) + + processed_requests.extend(batch_processed_requests) + unprocessed_requests.extend(batch_unprocessed_requests) finally: # Mark the batch as done whether it succeeded or failed. @@ -998,11 +1084,16 @@ async def batch_add_requests( *, forefront: bool = False, max_parallel: int = 5, + max_unprocessed_requests_retries: int = DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS, + min_delay_between_unprocessed_requests_retries: timedelta = ( + DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES + ), timeout: Timeout = 'medium', ) -> BatchAddResult: """Add requests to the request queue in batches. - Requests are split into batches based on size and processed in parallel. + Requests are split into batches based on size and processed in parallel. Any requests reported as unprocessed + by the API are retried with exponential backoff. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests @@ -1012,11 +1103,19 @@ async def batch_add_requests( max_parallel: Specifies the maximum number of parallel tasks for API calls. This is only applicable to the async client. For the sync client, this value must be set to 1, as parallel execution is not supported. + max_unprocessed_requests_retries: Maximum number of retry attempts for requests returned as unprocessed + by the API. + min_delay_between_unprocessed_requests_retries: Minimum delay before retrying unprocessed requests. timeout: Timeout for the API HTTP request. Returns: Result containing lists of processed and unprocessed requests. """ + if max_unprocessed_requests_retries < 0: + raise ValueError( + f'max_unprocessed_requests_retries must be non-negative, got {max_unprocessed_requests_retries}' + ) + # Validate and serialize the requests in a worker thread, as it is CPU-bound and would block the event loop. serialized_requests = await asyncio.to_thread(_serialize_requests, requests) @@ -1031,12 +1130,12 @@ async def batch_add_requests( serialized_requests, max_size=payload_size_limit_bytes - len(b'[]'), max_count=_RQ_MAX_REQUESTS_PER_BATCH, - get_len=lambda serialized: len(serialized) + len(b','), + get_len=lambda item: len(item[1]) + len(b','), strict=False, ) # Create a queue with all the batches, from which the worker tasks will consume them. - batch_queue: asyncio.Queue[Iterable[bytes]] = asyncio.Queue() + batch_queue: asyncio.Queue[Iterable[tuple[str, bytes]]] = asyncio.Queue() for batch in batches: await batch_queue.put(batch) @@ -1047,7 +1146,13 @@ async def batch_add_requests( workers = [ tg.create_task( self._batch_add_requests_worker( - queue=batch_queue, request_params=request_params, timeout=timeout + queue=batch_queue, + request_params=request_params, + max_unprocessed_requests_retries=max_unprocessed_requests_retries, + min_delay_between_unprocessed_requests_retries=( + min_delay_between_unprocessed_requests_retries + ), + timeout=timeout, ), name=f'batch_add_requests_worker_{i}', ) diff --git a/tests/unit/test_client_request_queue.py b/tests/unit/test_client_request_queue.py index 728fa459..91c44200 100644 --- a/tests/unit/test_client_request_queue.py +++ b/tests/unit/test_client_request_queue.py @@ -3,6 +3,7 @@ import gzip import json import re +from datetime import timedelta from typing import TYPE_CHECKING import pytest @@ -76,19 +77,35 @@ async def test_batch_processed_partially_async(httpserver: HTTPServer) -> None: api_public_url=server_url, ) - httpserver.expect_oneshot_request(re.compile(r'.*'), method='POST').respond_with_data( - status=200, response_data=_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT - ) + attempt = 0 + + def handler(_request: Request) -> Response: + nonlocal attempt + attempt += 1 + if attempt == 1: + return Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') + return Response( + '{"data": {"processedRequests": [], "unprocessedRequests": ' + '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}', + status=200, + content_type='application/json', + ) + + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) requests: list[RequestWithoutIdDict] = [ {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, ] rq_client = client.request_queue(request_queue_id='whatever') - batch_response = await rq_client.batch_add_requests(requests=requests) - assert requests[0]['unique_key'] in {request.unique_key for request in batch_response.processed_requests} + batch_response = await rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + assert [request.unique_key for request in batch_response.processed_requests] == [requests[0]['unique_key']] assert len(batch_response.unprocessed_requests) == 1 assert batch_response.unprocessed_requests[0].unique_key == requests[1]['unique_key'] + assert client.stats.rate_limit_errors == {0: 1, 1: 1, 2: 1, 3: 1} def test_batch_not_processed_raises_exception_sync(httpserver: HTTPServer) -> None: @@ -247,19 +264,136 @@ def test_batch_processed_partially_sync(httpserver: HTTPServer) -> None: api_public_url=server_url, ) - httpserver.expect_oneshot_request(re.compile(r'.*'), method='POST').respond_with_data( - status=200, response_data=_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT - ) + attempt = 0 + + def handler(_request: Request) -> Response: + nonlocal attempt + attempt += 1 + if attempt == 1: + return Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') + return Response( + '{"data": {"processedRequests": [], "unprocessedRequests": ' + '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}', + status=200, + content_type='application/json', + ) + + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) requests: list[RequestWithoutIdDict] = [ {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, ] rq_client = client.request_queue(request_queue_id='whatever') - batch_response = rq_client.batch_add_requests(requests=requests) - assert requests[0]['unique_key'] in {request.unique_key for request in batch_response.processed_requests} + batch_response = rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + assert [request.unique_key for request in batch_response.processed_requests] == [requests[0]['unique_key']] assert len(batch_response.unprocessed_requests) == 1 assert batch_response.unprocessed_requests[0].unique_key == requests[1]['unique_key'] + assert client.stats.rate_limit_errors == {0: 1, 1: 1, 2: 1, 3: 1} + + +def _progressive_retry_handler(sent_keys: list[list[str]]) -> Callable[[Request], Response]: + """Respond to 3 rounds of batch-add calls, processing one request per round.""" + round_num = 0 + + def handler(request: Request) -> Response: + nonlocal round_num + round_num += 1 + body = request.get_data() + raw = gzip.decompress(body) if request.headers.get('Content-Encoding') == 'gzip' else body + items = json.loads(raw) + sent_keys.append([item['uniqueKey'] for item in items]) + + processed = [ + { + 'requestId': f'id_{round_num}', + 'uniqueKey': f'http://example.com/{round_num}', + 'wasAlreadyPresent': False, + 'wasAlreadyHandled': False, + } + ] + unprocessed = [ + {'uniqueKey': f'http://example.com/{k}', 'url': f'http://example.com/{k}', 'method': 'GET'} + for k in range(round_num + 1, 4) + ] + return Response( + json.dumps({'data': {'processedRequests': processed, 'unprocessedRequests': unprocessed}}), + status=200, + content_type='application/json', + ) + + return handler + + +async def test_batch_add_requests_retries_unprocessed_requests_async(httpserver: HTTPServer) -> None: + """Unprocessed requests are retried by `unique_key` until processed and rate limits are tracked.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClientAsync(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + sent_keys = list[list[str]]() + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler( + _progressive_retry_handler(sent_keys) + ) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': f'http://example.com/{i}', 'url': f'http://example.com/{i}', 'method': 'GET'} + for i in range(1, 4) + ] + rq_client = client.request_queue(request_queue_id='whatever') + + result = await rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert sent_keys == [ + ['http://example.com/1', 'http://example.com/2', 'http://example.com/3'], + ['http://example.com/2', 'http://example.com/3'], + ['http://example.com/3'], + ] + assert [req.unique_key for req in result.processed_requests] == [ + 'http://example.com/1', + 'http://example.com/2', + 'http://example.com/3', + ] + assert result.unprocessed_requests == [] + assert client.stats.rate_limit_errors == {0: 1, 1: 1} + + +def test_batch_add_requests_retries_unprocessed_requests_sync(httpserver: HTTPServer) -> None: + """Unprocessed requests are retried by `unique_key` until processed and rate limits are tracked.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClient(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + sent_keys = list[list[str]]() + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler( + _progressive_retry_handler(sent_keys) + ) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': f'http://example.com/{i}', 'url': f'http://example.com/{i}', 'method': 'GET'} + for i in range(1, 4) + ] + rq_client = client.request_queue(request_queue_id='whatever') + + result = rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert sent_keys == [ + ['http://example.com/1', 'http://example.com/2', 'http://example.com/3'], + ['http://example.com/2', 'http://example.com/3'], + ['http://example.com/3'], + ] + assert [req.unique_key for req in result.processed_requests] == [ + 'http://example.com/1', + 'http://example.com/2', + 'http://example.com/3', + ] + assert result.unprocessed_requests == [] + assert client.stats.rate_limit_errors == {0: 1, 1: 1} _REQUEST_REGISTRATION_RESPONSE_CONTENT = ( From 04d68fc93875fa68b1a6d9ff9a8ad81402ff56c2 Mon Sep 17 00:00:00 2001 From: Furkan Coban Date: Fri, 20 Nov 2026 15:54:27 +0300 Subject: [PATCH 2/5] refactor: address batch_add_requests retry review feedback --- docs/04_upgrading/upgrading_to_v3.mdx | 5 +- .../_resource_clients/request_queue.py | 166 ++++++++---- src/apify_client/_statistics.py | 5 +- tests/unit/test_client_request_queue.py | 246 +++++++++++++++--- 4 files changed, 331 insertions(+), 91 deletions(-) diff --git a/docs/04_upgrading/upgrading_to_v3.mdx b/docs/04_upgrading/upgrading_to_v3.mdx index 61a3c0ef..cb91d4dd 100644 --- a/docs/04_upgrading/upgrading_to_v3.mdx +++ b/docs/04_upgrading/upgrading_to_v3.mdx @@ -135,9 +135,12 @@ Affected types: `ActorJobStatus`, `ActorPermissionLevel`, `ErrorType`, `GeneralA ## Removed deprecated APIs - `DatasetClient.download_items()` → use `DatasetClient.get_items_as_bytes()` (identical signature). -- `max_unprocessed_requests_retries` and `min_delay_between_unprocessed_requests_retries` on `RequestQueueClient.batch_add_requests()` — were no-ops; drop them. - `exclusive_start_id` on `RequestQueueClient.list_requests()` → use `cursor` with `next_cursor` from the previous response, or `iterate_requests()`. +## Retrying unprocessed requests in batch_add_requests + +`max_unprocessed_requests_retries` and `min_delay_between_unprocessed_requests_retries` on `RequestQueueClient.batch_add_requests()` now actively retry requests returned as unprocessed with exponential backoff (defaulting to 3 retries and a 500 ms `timedelta` minimum delay). Pass `max_unprocessed_requests_retries=0` to disable retries. + ## Pluggable HTTP client Additive change, non-breaking. The HTTP layer is now abstracted behind the `HttpClient` and `HttpClientAsync` base classes, so you can swap the underlying transport for your own implementation. The default client built on [Impit](https://github.com/apify/impit) is unchanged and existing code keeps working out of the box. To plug in a custom client, pass an instance to `ApifyClient.with_custom_http_client()` — see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients) for the full walkthrough. diff --git a/src/apify_client/_resource_clients/request_queue.py b/src/apify_client/_resource_clients/request_queue.py index d1b537ef..2cb69efa 100644 --- a/src/apify_client/_resource_clients/request_queue.py +++ b/src/apify_client/_resource_clients/request_queue.py @@ -6,8 +6,9 @@ import random import time from collections.abc import Iterable +from datetime import timedelta from queue import Queue -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING, Any, Literal, NamedTuple from more_itertools import constrained_batches @@ -16,6 +17,7 @@ DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS, ) from apify_client._docs import docs_group +from apify_client._logging import logger from apify_client._models import ( AddedRequest, AddRequestResponse, @@ -51,10 +53,8 @@ if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterator - from datetime import timedelta from apify_client._literals import GeneralAccess - from apify_client._statistics import ClientStatistics from apify_client._typeddicts import ( RequestResourceCamelDict, RequestResourceDict, @@ -99,29 +99,61 @@ def _serialize_requests( return serialized +def _validate_batch_retry_params( + *, + max_unprocessed_requests_retries: int, + min_delay_between_unprocessed_requests_retries: timedelta, +) -> None: + """Validate retry count and minimum backoff delay for `batch_add_requests`.""" + if max_unprocessed_requests_retries < 0: + raise ValueError( + f'max_unprocessed_requests_retries must be non-negative, got {max_unprocessed_requests_retries}' + ) + if min_delay_between_unprocessed_requests_retries < timedelta(0): + raise ValueError( + 'min_delay_between_unprocessed_requests_retries must be non-negative, ' + f'got {min_delay_between_unprocessed_requests_retries}' + ) + + def _compute_retry_delay_seconds(attempt: int, min_delay: timedelta) -> float: """Compute exponential backoff delay with jitter for an unprocessed-requests retry round.""" return random.uniform(1.0, 2.0) * (2**attempt) * to_seconds(min_delay) -def _record_batch_attempt_result( +class _BatchAttemptResult(NamedTuple): + """Result of evaluating a single `batch_add_requests` attempt.""" + + processed_requests: list[AddedRequest] + unprocessed_requests: list[UnprocessedRequest] + remaining_items: list[tuple[str, bytes]] + processed_unique_keys: frozenset[str] + + +def _extract_batch_attempt_result( *, batch_items: list[tuple[str, bytes]], batch_response: BatchAddResponse, - processed_unique_keys: set[str], - processed_requests: list[AddedRequest], - attempt: int, - statistics: ClientStatistics, -) -> tuple[list[tuple[str, bytes]], list[UnprocessedRequest]]: - """Accumulate processed requests, record rate limits when needed, and return remaining items to retry.""" - processed_requests.extend(batch_response.data.processed_requests) + already_processed_keys: frozenset[str], +) -> _BatchAttemptResult: + """Compute newly processed requests, unprocessed requests, and remaining items to retry.""" + new_processed = batch_response.data.processed_requests unprocessed = batch_response.data.unprocessed_requests if not unprocessed: - return [], unprocessed - statistics.add_rate_limit_error(attempt + 1) - processed_unique_keys.update(req.unique_key for req in batch_response.data.processed_requests) - remaining = [item for item in batch_items if item[0] not in processed_unique_keys] - return remaining, unprocessed + return _BatchAttemptResult( + processed_requests=new_processed, + unprocessed_requests=unprocessed, + remaining_items=[], + processed_unique_keys=already_processed_keys, + ) + updated_keys = already_processed_keys | {req.unique_key for req in new_processed} + remaining = [item for item in batch_items if item[0] not in updated_keys] + return _BatchAttemptResult( + processed_requests=new_processed, + unprocessed_requests=unprocessed, + remaining_items=remaining, + processed_unique_keys=updated_keys, + ) @docs_group('Resource clients') @@ -478,10 +510,10 @@ def batch_add_requests( """ if max_parallel != 1: raise NotImplementedError('max_parallel is only supported in async client') - if max_unprocessed_requests_retries < 0: - raise ValueError( - f'max_unprocessed_requests_retries must be non-negative, got {max_unprocessed_requests_retries}' - ) + _validate_batch_retry_params( + max_unprocessed_requests_retries=max_unprocessed_requests_retries, + min_delay_between_unprocessed_requests_retries=min_delay_between_unprocessed_requests_retries, + ) # Validate the requests and serialize each of them into `(unique_key, json_bytes)`. serialized_requests = _serialize_requests(requests) @@ -514,30 +546,41 @@ def batch_add_requests( while not batch_queue.empty(): batch_items = list(batch_queue.get()) remaining_items = batch_items - processed_unique_keys = set[str]() + processed_unique_keys = frozenset[str]() batch_processed_requests = list[AddedRequest]() batch_unprocessed_requests = list[UnprocessedRequest]() for attempt in range(1 + max_unprocessed_requests_retries): - response = self._http_client.call( - url=self._build_url('requests/batch'), - method='POST', - headers={'content-type': 'application/json'}, - params=request_params, - data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', - timeout=timeout, - ) + try: + response = self._http_client.call( + url=self._build_url('requests/batch'), + method='POST', + headers={'content-type': 'application/json'}, + params=request_params, + data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', + timeout=timeout, + ) + result = response_to_dict(response) + batch_response = BatchAddResponse.model_validate(result) + except Exception: + if attempt == 0: + raise + logger.exception( + 'Failed to retry unprocessed requests in request queue batch; returning partial result.' + ) + break - result = response_to_dict(response) - batch_response = BatchAddResponse.model_validate(result) - remaining_items, batch_unprocessed_requests = _record_batch_attempt_result( + attempt_result = _extract_batch_attempt_result( batch_items=batch_items, batch_response=batch_response, - processed_unique_keys=processed_unique_keys, - processed_requests=batch_processed_requests, - attempt=attempt, - statistics=self._http_client.stats, + already_processed_keys=processed_unique_keys, ) + batch_processed_requests.extend(attempt_result.processed_requests) + batch_unprocessed_requests = attempt_result.unprocessed_requests + remaining_items = attempt_result.remaining_items + processed_unique_keys = attempt_result.processed_unique_keys + if batch_unprocessed_requests: + self._http_client.stats.add_rate_limit_error(attempt + 1) if not remaining_items: break @@ -1032,30 +1075,41 @@ async def _batch_add_requests_worker( try: batch_items = list(request_batch) remaining_items = batch_items - processed_unique_keys = set[str]() + processed_unique_keys = frozenset[str]() batch_processed_requests = list[AddedRequest]() batch_unprocessed_requests = list[UnprocessedRequest]() for attempt in range(1 + max_unprocessed_requests_retries): - response = await self._http_client.call( - url=self._build_url('requests/batch'), - method='POST', - headers={'content-type': 'application/json'}, - params=request_params, - data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', - timeout=timeout, - ) + try: + response = await self._http_client.call( + url=self._build_url('requests/batch'), + method='POST', + headers={'content-type': 'application/json'}, + params=request_params, + data=b'[' + b','.join(payload for _, payload in remaining_items) + b']', + timeout=timeout, + ) + result = response_to_dict(response) + batch_response = BatchAddResponse.model_validate(result) + except Exception: + if attempt == 0: + raise + logger.exception( + 'Failed to retry unprocessed requests in request queue batch; returning partial result.' + ) + break - result = response_to_dict(response) - batch_response = BatchAddResponse.model_validate(result) - remaining_items, batch_unprocessed_requests = _record_batch_attempt_result( + attempt_result = _extract_batch_attempt_result( batch_items=batch_items, batch_response=batch_response, - processed_unique_keys=processed_unique_keys, - processed_requests=batch_processed_requests, - attempt=attempt, - statistics=self._http_client.stats, + already_processed_keys=processed_unique_keys, ) + batch_processed_requests.extend(attempt_result.processed_requests) + batch_unprocessed_requests = attempt_result.unprocessed_requests + remaining_items = attempt_result.remaining_items + processed_unique_keys = attempt_result.processed_unique_keys + if batch_unprocessed_requests: + self._http_client.stats.add_rate_limit_error(attempt + 1) if not remaining_items: break @@ -1111,10 +1165,10 @@ async def batch_add_requests( Returns: Result containing lists of processed and unprocessed requests. """ - if max_unprocessed_requests_retries < 0: - raise ValueError( - f'max_unprocessed_requests_retries must be non-negative, got {max_unprocessed_requests_retries}' - ) + _validate_batch_retry_params( + max_unprocessed_requests_retries=max_unprocessed_requests_retries, + min_delay_between_unprocessed_requests_retries=min_delay_between_unprocessed_requests_retries, + ) # Validate and serialize the requests in a worker thread, as it is CPU-bound and would block the event loop. serialized_requests = await asyncio.to_thread(_serialize_requests, requests) diff --git a/src/apify_client/_statistics.py b/src/apify_client/_statistics.py index a288556d..f312032d 100644 --- a/src/apify_client/_statistics.py +++ b/src/apify_client/_statistics.py @@ -18,9 +18,10 @@ class ClientStatistics: """Total number of HTTP requests sent, including retries.""" rate_limit_errors: defaultdict[int, int] = field(default_factory=lambda: defaultdict(int)) - """Number of rate limit (429) errors per attempt, keyed by the 0-based attempt index. + """Number of rate limit errors per attempt, keyed by the 0-based attempt index. - Reading a missing key adds it with a count of `0`. Use `.get()` to read a count without changing the dict. + Counts HTTP 429 responses as well as `batch_add_requests` rounds that return unprocessed requests. Reading a + missing key adds it with a count of `0`. Use `.get()` to read a count without changing the dict. """ def add_rate_limit_error(self, attempt: int) -> None: diff --git a/tests/unit/test_client_request_queue.py b/tests/unit/test_client_request_queue.py index 91c44200..9b9bcdfa 100644 --- a/tests/unit/test_client_request_queue.py +++ b/tests/unit/test_client_request_queue.py @@ -2,9 +2,11 @@ import gzip import json +import logging import re from datetime import timedelta from typing import TYPE_CHECKING +from unittest.mock import Mock import pytest from pydantic import ValidationError @@ -77,19 +79,16 @@ async def test_batch_processed_partially_async(httpserver: HTTPServer) -> None: api_public_url=server_url, ) - attempt = 0 - - def handler(_request: Request) -> Response: - nonlocal attempt - attempt += 1 - if attempt == 1: - return Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') - return Response( - '{"data": {"processedRequests": [], "unprocessedRequests": ' - '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}', - status=200, - content_type='application/json', - ) + unprocessed_body = ( + '{"data": {"processedRequests": [], "unprocessedRequests": ' + '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}' + ) + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + *(Response(unprocessed_body, status=200, content_type='application/json') for _ in range(3)), + ] + ) httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) requests: list[RequestWithoutIdDict] = [ @@ -102,6 +101,7 @@ def handler(_request: Request) -> Response: requests=requests, min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), ) + assert handler.call_count == 4 assert [request.unique_key for request in batch_response.processed_requests] == [requests[0]['unique_key']] assert len(batch_response.unprocessed_requests) == 1 assert batch_response.unprocessed_requests[0].unique_key == requests[1]['unique_key'] @@ -264,19 +264,16 @@ def test_batch_processed_partially_sync(httpserver: HTTPServer) -> None: api_public_url=server_url, ) - attempt = 0 - - def handler(_request: Request) -> Response: - nonlocal attempt - attempt += 1 - if attempt == 1: - return Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') - return Response( - '{"data": {"processedRequests": [], "unprocessedRequests": ' - '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}', - status=200, - content_type='application/json', - ) + unprocessed_body = ( + '{"data": {"processedRequests": [], "unprocessedRequests": ' + '[{"uniqueKey": "http://example.com/2", "url": "http://example.com/2", "method": "GET"}]}}' + ) + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + *(Response(unprocessed_body, status=200, content_type='application/json') for _ in range(3)), + ] + ) httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) requests: list[RequestWithoutIdDict] = [ @@ -289,19 +286,19 @@ def handler(_request: Request) -> Response: requests=requests, min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), ) + assert handler.call_count == 4 assert [request.unique_key for request in batch_response.processed_requests] == [requests[0]['unique_key']] assert len(batch_response.unprocessed_requests) == 1 assert batch_response.unprocessed_requests[0].unique_key == requests[1]['unique_key'] assert client.stats.rate_limit_errors == {0: 1, 1: 1, 2: 1, 3: 1} -def _progressive_retry_handler(sent_keys: list[list[str]]) -> Callable[[Request], Response]: - """Respond to 3 rounds of batch-add calls, processing one request per round.""" - round_num = 0 +def _progressive_retry_handler(sent_keys: list[list[str]]) -> Mock: + """Return a mock handler that processes one request per round across 3 rounds.""" + handler = Mock() - def handler(request: Request) -> Response: - nonlocal round_num - round_num += 1 + def respond(request: Request) -> Response: + round_num = handler.call_count body = request.get_data() raw = gzip.decompress(body) if request.headers.get('Content-Encoding') == 'gzip' else body items = json.loads(raw) @@ -325,6 +322,7 @@ def handler(request: Request) -> Response: content_type='application/json', ) + handler.side_effect = respond return handler @@ -396,6 +394,190 @@ def test_batch_add_requests_retries_unprocessed_requests_sync(httpserver: HTTPSe assert client.stats.rate_limit_errors == {0: 1, 1: 1} +async def test_batch_add_requests_zero_retries_async(httpserver: HTTPServer) -> None: + """Setting `max_unprocessed_requests_retries=0` sends one call and returns unprocessed requests without retrying.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClientAsync(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + handler = Mock( + return_value=Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + result = await rq_client.batch_add_requests(requests=requests, max_unprocessed_requests_retries=0) + + assert handler.call_count == 1 + assert [req.unique_key for req in result.processed_requests] == ['http://example.com/1'] + assert [req.unique_key for req in result.unprocessed_requests] == ['http://example.com/2'] + assert client.stats.rate_limit_errors == {0: 1} + + +def test_batch_add_requests_zero_retries_sync(httpserver: HTTPServer) -> None: + """Setting `max_unprocessed_requests_retries=0` sends one call and returns unprocessed requests without retrying.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClient(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + handler = Mock( + return_value=Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json') + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + result = rq_client.batch_add_requests(requests=requests, max_unprocessed_requests_retries=0) + + assert handler.call_count == 1 + assert [req.unique_key for req in result.processed_requests] == ['http://example.com/1'] + assert [req.unique_key for req in result.unprocessed_requests] == ['http://example.com/2'] + assert client.stats.rate_limit_errors == {0: 1} + + +@pytest.mark.parametrize( + ('max_retries', 'min_delay'), + [ + pytest.param(-1, timedelta(milliseconds=500), id='negative_retries'), + pytest.param(3, timedelta(milliseconds=-1), id='negative_min_delay'), + ], +) +async def test_batch_add_requests_invalid_retry_params_async( + max_retries: int, + min_delay: timedelta, +) -> None: + """Negative retry count or minimum delay raises `ValueError` in the async client.""" + client = ApifyClientAsync(token='placeholder_token') + rq_client = client.request_queue(request_queue_id='whatever') + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + ] + + with pytest.raises(ValueError, match='must be non-negative'): + await rq_client.batch_add_requests( + requests=requests, + max_unprocessed_requests_retries=max_retries, + min_delay_between_unprocessed_requests_retries=min_delay, + ) + + +@pytest.mark.parametrize( + ('max_retries', 'min_delay'), + [ + pytest.param(-1, timedelta(milliseconds=500), id='negative_retries'), + pytest.param(3, timedelta(milliseconds=-1), id='negative_min_delay'), + ], +) +def test_batch_add_requests_invalid_retry_params_sync( + max_retries: int, + min_delay: timedelta, +) -> None: + """Negative retry count or minimum delay raises `ValueError` in the sync client.""" + client = ApifyClient(token='placeholder_token') + rq_client = client.request_queue(request_queue_id='whatever') + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + ] + + with pytest.raises(ValueError, match='must be non-negative'): + rq_client.batch_add_requests( + requests=requests, + max_unprocessed_requests_retries=max_retries, + min_delay_between_unprocessed_requests_retries=min_delay, + ) + + +async def test_batch_add_requests_retry_round_error_returns_partial_result_async( + httpserver: HTTPServer, + caplog: pytest.LogCaptureFixture, +) -> None: + """A failing retry round logs the error and returns requests added in earlier rounds plus remaining unprocessed.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClientAsync( + token='placeholder_token', + api_url=server_url, + api_public_url=server_url, + max_retries=1, + min_delay_between_retries=timedelta(milliseconds=1), + ) + + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + Response( + '{"error": {"type": "internal-error", "message": "boom"}}', status=500, content_type='application/json' + ), + Response( + '{"error": {"type": "internal-error", "message": "boom"}}', status=500, content_type='application/json' + ), + ] + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + with caplog.at_level(logging.ERROR, logger='apify_client'): + result = await rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert [req.unique_key for req in result.processed_requests] == ['http://example.com/1'] + assert [req.unique_key for req in result.unprocessed_requests] == ['http://example.com/2'] + assert any('Failed to retry unprocessed requests' in record.message for record in caplog.records) + + +def test_batch_add_requests_retry_round_error_returns_partial_result_sync( + httpserver: HTTPServer, + caplog: pytest.LogCaptureFixture, +) -> None: + """A failing retry round logs the error and returns requests added in earlier rounds plus remaining unprocessed.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClient( + token='placeholder_token', + api_url=server_url, + api_public_url=server_url, + max_retries=1, + min_delay_between_retries=timedelta(milliseconds=1), + ) + + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + Response( + '{"error": {"type": "internal-error", "message": "boom"}}', status=500, content_type='application/json' + ), + Response( + '{"error": {"type": "internal-error", "message": "boom"}}', status=500, content_type='application/json' + ), + ] + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + with caplog.at_level(logging.ERROR, logger='apify_client'): + result = rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert [req.unique_key for req in result.processed_requests] == ['http://example.com/1'] + assert [req.unique_key for req in result.unprocessed_requests] == ['http://example.com/2'] + assert any('Failed to retry unprocessed requests' in record.message for record in caplog.records) + + _REQUEST_REGISTRATION_RESPONSE_CONTENT = ( '{"data": {"requestId": "YiKoxjkaS9gjGTqhF", "wasAlreadyPresent": false, "wasAlreadyHandled": false}}' ) From 559a977784cbd6f3092ba5a33ca1983f39924512 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 23 Nov 2026 12:38:09 +0100 Subject: [PATCH 3/5] docs: revert upgrading guide changes --- docs/04_upgrading/upgrading_to_v3.mdx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/docs/04_upgrading/upgrading_to_v3.mdx b/docs/04_upgrading/upgrading_to_v3.mdx index cb91d4dd..61a3c0ef 100644 --- a/docs/04_upgrading/upgrading_to_v3.mdx +++ b/docs/04_upgrading/upgrading_to_v3.mdx @@ -135,12 +135,9 @@ Affected types: `ActorJobStatus`, `ActorPermissionLevel`, `ErrorType`, `GeneralA ## Removed deprecated APIs - `DatasetClient.download_items()` → use `DatasetClient.get_items_as_bytes()` (identical signature). +- `max_unprocessed_requests_retries` and `min_delay_between_unprocessed_requests_retries` on `RequestQueueClient.batch_add_requests()` — were no-ops; drop them. - `exclusive_start_id` on `RequestQueueClient.list_requests()` → use `cursor` with `next_cursor` from the previous response, or `iterate_requests()`. -## Retrying unprocessed requests in batch_add_requests - -`max_unprocessed_requests_retries` and `min_delay_between_unprocessed_requests_retries` on `RequestQueueClient.batch_add_requests()` now actively retry requests returned as unprocessed with exponential backoff (defaulting to 3 retries and a 500 ms `timedelta` minimum delay). Pass `max_unprocessed_requests_retries=0` to disable retries. - ## Pluggable HTTP client Additive change, non-breaking. The HTTP layer is now abstracted behind the `HttpClient` and `HttpClientAsync` base classes, so you can swap the underlying transport for your own implementation. The default client built on [Impit](https://github.com/apify/impit) is unchanged and existing code keeps working out of the box. To plug in a custom client, pass an instance to `ApifyClient.with_custom_http_client()` — see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients) for the full walkthrough. From 1af640731460cc9b09e8a57cec535daddff55d59 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 23 Nov 2026 12:59:08 +0100 Subject: [PATCH 4/5] refactor: simplify batch add retries and re-raise response validation errors --- .../_resource_clients/request_queue.py | 97 ++++++------------- tests/unit/test_client_request_queue.py | 82 ++++++++++++++++ 2 files changed, 114 insertions(+), 65 deletions(-) diff --git a/src/apify_client/_resource_clients/request_queue.py b/src/apify_client/_resource_clients/request_queue.py index 2cb69efa..4a0c0f26 100644 --- a/src/apify_client/_resource_clients/request_queue.py +++ b/src/apify_client/_resource_clients/request_queue.py @@ -8,9 +8,10 @@ from collections.abc import Iterable from datetime import timedelta from queue import Queue -from typing import TYPE_CHECKING, Any, Literal, NamedTuple +from typing import TYPE_CHECKING, Any, Literal from more_itertools import constrained_batches +from pydantic import ValidationError from apify_client._consts import ( DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES, @@ -121,39 +122,15 @@ def _compute_retry_delay_seconds(attempt: int, min_delay: timedelta) -> float: return random.uniform(1.0, 2.0) * (2**attempt) * to_seconds(min_delay) -class _BatchAttemptResult(NamedTuple): - """Result of evaluating a single `batch_add_requests` attempt.""" - - processed_requests: list[AddedRequest] - unprocessed_requests: list[UnprocessedRequest] - remaining_items: list[tuple[str, bytes]] - processed_unique_keys: frozenset[str] - - -def _extract_batch_attempt_result( - *, - batch_items: list[tuple[str, bytes]], +def _remaining_batch_items( + remaining_items: list[tuple[str, bytes]], batch_response: BatchAddResponse, - already_processed_keys: frozenset[str], -) -> _BatchAttemptResult: - """Compute newly processed requests, unprocessed requests, and remaining items to retry.""" - new_processed = batch_response.data.processed_requests - unprocessed = batch_response.data.unprocessed_requests - if not unprocessed: - return _BatchAttemptResult( - processed_requests=new_processed, - unprocessed_requests=unprocessed, - remaining_items=[], - processed_unique_keys=already_processed_keys, - ) - updated_keys = already_processed_keys | {req.unique_key for req in new_processed} - remaining = [item for item in batch_items if item[0] not in updated_keys] - return _BatchAttemptResult( - processed_requests=new_processed, - unprocessed_requests=unprocessed, - remaining_items=remaining, - processed_unique_keys=updated_keys, - ) +) -> list[tuple[str, bytes]]: + """Return the items of a batch round that the API did not process and that need another round.""" + if not batch_response.data.unprocessed_requests: + return [] + processed_keys = {request.unique_key for request in batch_response.data.processed_requests} + return [item for item in remaining_items if item[0] not in processed_keys] @docs_group('Resource clients') @@ -489,8 +466,10 @@ def batch_add_requests( ) -> BatchAddResult: """Add requests to the request queue in batches. - Requests are split into batches based on size and processed in parallel. Any requests reported as unprocessed - by the API are retried with exponential backoff. + Requests are split into batches based on size and processed in parallel. Requests that the API reports as + unprocessed are retried with exponential backoff. If the first call for a batch fails, the error is raised. If + a retry call fails, the error is logged and the requests not added yet are returned as unprocessed. A response + that does not match the expected model is always raised. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests @@ -544,10 +523,7 @@ def batch_add_requests( # Process all batches in the queue sequentially. while not batch_queue.empty(): - batch_items = list(batch_queue.get()) - remaining_items = batch_items - processed_unique_keys = frozenset[str]() - batch_processed_requests = list[AddedRequest]() + remaining_items = list(batch_queue.get()) batch_unprocessed_requests = list[UnprocessedRequest]() for attempt in range(1 + max_unprocessed_requests_retries): @@ -562,6 +538,9 @@ def batch_add_requests( ) result = response_to_dict(response) batch_response = BatchAddResponse.model_validate(result) + except ValidationError: + # The API may have added the batch, so its requests can't be reported as unprocessed. + raise except Exception: if attempt == 0: raise @@ -570,24 +549,17 @@ def batch_add_requests( ) break - attempt_result = _extract_batch_attempt_result( - batch_items=batch_items, - batch_response=batch_response, - already_processed_keys=processed_unique_keys, - ) - batch_processed_requests.extend(attempt_result.processed_requests) - batch_unprocessed_requests = attempt_result.unprocessed_requests - remaining_items = attempt_result.remaining_items - processed_unique_keys = attempt_result.processed_unique_keys + processed_requests.extend(batch_response.data.processed_requests) + batch_unprocessed_requests = batch_response.data.unprocessed_requests if batch_unprocessed_requests: self._http_client.stats.add_rate_limit_error(attempt + 1) + remaining_items = _remaining_batch_items(remaining_items, batch_response) if not remaining_items: break if attempt < max_unprocessed_requests_retries: time.sleep(_compute_retry_delay_seconds(attempt, min_delay_between_unprocessed_requests_retries)) - processed_requests.extend(batch_processed_requests) unprocessed_requests.extend(batch_unprocessed_requests) return BatchAddResponse.model_construct( @@ -1073,10 +1045,7 @@ async def _batch_add_requests_worker( break try: - batch_items = list(request_batch) - remaining_items = batch_items - processed_unique_keys = frozenset[str]() - batch_processed_requests = list[AddedRequest]() + remaining_items = list(request_batch) batch_unprocessed_requests = list[UnprocessedRequest]() for attempt in range(1 + max_unprocessed_requests_retries): @@ -1091,6 +1060,9 @@ async def _batch_add_requests_worker( ) result = response_to_dict(response) batch_response = BatchAddResponse.model_validate(result) + except ValidationError: + # The API may have added the batch, so its requests can't be reported as unprocessed. + raise except Exception: if attempt == 0: raise @@ -1099,17 +1071,11 @@ async def _batch_add_requests_worker( ) break - attempt_result = _extract_batch_attempt_result( - batch_items=batch_items, - batch_response=batch_response, - already_processed_keys=processed_unique_keys, - ) - batch_processed_requests.extend(attempt_result.processed_requests) - batch_unprocessed_requests = attempt_result.unprocessed_requests - remaining_items = attempt_result.remaining_items - processed_unique_keys = attempt_result.processed_unique_keys + processed_requests.extend(batch_response.data.processed_requests) + batch_unprocessed_requests = batch_response.data.unprocessed_requests if batch_unprocessed_requests: self._http_client.stats.add_rate_limit_error(attempt + 1) + remaining_items = _remaining_batch_items(remaining_items, batch_response) if not remaining_items: break @@ -1118,7 +1084,6 @@ async def _batch_add_requests_worker( _compute_retry_delay_seconds(attempt, min_delay_between_unprocessed_requests_retries) ) - processed_requests.extend(batch_processed_requests) unprocessed_requests.extend(batch_unprocessed_requests) finally: @@ -1146,8 +1111,10 @@ async def batch_add_requests( ) -> BatchAddResult: """Add requests to the request queue in batches. - Requests are split into batches based on size and processed in parallel. Any requests reported as unprocessed - by the API are retried with exponential backoff. + Requests are split into batches based on size and processed in parallel. Requests that the API reports as + unprocessed are retried with exponential backoff. If the first call for a batch fails, the error is raised. If + a retry call fails, the error is logged and the requests not added yet are returned as unprocessed. A response + that does not match the expected model is always raised. https://docs.apify.com/api/v2#/reference/request-queues/batch-request-operations/add-requests diff --git a/tests/unit/test_client_request_queue.py b/tests/unit/test_client_request_queue.py index 9b9bcdfa..861ba813 100644 --- a/tests/unit/test_client_request_queue.py +++ b/tests/unit/test_client_request_queue.py @@ -3,6 +3,7 @@ import gzip import json import logging +import random import re from datetime import timedelta from typing import TYPE_CHECKING @@ -14,6 +15,7 @@ from apify_client import ApifyClient, ApifyClientAsync from apify_client._models import RequestToDelete +from apify_client._resource_clients.request_queue import _compute_retry_delay_seconds from apify_client.errors import ApifyApiError if TYPE_CHECKING: @@ -578,6 +580,86 @@ def test_batch_add_requests_retry_round_error_returns_partial_result_sync( assert any('Failed to retry unprocessed requests' in record.message for record in caplog.records) +_INVALID_BATCH_RESPONSE_CONTENT = '{"data": {"processedRequests": "invalid", "unprocessedRequests": []}}' + + +async def test_batch_add_requests_retry_round_invalid_response_raises_async(httpserver: HTTPServer) -> None: + """A retry round response that does not match the model raises `ValidationError` in the async client.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClientAsync(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + Response(_INVALID_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + ] + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + with pytest.raises(ValidationError): + await rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert handler.call_count == 2 + + +def test_batch_add_requests_retry_round_invalid_response_raises_sync(httpserver: HTTPServer) -> None: + """A retry round response that does not match the model raises `ValidationError` in the sync client.""" + server_url = httpserver.url_for('/').removesuffix('/') + client = ApifyClient(token='placeholder_token', api_url=server_url, api_public_url=server_url) + + handler = Mock( + side_effect=[ + Response(_PARTIALLY_ADDED_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + Response(_INVALID_BATCH_RESPONSE_CONTENT, status=200, content_type='application/json'), + ] + ) + httpserver.expect_request(re.compile(r'.*'), method='POST').respond_with_handler(handler) + requests: list[RequestWithoutIdDict] = [ + {'unique_key': 'http://example.com/1', 'url': 'http://example.com/1', 'method': 'GET'}, + {'unique_key': 'http://example.com/2', 'url': 'http://example.com/2', 'method': 'GET'}, + ] + rq_client = client.request_queue(request_queue_id='whatever') + + with pytest.raises(ValidationError): + rq_client.batch_add_requests( + requests=requests, + min_delay_between_unprocessed_requests_retries=timedelta(milliseconds=1), + ) + + assert handler.call_count == 2 + + +@pytest.mark.parametrize( + ('attempt', 'expected_seconds'), + [ + pytest.param(0, 0.75, id='first retry'), + pytest.param(1, 1.5, id='second retry'), + pytest.param(2, 3.0, id='third retry'), + ], +) +def test_compute_retry_delay_seconds_doubles_per_attempt( + monkeypatch: pytest.MonkeyPatch, + attempt: int, + expected_seconds: float, +) -> None: + """The unprocessed-requests retry delay is the jittered minimum delay doubled for each attempt.""" + uniform = Mock(return_value=1.5) + monkeypatch.setattr(random, 'uniform', uniform) + + delay = _compute_retry_delay_seconds(attempt, timedelta(milliseconds=500)) + + assert delay == pytest.approx(expected_seconds) + uniform.assert_called_once_with(1.0, 2.0) + + _REQUEST_REGISTRATION_RESPONSE_CONTENT = ( '{"data": {"requestId": "YiKoxjkaS9gjGTqhF", "wasAlreadyPresent": false, "wasAlreadyHandled": false}}' ) From 332eec21192619f32ba2459a1b151e64a128dae5 Mon Sep 17 00:00:00 2001 From: Vlada Dusek Date: Mon, 23 Nov 2026 12:59:10 +0100 Subject: [PATCH 5/5] docs: document retries of unprocessed requests in batch adds --- docs/02_concepts/05_retries.mdx | 28 ++++++++++++++++++- .../code/05_batch_add_retries_async.py | 19 +++++++++++++ .../code/05_batch_add_retries_sync.py | 19 +++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 docs/02_concepts/code/05_batch_add_retries_async.py create mode 100644 docs/02_concepts/code/05_batch_add_retries_sync.py diff --git a/docs/02_concepts/05_retries.mdx b/docs/02_concepts/05_retries.mdx index 3f210b89..9893578f 100644 --- a/docs/02_concepts/05_retries.mdx +++ b/docs/02_concepts/05_retries.mdx @@ -10,6 +10,8 @@ import CodeBlock from '@theme/CodeBlock'; import ApiLink from '@theme/ApiLink'; +import BatchAddRetriesAsyncExample from '!!raw-loader!./code/05_batch_add_retries_async.py'; +import BatchAddRetriesSyncExample from '!!raw-loader!./code/05_batch_add_retries_sync.py'; import RetriesAsyncExample from '!!raw-loader!./code/05_retries_async.py'; import RetriesSyncExample from '!!raw-loader!./code/05_retries_sync.py'; import StatsAsyncExample from '!!raw-loader!./code/05_stats_async.py'; @@ -48,13 +50,37 @@ Retries with exponential backoff help reduce the load on the server and increase +## Retry unprocessed requests in batch adds + +When the API rate-limits a batch of added requests, it responds with HTTP 200 and lists the requests it skipped in `unprocessedRequests`. The client's HTTP retries don't apply to such a response, because it's a success. For this case, `RequestQueueClient.batch_add_requests` retries the skipped requests itself. Each retry sends only the requests the API hasn't processed yet. + +You can customize this behavior using the following arguments of `batch_add_requests`: + +- `max_unprocessed_requests_retries`: Defines the maximum number of retries, 3 by default. Set it to `0` to disable retries. +- `min_delay_between_unprocessed_requests_retries`: Sets the minimum delay before the first retry as a `timedelta`, 500 milliseconds by default. Each later retry waits about twice as long as the one before it. + +Requests that are still unprocessed after the last retry are returned in `unprocessed_requests`. If a retry call fails, the client logs the error and returns the requests it didn't add as unprocessed. + + + + + {BatchAddRetriesAsyncExample} + + + + + {BatchAddRetriesSyncExample} + + + + ## Request statistics The client counts its calls, HTTP requests, and rate limit errors. To read the counts, use the `stats` property. It returns a `ClientStatistics` object with these fields: - `calls` is the number of calls made through the client, including requests to Actor servers. - `requests` is the number of HTTP requests sent, including retries and requests to Actor servers. -- `rate_limit_errors` maps each attempt to the number of rate limit (429) errors it got. Key `0` is the first attempt, key `1` is the first retry, and so on. The field is a `defaultdict`, so reading a missing key adds it. To read a count without changing the dict, use `.get()`. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. +- `rate_limit_errors` maps each attempt to the number of rate limit errors it got. It counts 429 responses and the `batch_add_requests` rounds that return unprocessed requests. Key `0` is the first attempt, key `1` is the first retry, and so on. The field is a `defaultdict`, so reading a missing key adds it. To read a count without changing the dict, use `.get()`. Only API calls count here. A 429 from an Actor server called through `ActorServerClient.request` is not counted. With a custom HTTP client, `stats` returns the statistics of that client. For details, see [HTTP clients](/api/client/python/docs/concepts/custom-http-clients). diff --git a/docs/02_concepts/code/05_batch_add_retries_async.py b/docs/02_concepts/code/05_batch_add_retries_async.py new file mode 100644 index 00000000..c7faf10a --- /dev/null +++ b/docs/02_concepts/code/05_batch_add_retries_async.py @@ -0,0 +1,19 @@ +from datetime import timedelta + +from apify_client import ApifyClientAsync + +TOKEN = 'MY-APIFY-TOKEN' + + +async def main() -> None: + apify_client = ApifyClientAsync(TOKEN) + rq_client = apify_client.request_queue('my-request-queue-id') + + result = await rq_client.batch_add_requests( + [{'unique_key': 'https://example.com', 'url': 'https://example.com'}], + max_unprocessed_requests_retries=5, + min_delay_between_unprocessed_requests_retries=timedelta(seconds=1), + ) + + for request in result.unprocessed_requests: + print(f'Not added: {request.url}') diff --git a/docs/02_concepts/code/05_batch_add_retries_sync.py b/docs/02_concepts/code/05_batch_add_retries_sync.py new file mode 100644 index 00000000..82ba892f --- /dev/null +++ b/docs/02_concepts/code/05_batch_add_retries_sync.py @@ -0,0 +1,19 @@ +from datetime import timedelta + +from apify_client import ApifyClient + +TOKEN = 'MY-APIFY-TOKEN' + + +def main() -> None: + apify_client = ApifyClient(TOKEN) + rq_client = apify_client.request_queue('my-request-queue-id') + + result = rq_client.batch_add_requests( + [{'unique_key': 'https://example.com', 'url': 'https://example.com'}], + max_unprocessed_requests_retries=5, + min_delay_between_unprocessed_requests_retries=timedelta(seconds=1), + ) + + for request in result.unprocessed_requests: + print(f'Not added: {request.url}')