Skip to content

feat: Retry unprocessed requests in RequestQueueClient.batch_add_requests - #1244

Open
cobanfurkanx wants to merge 2 commits into
apify:masterfrom
cobanfurkanx:feat/retry-unprocessed-batch-requests
Open

cobanfurkanx wants to merge 2 commits into
apify:masterfrom
cobanfurkanx:feat/retry-unprocessed-batch-requests

Conversation

@cobanfurkanx

Copy link
Copy Markdown
Contributor

Summary

  • Add DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS = 3 and DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES = timedelta(milliseconds=500) in src/apify_client/_consts.py.
  • Update sync RequestQueueClient.batch_add_requests() and async RequestQueueClientAsync.batch_add_requests() (along with _batch_add_requests_worker, _serialize_requests, _compute_retry_delay_seconds, and _record_batch_attempt_result) in src/apify_client/_resource_clients/request_queue.py to retry unprocessed_requests with exponential backoff while preserving non-breaking default behavior and recording rate-limit rounds via self._http_client.stats.add_rate_limit_error(attempt + 1).
  • Update test_batch_processed_partially_{async,sync} and add test_batch_add_requests_retries_unprocessed_requests_{async,sync} in tests/unit/test_client_request_queue.py.

Closes #1134

Verification

  • pytest tests/unit/test_client_request_queue.py tests/unit/test_statistics.py: 63 passed ([impit] and [httpx2])
  • poe lint (ruff format --check && ruff check): 249 files formatted, all checks passed
  • ty check src tests/unit/test_client_request_queue.py & ty check --python-platform linux: all checks passed
  • poe check-docstrings: async and sync method docstrings are in sync

@github-actions github-actions Bot added the t-tooling Issues with this label are in the ownership of the tooling team. label Nov 18, 2026
@vdusek vdusek changed the title feat: retry unprocessed requests in batch_add_requests feat: Retry unprocessed requests in RequestQueueClient.batch_add_requests Nov 20, 2026
batch_processed_requests = list[AddedRequest]()
batch_unprocessed_requests = list[UnprocessedRequest]()

for attempt in range(1 + max_unprocessed_requests_retries):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: If a retry round fails after the HTTP client's own retries (for example a 5xx), the method raises, and the requests that earlier rounds added are lost from the result. On master the same call returns the partial result, and the SDK RQ clients treat a raise as "nothing added". The JS client logs the error and returns the processed requests plus the remaining ones as unprocessed. Could you do the same for rounds with attempt > 0, in sync and async (:1039), and add a test?

✍️ Drafted by Claude Code

"""
if max_parallel != 1:
raise NotImplementedError('max_parallel is only supported in async client')
if max_unprocessed_requests_retries < 0:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Please also validate min_delay_between_unprocessed_requests_retries >= timedelta(0) here and in the async twin (:1114). Today a negative value makes the sync time.sleep raise after requests were already added, while the async asyncio.sleep silently skips the backoff.

✍️ Drafted by Claude Code

DEFAULT_MIN_DELAY_BETWEEN_RETRIES = timedelta(milliseconds=500)
"""Default minimum delay between retries."""

DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS = 3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: docs/04_upgrading/upgrading_to_v3.mdx:138 says max_unprocessed_requests_retries and min_delay_between_unprocessed_requests_retries "were no-ops; drop them". This PR brings them back with working behavior, so please update that line.

✍️ Drafted by Claude Code

unprocessed = batch_response.data.unprocessed_requests
if not unprocessed:
return [], unprocessed
statistics.add_rate_limit_error(attempt + 1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: ClientStatistics.rate_limit_errors in _statistics.py is documented as counting 429 errors. It now also counts batch-add rounds with unprocessed requests (the same as in JS), so please update the docstring.

✍️ Drafted by Claude Code

return handler


async def test_batch_add_requests_retries_unprocessed_requests_async(httpserver: HTTPServer) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Please add tests for max_unprocessed_requests_retries=0 (one call, no retry) and for the ValueError on a negative value.

✍️ Drafted by Claude Code

Comment thread tests/unit/test_client_request_queue.py Outdated
round_num = 0

def handler(request: Request) -> Response:
nonlocal round_num

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: CONTRIBUTING.md asks for Mock instead of hand-rolled counters. These nonlocal counters (also at :83 and :270) could be a Mock(side_effect=...) handler.

✍️ Drafted by Claude Code

return random.uniform(1.0, 2.0) * (2**attempt) * to_seconds(min_delay)


def _record_batch_attempt_result(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This helper changes processed_requests and processed_unique_keys and also returns a tuple. A pure function that returns all its results would be easier to read.

✍️ Drafted by Claude Code

@vdusek
vdusek requested a review from apify-factory November 20, 2026 08:56

@apify-factory apify-factory left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, nothing blocking.

🏭 Factory review — ℹ️ not auto-approved

This change was reviewed but cannot be auto-approved: a gate failed, so the review cannot end in an approval.

check result
Static gates ❌ 12/16 — author-allowed, same-repo, max-lines, no-risky-content
Review findings ✅ none
Reviewer escalation ❌ Adds new parameters to the public batch_add_requests signature and changes default runtime behavior (3 retries with sleeps of several seconds by default), which a maintainer should sign off on.
Juror 1 — claude-sonnet-5-5, adversarial ⏭️ skipped — a gate failed
Why it was not auto-approved

Failed gates:

  • author-allowed: cobanfurkanx: not a member of apify/product-engineering
  • same-repo: head repo is cobanfurkanx/apify-client-python
  • max-lines: 363 changed lines: over the limit 200 (+304/-59)
  • no-risky-content: src/apify_client/_resource_clients/request_queue.py: network call (network-call)

The comments above are the review itself; this section only explains the approval decision. Push a change and request @apify-factory again to re-run it, or ask a human to review.

Reviewed 867e5e0bd · Review details on the dashboard · workflow run

@cobanfurkanx

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review @vdusek! Addressed all feedback in 04d68fc:

  • Retry round error handling (attempt > 0): Both sync and async batch_add_requests now catch exceptions on retry rounds (attempt > 0), log the error via logger.exception, and return requests already processed in earlier rounds along with the remaining unprocessed requests (still re-raising on attempt == 0). Added sync/async unit tests covering HTTP 500 on a retry round.
  • Delay validation: Validated min_delay_between_unprocessed_requests_retries >= timedelta(0) alongside max_unprocessed_requests_retries >= 0 in both sync and async clients via _validate_batch_retry_params.
  • Upgrading guide: Updated docs/04_upgrading/upgrading_to_v3.mdx to remove the stale no-op bullet and document the active retry parameters.
  • Statistics docstring: Updated ClientStatistics.rate_limit_errors docstring in src/apify_client/_statistics.py to note both HTTP 429 responses and batch_add_requests rounds with unprocessed requests.
  • Pure attempt helper: Replaced _record_batch_attempt_result with a pure _extract_batch_attempt_result returning a _BatchAttemptResult NamedTuple.
  • Tests: Replaced nonlocal counters with Mock(side_effect=...) and added sync/async tests for max_unprocessed_requests_retries=0 and negative retry/delay ValueError validation.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

t-tooling Issues with this label are in the ownership of the tooling team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

batch_add_requests() doesn't retry unprocessed requests

3 participants