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}')
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..4a0c0f26 100644
--- a/src/apify_client/_resource_clients/request_queue.py
+++ b/src/apify_client/_resource_clients/request_queue.py
@@ -3,13 +3,22 @@
import asyncio
import json
import math
+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 more_itertools import constrained_batches
+from pydantic import ValidationError
+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._logging import logger
from apify_client._models import (
AddedRequest,
AddRequestResponse,
@@ -45,7 +54,6 @@
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Iterator
- from datetime import timedelta
from apify_client._literals import GeneralAccess
from apify_client._typeddicts import (
@@ -70,26 +78,59 @@
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 _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 _remaining_batch_items(
+ remaining_items: list[tuple[str, bytes]],
+ batch_response: BatchAddResponse,
+) -> 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')
@@ -417,11 +458,18 @@ 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. 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
@@ -431,6 +479,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 +489,12 @@ def batch_add_requests(
"""
if max_parallel != 1:
raise NotImplementedError('max_parallel is only supported in async client')
+ _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 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 +508,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 +523,44 @@ def batch_add_requests(
# Process all batches in the queue sequentially.
while not batch_queue.empty():
- request_batch = batch_queue.get()
+ remaining_items = list(batch_queue.get())
+ batch_unprocessed_requests = list[UnprocessedRequest]()
+
+ for attempt in range(1 + max_unprocessed_requests_retries):
+ 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 ValidationError:
+ # The API may have added the batch, so its requests can't be reported as unprocessed.
+ raise
+ except Exception:
+ if attempt == 0:
+ raise
+ logger.exception(
+ 'Failed to retry unprocessed requests in request queue batch; returning partial result.'
+ )
+ break
- # 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,
- )
+ 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
- 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))
+
+ unprocessed_requests.extend(batch_unprocessed_requests)
return BatchAddResponse.model_construct(
data=BatchAddResult.model_construct(
@@ -945,13 +1022,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 +1045,46 @@ 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,
- )
-
- 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)
+ remaining_items = list(request_batch)
+ batch_unprocessed_requests = list[UnprocessedRequest]()
+
+ for attempt in range(1 + max_unprocessed_requests_retries):
+ 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 ValidationError:
+ # The API may have added the batch, so its requests can't be reported as unprocessed.
+ raise
+ except Exception:
+ if attempt == 0:
+ raise
+ logger.exception(
+ 'Failed to retry unprocessed requests in request queue batch; returning partial result.'
+ )
+ break
+
+ 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:
+ await asyncio.sleep(
+ _compute_retry_delay_seconds(attempt, min_delay_between_unprocessed_requests_retries)
+ )
+
+ unprocessed_requests.extend(batch_unprocessed_requests)
finally:
# Mark the batch as done whether it succeeded or failed.
@@ -998,11 +1103,18 @@ 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. 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
@@ -1012,11 +1124,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.
"""
+ _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)
@@ -1031,12 +1151,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 +1167,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/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 728fa459..861ba813 100644
--- a/tests/unit/test_client_request_queue.py
+++ b/tests/unit/test_client_request_queue.py
@@ -2,8 +2,12 @@
import gzip
import json
+import logging
+import random
import re
+from datetime import timedelta
from typing import TYPE_CHECKING
+from unittest.mock import Mock
import pytest
from pydantic import ValidationError
@@ -11,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:
@@ -76,19 +81,33 @@ 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
+ 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] = [
{'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 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 test_batch_not_processed_raises_exception_sync(httpserver: HTTPServer) -> None:
@@ -247,19 +266,398 @@ 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
+ 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] = [
{'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 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]]) -> Mock:
+ """Return a mock handler that processes one request per round across 3 rounds."""
+ handler = Mock()
+
+ 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)
+ 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',
+ )
+
+ handler.side_effect = respond
+ 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}
+
+
+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)
+
+
+_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 = (