From 647571a3b8b505301fbc79518cfff755922903f5 Mon Sep 17 00:00:00 2001 From: kasparasizi1 <132673909+kasparasizi1@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:15:12 +0200 Subject: [PATCH] feat!: max concurrency replaces rate-limit tiers (0.84.0, SCR-736) RateLimitError keeps its name and now carries max_concurrency, concurrent_requests and retry_after (seconds); limit/remaining/reset_at/tier are gone. A concurrency 429 (refused before it runs, never billed) is retried automatically with a capped backoff. X-RateLimit pagination throttling is removed: the API no longer sends those headers. README gets a Concurrency section. Linear: SCR-736 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 ++ README.md | 70 ++++++-- pyproject.toml | 2 +- src/scrapebadger/__init__.py | 2 +- src/scrapebadger/_internal/client.py | 45 +++-- src/scrapebadger/_internal/exceptions.py | 46 +++-- src/scrapebadger/_internal/pagination.py | 107 +----------- src/scrapebadger/agent/client.py | 3 +- tests/test_agent.py | 2 +- tests/test_exceptions.py | 44 ++--- tests/test_pagination.py | 206 ++++++----------------- tests/test_retry_warnings.py | 110 +++++++++++- tests/test_twitter_tweets_aliases.py | 7 +- uv.lock | 2 +- 14 files changed, 318 insertions(+), 342 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e74896..585710a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## [0.84.0] - 2026-11-29 + +ScrapeBadger replaced rate-limit tiers and per-minute limits with one number per account: **max concurrency**, how many requests the account may run at the same time across all of its API keys. There is no per-minute limit any more. (SCR-736) + +### Breaking +- **`RateLimitError` describes the concurrency limit.** The class name and import are unchanged, and every 429 still raises it. New attributes: `max_concurrency` and `concurrent_requests` (ints from the 429 body, `None` when the body has none; `max_concurrency` is 1 for an agent trial key's `trial_concurrency` 429). `retry_after` is now always a number of seconds from the `Retry-After` header and defaults to 1 (was 60) when the header is missing or malformed. Removed: `limit`, `remaining`, `reset_at` and `tier`; code that reads them gets `AttributeError`. The keyword arguments of the constructor changed the same way. +- **Pagination no longer throttles.** The `*_all` iterators read `X-RateLimit-*` headers and slowed down near the limit; the API no longer sends those headers, so the throttling and its "Rate limit: ... throttling pagination" warning are gone. Pages are still fetched one at a time, with the same cursor, `max_pages` and `max_items` handling. +- **`account.get_account_info()`** (raw dict) no longer has `tier` or `rate_limit_per_minute`. It has `max_concurrency` (the account's limit) and `concurrent_requests` (its requests running right now, not counting this one). + +### Changed +- The API's 429 for the limit is `{"error": "concurrency_limit_exceeded", "detail": ..., "max_concurrency": N, "concurrent_requests": N}` with `Retry-After: 1`. Successful responses carry `X-Concurrency-Limit` and `X-Concurrency-Remaining` instead of `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` and `X-Api-Tier`. +- **A concurrency 429 is retried automatically.** `concurrency_limit_exceeded` and `trial_concurrency` are refused before the call runs or bills, so the SDK waits for a slot (`Retry-After`, then 2, 4, 8, at most 10 s) and retries, up to `max_retries`. Other 429s (e.g. the zero-credit throttle) still raise straight away; `retry_on_status` is unchanged. +- README: "Rate Limit Aware Pagination" is replaced by a "Concurrency" section (checking the limit, staying under it with a semaphore, handling the 429). + ## [0.83.1] - 2026-11-26 ### Changed diff --git a/README.md b/README.md index 0ce95f2..9e4534c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The official Python SDK for [ScrapeBadger](https://scrapebadger.com) - async web - **Async-first** - Built with `asyncio` for high-performance concurrent scraping - **Type-safe** - Full type hints and Pydantic models for all responses -- **Automatic pagination** - Iterator methods with smart rate limit handling +- **Automatic pagination** - Iterator methods that follow cursors for you - **Resilient retries** - Exponential backoff on transient errors - **Async requests and webhooks** - Submit any slow call, poll or `wait` for it, or take a signed webhook; idempotency keys make re-submits safe - **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams @@ -243,8 +243,8 @@ async with ScrapeBadger(api_key="your-key") as client: except AuthenticationError: print("Invalid API key") except RateLimitError as e: - print(f"Rate limited. Retry after {e.retry_after} seconds") - print(f"Limit: {e.limit}, Remaining: {e.remaining}") + print(f"Too many concurrent requests. Retry after {e.retry_after} seconds") + print(f"Running: {e.concurrent_requests} of {e.max_concurrency}") except InsufficientCreditsError: print("Out of credits! Purchase more at scrapebadger.com") except NotFoundError: @@ -311,20 +311,66 @@ import logging logging.basicConfig(level=logging.WARNING) ``` -### Rate Limit Aware Pagination +### Concurrency -When using `*_all` pagination methods, the SDK reads `X-RateLimit-Remaining` and -`X-RateLimit-Reset` headers from each response. When remaining requests drop below -20% of your tier's limit, pagination automatically slows down to spread requests -across the remaining window — preventing 429 errors. A warning is logged when -throttling activates: +Every ScrapeBadger account has a **max concurrency**: how many requests it can +have running at the same time, across all of its API keys. There is no +per-minute limit; send as many requests as you like, as long as no more than +`max_concurrency` are in flight at once. Your plan sets the number, see +[pricing](https://scrapebadger.com/pricing). +Check it with the account endpoint (free): + +```python +info = await client.account.get_account_info() +print(info["max_concurrency"]) # requests the account may run at once +print(info["concurrent_requests"]) # running right now, not counting this call ``` -⚠ Rate limit: 25/300 remaining (resets in 42s), throttling pagination to ~0.6 req/s + +To stay under it, cap your own in-flight calls, for example with a semaphore: + +```python +import asyncio + +from scrapebadger import ScrapeBadger + +async with ScrapeBadger(api_key="your-key") as client: + info = await client.account.get_account_info() + slots = asyncio.Semaphore(info["max_concurrency"]) + + async def fetch(username: str): + async with slots: + return await client.twitter.users.get_by_username(username) + + users = await asyncio.gather(*(fetch(u) for u in ["elonmusk", "nasa", "github"])) ``` -This works transparently with all tier levels (Free: 60/min, Basic: 300/min, -Pro: 1000/min, Enterprise: 5000/min). +The limit counts every request of the account, whichever key, process or +machine sends it, so split the number between workers that share an account. +The `*_all` iterators fetch one page at a time and hold one slot. An async +request (`client.requests.submit`) holds its slot until the call finishes; +polling it does not take one. + +A request over the limit is refused before it runs, so it is not charged. The +API answers `429` with `Retry-After: 1`: + +```json +{ + "error": "concurrency_limit_exceeded", + "detail": "Too many concurrent requests: ...", + "max_concurrency": 5, + "concurrent_requests": 5 +} +``` + +The SDK retries this 429 by itself: it waits `Retry-After`, then 2, 4, 8 and at +most 10 seconds between attempts, up to `max_retries` (10 by default). Only when +the retries run out does it raise `RateLimitError`, with `max_concurrency`, +`concurrent_requests` and `retry_after` (seconds). Capping your own in-flight +calls as above avoids the wait altogether. + +Successful responses carry `X-Concurrency-Limit` (your max concurrency) and +`X-Concurrency-Remaining` (free slots once this request started). ## Development diff --git a/pyproject.toml b/pyproject.toml index 9b2d312..fbfa0af 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "scrapebadger" -version = "0.83.1" +version = "0.84.0" description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more" readme = "README.md" license = { text = "MIT" } diff --git a/src/scrapebadger/__init__.py b/src/scrapebadger/__init__.py index 6e9069f..1c31bdc 100644 --- a/src/scrapebadger/__init__.py +++ b/src/scrapebadger/__init__.py @@ -1356,7 +1356,7 @@ async def main(): ZestimateHistoryPoint as ZillowZestimateHistoryPoint, ) -__version__ = "0.83.1" +__version__ = "0.84.0" __all__ = [ # TikTok core models diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index dadf57a..5de6623 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -55,8 +55,11 @@ T = TypeVar("T") +# 429 bodies that mean "every concurrency slot is in use": retried by default. +_CONCURRENCY_ERRORS = frozenset({"concurrency_limit_exceeded", "trial_concurrency"}) + # User agent for SDK requests -SDK_VERSION = "0.83.1" +SDK_VERSION = "0.84.0" USER_AGENT = f"scrapebadger-python/{SDK_VERSION}" @@ -79,6 +82,13 @@ def _retry_after_seconds(response: httpx.Response, default: int) -> int: return default +def _int_or_none(value: Any) -> int | None: + """An integer field of an error body, or None when it is missing or not an integer.""" + if isinstance(value, bool) or not isinstance(value, int): + return None + return value + + class BaseClient: """Base HTTP client with retry logic and error handling. @@ -209,15 +219,16 @@ def _handle_error_response( raise ValidationError(message, status_code, data) if status_code == 429: + max_concurrency = _int_or_none(data.get("max_concurrency")) + if max_concurrency is None and data.get("error") == "trial_concurrency": + max_concurrency = 1 # agent trial keys run one call at a time raise RateLimitError( message, status_code, data, - limit=data.get("limit"), - remaining=data.get("remaining"), - reset_at=data.get("reset_at"), - retry_after=_retry_after_seconds(response, default=60), - tier=data.get("tier"), + max_concurrency=max_concurrency, + concurrent_requests=_int_or_none(data.get("concurrent_requests")), + retry_after=_retry_after_seconds(response, default=1), ) if status_code >= 500: @@ -316,17 +327,31 @@ async def _send( replayed = ( response.headers.get("Idempotent-Replayed", "").strip().lower() == "true" ) + # A concurrency 429 is refused before anything runs or bills, + # so it is always safe to retry once a slot frees up. + concurrency_full = ( + response.status_code == 429 and data.get("error") in _CONCURRENCY_ERRORS + ) # Don't retry client errors (except specific status codes) if ( not retry_status or replayed - or response.status_code not in self._config.retry_on_status + or ( + response.status_code not in self._config.retry_on_status + and not concurrency_full + ) ): self._handle_error_response(response, data) # Retry on configured status codes if attempt < self._config.max_retries: - delay = max(2**attempt, _retry_after_seconds(response, default=0)) + if concurrency_full: + # Slots free as requests finish: poll briskly, not 2**n. + delay = max( + _retry_after_seconds(response, default=1), min(2**attempt, 10) + ) + else: + delay = max(2**attempt, _retry_after_seconds(response, default=0)) logger.warning( "⚠ %s %s — retrying in %ss (attempt %d/%d)", response.status_code, @@ -495,8 +520,8 @@ async def get_with_headers( Returns: A (data, headers) tuple. ``data`` is the parsed JSON response; - ``headers`` is a plain dict of response header name → value strings - (e.g. ``{"X-RateLimit-Remaining": "250", ...}``). + ``headers`` is a plain dict of response header name → value strings, + with lowercase names (e.g. ``{"x-concurrency-remaining": "4", ...}``). """ return await self._request_with_retry("GET", path, params=params) diff --git a/src/scrapebadger/_internal/exceptions.py b/src/scrapebadger/_internal/exceptions.py index 0063289..b5a7d49 100644 --- a/src/scrapebadger/_internal/exceptions.py +++ b/src/scrapebadger/_internal/exceptions.py @@ -8,7 +8,7 @@ try: tweets = await client.twitter.tweets.get_by_id("123456") except RateLimitError as e: - print(f"Rate limited. Retry after: {e.retry_after}s") + print(f"Too many concurrent requests. Retry after: {e.retry_after}s") except AuthenticationError: print("Invalid API key") except ScrapeBadgerError as e: @@ -128,43 +128,53 @@ def __init__( class RateLimitError(ScrapeBadgerError): - """Raised when rate limit is exceeded. + """Raised for a 429: usually the account is already at its max concurrency. + + Every account has a max concurrency: how many requests it may have in + flight at the same time, across all of its API keys. A request over that + number is refused with ``429`` (``error: "concurrency_limit_exceeded"``) + before it runs, so it is not charged; retry it as soon as one of your + running requests finishes. Agent trial keys run one call at a time and + answer ``429`` (``error: "trial_concurrency"``) the same way. Other 429s + (e.g. ``error: "rate_limited"`` from an endpoint's own cap) raise this + too; ``response_data["error"]`` tells them apart. + + The SDK does not retry a 429 by itself. Keep the number of requests you + send at once under ``max_concurrency`` (see the README's "Concurrency" + section), or wait ``retry_after`` seconds and try again. Attributes: - limit: Maximum requests allowed per minute. - remaining: Requests remaining in current window. - reset_at: Unix timestamp when the rate limit resets. - retry_after: Seconds until the rate limit resets. - tier: The user's current rate limit tier. + max_concurrency: How many requests the account may run at once, or + None when the response did not say (1 for an agent trial key). + concurrent_requests: How many of its requests were running when this + one was refused, or None when the response did not say. + retry_after: Seconds to wait before retrying, from the ``Retry-After`` + header (1 when the header is missing or malformed). Example: ```python try: tweets = await client.twitter.tweets.search("python") except RateLimitError as e: - print(f"Rate limited. Wait {e.retry_after} seconds.") + print(f"{e.concurrent_requests}/{e.max_concurrency} requests running") await asyncio.sleep(e.retry_after) ``` """ def __init__( self, - message: str = "Rate limit exceeded", + message: str = "Too many concurrent requests", status_code: int = 429, response_data: dict[str, Any] | None = None, *, - limit: int | None = None, - remaining: int | None = None, - reset_at: int | None = None, - retry_after: int | None = None, - tier: str | None = None, + max_concurrency: int | None = None, + concurrent_requests: int | None = None, + retry_after: float = 1, ) -> None: super().__init__(message, status_code, response_data) - self.limit = limit - self.remaining = remaining - self.reset_at = reset_at + self.max_concurrency = max_concurrency + self.concurrent_requests = concurrent_requests self.retry_after = retry_after - self.tier = tier class InsufficientCreditsError(ScrapeBadgerError): diff --git a/src/scrapebadger/_internal/pagination.py b/src/scrapebadger/_internal/pagination.py index 08b5cf0..fca5eba 100644 --- a/src/scrapebadger/_internal/pagination.py +++ b/src/scrapebadger/_internal/pagination.py @@ -2,9 +2,6 @@ from __future__ import annotations -import asyncio -import logging -import time from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Generic, TypeVar @@ -13,13 +10,8 @@ from scrapebadger._internal.client import BaseClient -logger = logging.getLogger("scrapebadger") - T = TypeVar("T") -# Throttle pagination when remaining requests drop below this fraction of the limit. -_RATE_LIMIT_THRESHOLD = 0.20 - @dataclass class PaginatedResponse(Generic[T]): @@ -70,37 +62,6 @@ def __bool__(self) -> bool: return bool(self.data) -def _compute_throttle_delay( - remaining: int, - limit: int, - reset_ts: int, -) -> float | None: - """Return a sleep delay in seconds if rate-limit throttling is needed. - - Throttling kicks in when ``remaining < limit * _RATE_LIMIT_THRESHOLD``. - The delay spreads remaining requests evenly across the time left in the - current window, giving a minimum of 0.05 s. - - Args: - remaining: Requests remaining in the current window. - limit: Total requests allowed per window. - reset_ts: Unix timestamp when the window resets. - - Returns: - Seconds to sleep, or ``None`` if no throttling is needed. - """ - if remaining >= limit * _RATE_LIMIT_THRESHOLD: - return None - - seconds_left = max(reset_ts - time.time(), 1.0) - # Spread remaining requests over the window — guard against zero division. - if remaining <= 0: - return seconds_left - - delay = seconds_left / remaining - return max(delay, 0.05) - - async def paginate( client: BaseClient, path: str, @@ -112,10 +73,8 @@ async def paginate( ) -> AsyncIterator[T]: """Async generator for automatic pagination through results. - Reads ``X-RateLimit-Remaining``, ``X-RateLimit-Limit``, and - ``X-RateLimit-Reset`` response headers on every page. When remaining - requests drop below 20 % of the limit a warning is logged and requests - are spread out over the remaining window time via ``asyncio.sleep``. + Pages are fetched one after another, so a pagination loop holds one of the + account's concurrent request slots at a time. Args: client: The base HTTP client. @@ -162,8 +121,7 @@ async def paginate( if cursor: request_params["cursor"] = cursor - # Fetch page — use get_with_headers so we can inspect rate-limit state. - response, headers = await client.get_with_headers(path, params=request_params) + response = await client.get(path, params=request_params) # Parse and yield items data = response.get("data", []) @@ -189,62 +147,3 @@ async def paginate( if not next_cursor or next_cursor == cursor: break cursor = next_cursor - - # Rate-limit-aware throttling between pages. - _maybe_throttle_between_pages(headers) - delay = _extract_throttle_delay(headers) - if delay is not None: - await asyncio.sleep(delay) - - -def _extract_throttle_delay(headers: dict[str, str]) -> float | None: - """Parse rate-limit headers and return a throttle delay if needed. - - Returns ``None`` when headers are absent or throttling is not required. - """ - raw_remaining = headers.get("x-ratelimit-remaining") or headers.get("X-RateLimit-Remaining") - raw_limit = headers.get("x-ratelimit-limit") or headers.get("X-RateLimit-Limit") - raw_reset = headers.get("x-ratelimit-reset") or headers.get("X-RateLimit-Reset") - - if raw_remaining is None or raw_limit is None or raw_reset is None: - return None - - try: - remaining = int(raw_remaining) - limit = int(raw_limit) - reset_ts = int(raw_reset) - except ValueError: - return None - - return _compute_throttle_delay(remaining, limit, reset_ts) - - -def _maybe_throttle_between_pages(headers: dict[str, str]) -> None: - """Log a warning if rate-limit throttling will be applied.""" - raw_remaining = headers.get("x-ratelimit-remaining") or headers.get("X-RateLimit-Remaining") - raw_limit = headers.get("x-ratelimit-limit") or headers.get("X-RateLimit-Limit") - raw_reset = headers.get("x-ratelimit-reset") or headers.get("X-RateLimit-Reset") - - if raw_remaining is None or raw_limit is None or raw_reset is None: - return - - try: - remaining = int(raw_remaining) - limit = int(raw_limit) - reset_ts = int(raw_reset) - except ValueError: - return - - delay = _compute_throttle_delay(remaining, limit, reset_ts) - if delay is None: - return - - resets_in = max(int(reset_ts - time.time()), 0) - rate = round(1.0 / delay, 1) if delay > 0 else 0 - logger.warning( - "Rate limit: %d/%d remaining (resets in %ds), throttling pagination to ~%s req/s", - remaining, - limit, - resets_in, - rate, - ) diff --git a/src/scrapebadger/agent/client.py b/src/scrapebadger/agent/client.py index d23f501..f5e1d3c 100644 --- a/src/scrapebadger/agent/client.py +++ b/src/scrapebadger/agent/client.py @@ -119,7 +119,8 @@ async def feedback( ) -> FeedbackReceipt: """Send feedback (an API or field you needed and couldn't find) or a bug report. - Free, never billed; rate limited per key (429 when over the limit). + Free, never billed. Counts toward your account's max concurrency, and each + key may send only so many reports per hour (429 when over either). Args: summary: One-line summary, 3-200 characters. diff --git a/tests/test_agent.py b/tests/test_agent.py index f28d94e..cab21a1 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -254,7 +254,7 @@ async def test_batch_submits_items_and_parses_each_outcome(self, sb: ScrapeBadge "accepted": False, "status": 429, "request_id": "r-1", - "error": {"detail": "Rate limit exceeded"}, + "error": {"detail": "Too many concurrent requests"}, }, ], }, diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 4b09f18..d3872ba 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -65,33 +65,33 @@ def test_inheritance(self) -> None: class TestRateLimitError: - """Tests for RateLimitError.""" + """Tests for RateLimitError (the account's max concurrency).""" def test_default_values(self) -> None: """Test default error values.""" error = RateLimitError() - assert "Rate limit exceeded" in str(error) + assert "Too many concurrent requests" in str(error) assert error.status_code == 429 - assert error.limit is None - assert error.remaining is None - assert error.reset_at is None - assert error.retry_after is None - assert error.tier is None - - def test_with_rate_limit_info(self) -> None: - """Test error with rate limit info.""" - error = RateLimitError( - limit=300, - remaining=0, - reset_at=1703123456, - retry_after=45, - tier="basic", - ) - assert error.limit == 300 - assert error.remaining == 0 - assert error.reset_at == 1703123456 - assert error.retry_after == 45 - assert error.tier == "basic" + assert error.max_concurrency is None + assert error.concurrent_requests is None + assert error.retry_after == 1 + + def test_with_concurrency_info(self) -> None: + """Test error with concurrency info.""" + error = RateLimitError(max_concurrency=5, concurrent_requests=5, retry_after=2) + assert error.max_concurrency == 5 + assert error.concurrent_requests == 5 + assert error.retry_after == 2 + + def test_old_rate_limit_attributes_are_gone(self) -> None: + """The per-minute fields were removed with the tiers (SCR-736).""" + error = RateLimitError() + for name in ("limit", "remaining", "reset_at", "tier"): + assert not hasattr(error, name) + + def test_inheritance(self) -> None: + """Existing ``except ScrapeBadgerError`` handlers still catch it.""" + assert isinstance(RateLimitError(), ScrapeBadgerError) class TestInsufficientCreditsError: diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 23ca015..d32df9a 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -1,9 +1,7 @@ -"""Tests for pagination with rate-limit-aware throttling.""" +"""Tests for cursor pagination.""" from __future__ import annotations -import logging -import time from typing import Any from unittest.mock import AsyncMock, patch @@ -24,24 +22,11 @@ def base_client(config: ClientConfig) -> BaseClient: return BaseClient(config) -def _make_page( - items: list[dict[str, Any]], - next_cursor: str | None = None, - *, - remaining: int = 300, - limit: int = 300, - reset_at: int | None = None, -) -> tuple[dict[str, Any], dict[str, str]]: - reset_ts = reset_at if reset_at is not None else int(time.time()) + 60 +def _make_page(items: list[dict[str, Any]], next_cursor: str | None = None) -> dict[str, Any]: data: dict[str, Any] = {"data": items} if next_cursor: data["next_cursor"] = next_cursor - headers = { - "X-RateLimit-Remaining": str(remaining), - "X-RateLimit-Limit": str(limit), - "X-RateLimit-Reset": str(reset_ts), - } - return data, headers + return data class TestPaginateBasic: @@ -49,49 +34,49 @@ class TestPaginateBasic: async def test_single_page_no_cursor(self, base_client: BaseClient) -> None: """Yields all items from a single page when there is no next_cursor.""" - page, headers = _make_page([{"id": "1"}, {"id": "2"}]) - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + page = _make_page([{"id": "1"}, {"id": "2"}]) + base_client.get = AsyncMock(return_value=page) # type: ignore[method-assign] results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] assert results == [{"id": "1"}, {"id": "2"}] - assert base_client.get_with_headers.call_count == 1 + assert base_client.get.call_count == 1 async def test_multiple_pages_follow_cursor(self, base_client: BaseClient) -> None: """Follows next_cursor across multiple pages.""" - page1, h1 = _make_page([{"id": "1"}], next_cursor="cur1") - page2, h2 = _make_page([{"id": "2"}], next_cursor="cur2") - page3, h3 = _make_page([{"id": "3"}]) + page1 = _make_page([{"id": "1"}], next_cursor="cur1") + page2 = _make_page([{"id": "2"}], next_cursor="cur2") + page3 = _make_page([{"id": "3"}]) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2), (page3, h3)] + base_client.get = AsyncMock( # type: ignore[method-assign] + side_effect=[page1, page2, page3] ) results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] assert results == [{"id": "1"}, {"id": "2"}, {"id": "3"}] # second call must include cursor=cur1 - _, kwargs = base_client.get_with_headers.call_args_list[1] + _, kwargs = base_client.get.call_args_list[1] assert kwargs["params"]["cursor"] == "cur1" async def test_max_pages_limits_fetching(self, base_client: BaseClient) -> None: """Stops after max_pages regardless of next_cursor.""" - page, headers = _make_page([{"id": "1"}], next_cursor="cur") - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + page = _make_page([{"id": "1"}], next_cursor="cur") + base_client.get = AsyncMock(return_value=page) # type: ignore[method-assign] results = [ item async for item in paginate(base_client, "/v1/test", {}, lambda x: x, max_pages=2) ] assert len(results) == 2 - assert base_client.get_with_headers.call_count == 2 + assert base_client.get.call_count == 2 async def test_max_items_limits_yielding(self, base_client: BaseClient) -> None: """Stops yielding once max_items is reached.""" - page1, h1 = _make_page([{"id": "1"}, {"id": "2"}, {"id": "3"}], next_cursor="c") - page2, h2 = _make_page([{"id": "4"}]) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] + page1 = _make_page([{"id": "1"}, {"id": "2"}, {"id": "3"}], next_cursor="c") + page2 = _make_page([{"id": "4"}]) + base_client.get = AsyncMock( # type: ignore[method-assign] + side_effect=[page1, page2] ) results = [ @@ -103,8 +88,8 @@ async def test_max_items_limits_yielding(self, base_client: BaseClient) -> None: async def test_empty_data_field_stops_iteration(self, base_client: BaseClient) -> None: """Treats empty data list as last page.""" - page, headers = _make_page([], next_cursor="ghost") - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + page = _make_page([], next_cursor="ghost") + base_client.get = AsyncMock(return_value=page) # type: ignore[method-assign] results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] @@ -117,21 +102,21 @@ async def test_echoed_cursor_stops_iteration(self, base_client: BaseClient) -> N causing the 'repeats first page' loop. Only two pages are mocked, so a third call would raise StopIteration and fail this test. """ - page1, h1 = _make_page([{"id": "1"}], next_cursor="c") - page2, h2 = _make_page([{"id": "2"}], next_cursor="c") # echoes "c" - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] + page1 = _make_page([{"id": "1"}], next_cursor="c") + page2 = _make_page([{"id": "2"}], next_cursor="c") # echoes "c" + base_client.get = AsyncMock( # type: ignore[method-assign] + side_effect=[page1, page2] ) results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] assert results == [{"id": "1"}, {"id": "2"}] - assert base_client.get_with_headers.call_count == 2 + assert base_client.get.call_count == 2 async def test_item_parser_is_applied(self, base_client: BaseClient) -> None: """Applies item_parser to each raw dict.""" - page, headers = _make_page([{"value": 1}, {"value": 2}]) - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + page = _make_page([{"value": 1}, {"value": 2}]) + base_client.get = AsyncMock(return_value=page) # type: ignore[method-assign] results = [ item async for item in paginate(base_client, "/v1/test", {}, lambda x: x["value"] * 10) @@ -140,127 +125,30 @@ async def test_item_parser_is_applied(self, base_client: BaseClient) -> None: assert results == [10, 20] -class TestPaginateRateLimitThrottling: - """Tests for rate-limit-aware throttling behaviour.""" +class TestPaginateNoThrottling: + """Pagination no longer slows down: the API has no per-minute limit (SCR-736).""" - async def test_no_sleep_when_remaining_above_threshold(self, base_client: BaseClient) -> None: - """Does NOT sleep when remaining is above 20% of limit.""" - # 100/300 = 33% > 20% — should not throttle - page, headers = _make_page([{"id": "1"}], next_cursor=None, remaining=100, limit=300) - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + async def test_never_sleeps_between_pages(self, base_client: BaseClient) -> None: + """Fetches the next page right away.""" + page1 = _make_page([{"id": "1"}], next_cursor="c1") + page2 = _make_page([{"id": "2"}], next_cursor="c2") + page3 = _make_page([{"id": "3"}]) + base_client.get = AsyncMock(side_effect=[page1, page2, page3]) # type: ignore[method-assign] - with patch("scrapebadger._internal.pagination.asyncio.sleep") as mock_sleep: + with patch("asyncio.sleep") as mock_sleep: results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - assert results == [{"id": "1"}] + assert results == [{"id": "1"}, {"id": "2"}, {"id": "3"}] mock_sleep.assert_not_called() - async def test_sleep_when_remaining_below_20_percent(self, base_client: BaseClient) -> None: - """Sleeps between pages when remaining drops below 20% of limit.""" - reset_ts = int(time.time()) + 60 - - # Page 1 triggers throttle (remaining=10, limit=300 → 3.3% < 20%) - page1, h1 = _make_page( - [{"id": "1"}], next_cursor="c", remaining=10, limit=300, reset_at=reset_ts - ) - page2, h2 = _make_page([{"id": "2"}], remaining=5, limit=300, reset_at=reset_ts) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] - ) - - with patch("scrapebadger._internal.pagination.asyncio.sleep") as mock_sleep: - results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - assert results == [{"id": "1"}, {"id": "2"}] - # sleep must be called at least once - assert mock_sleep.call_count >= 1 - # delay must be positive - delay_arg = mock_sleep.call_args_list[0][0][0] - assert delay_arg > 0 - - async def test_warning_logged_when_throttling( - self, base_client: BaseClient, caplog: pytest.LogCaptureFixture - ) -> None: - """Emits a warning log through the 'scrapebadger' logger when throttling.""" - reset_ts = int(time.time()) + 60 - page1, h1 = _make_page( - [{"id": "1"}], next_cursor="c", remaining=5, limit=300, reset_at=reset_ts - ) - page2, h2 = _make_page([{"id": "2"}], remaining=5, limit=300, reset_at=reset_ts) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] - ) - - with ( - patch("scrapebadger._internal.pagination.asyncio.sleep"), - caplog.at_level(logging.WARNING, logger="scrapebadger"), - ): - results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - assert results == [{"id": "1"}, {"id": "2"}] - assert any("throttling" in record.message.lower() for record in caplog.records) - assert any(record.name == "scrapebadger" for record in caplog.records) - - async def test_warning_message_contains_rate_limit_info( - self, base_client: BaseClient, caplog: pytest.LogCaptureFixture - ) -> None: - """Warning message includes remaining/limit and resets-in info.""" - reset_ts = int(time.time()) + 45 - page1, h1 = _make_page( - [{"id": "1"}], next_cursor="c", remaining=12, limit=300, reset_at=reset_ts - ) - page2, h2 = _make_page([{"id": "2"}], remaining=12, limit=300, reset_at=reset_ts) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] - ) + def test_throttle_helpers_are_gone(self) -> None: + """The X-RateLimit header parsing was removed with the headers.""" + from scrapebadger._internal import pagination - with ( - patch("scrapebadger._internal.pagination.asyncio.sleep"), - caplog.at_level(logging.WARNING, logger="scrapebadger"), + for name in ( + "_RATE_LIMIT_THRESHOLD", + "_compute_throttle_delay", + "_extract_throttle_delay", + "_maybe_throttle_between_pages", ): - [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - warning_msgs = [r.message for r in caplog.records if r.levelno == logging.WARNING] - assert warning_msgs, "Expected at least one WARNING log" - msg = warning_msgs[0] - assert "12/300" in msg # remaining/limit - - async def test_missing_rate_limit_headers_no_throttle(self, base_client: BaseClient) -> None: - """Gracefully handles responses with no rate-limit headers (no sleep).""" - page: dict[str, Any] = {"data": [{"id": "1"}]} - headers: dict[str, str] = {} # no rate limit headers - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] - - with patch("scrapebadger._internal.pagination.asyncio.sleep") as mock_sleep: - results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - assert results == [{"id": "1"}] - mock_sleep.assert_not_called() - - async def test_exactly_at_threshold_no_throttle(self, base_client: BaseClient) -> None: - """Does not throttle when remaining equals exactly 20% of limit.""" - # 60/300 = 20% — boundary, should NOT throttle (strictly below 20%) - page, headers = _make_page([{"id": "1"}], remaining=60, limit=300) - base_client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] - - with patch("scrapebadger._internal.pagination.asyncio.sleep") as mock_sleep: - results = [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - assert results == [{"id": "1"}] - mock_sleep.assert_not_called() - - async def test_one_below_threshold_throttles(self, base_client: BaseClient) -> None: - """Throttles when remaining is one below 20% of limit.""" - reset_ts = int(time.time()) + 60 - page1, h1 = _make_page( - [{"id": "1"}], next_cursor="c", remaining=59, limit=300, reset_at=reset_ts - ) - page2, h2 = _make_page([{"id": "2"}], remaining=59, limit=300, reset_at=reset_ts) - base_client.get_with_headers = AsyncMock( # type: ignore[method-assign] - side_effect=[(page1, h1), (page2, h2)] - ) - - with patch("scrapebadger._internal.pagination.asyncio.sleep") as mock_sleep: - [item async for item in paginate(base_client, "/v1/test", {}, lambda x: x)] - - assert mock_sleep.call_count >= 1 + assert not hasattr(pagination, name) diff --git a/tests/test_retry_warnings.py b/tests/test_retry_warnings.py index ec13939..931f952 100644 --- a/tests/test_retry_warnings.py +++ b/tests/test_retry_warnings.py @@ -166,7 +166,7 @@ async def test_retry_limit_and_backoff_are_preserved(self) -> None: @pytest.mark.parametrize( ("value", "expected"), - [("5", 5), ("0", 0), (formatdate(1_800_000_005, usegmt=True), 5), ("invalid", 60)], + [("5", 5), ("0", 0), (formatdate(1_800_000_005, usegmt=True), 5), ("invalid", 1)], ) async def test_429_keeps_rate_limit_error_without_automatic_retry( self, config_one_retry: ClientConfig, value: str, expected: int @@ -187,6 +187,104 @@ async def test_429_keeps_rate_limit_error_without_automatic_retry( assert request.await_count == 1 sleep.assert_not_awaited() + async def test_429_concurrency_limit_body_is_parsed( + self, config_one_retry: ClientConfig + ) -> None: + body = { + "error": "concurrency_limit_exceeded", + "detail": "Too many concurrent requests: this account allows 5 at a time and 5 " + "are already running.", + "max_concurrency": 5, + "concurrent_requests": 5, + } + response = httpx.Response( + 429, + json=body, + headers={ + "Retry-After": "1", + "X-Concurrency-Limit": "5", + "X-Concurrency-Remaining": "0", + }, + ) + async with BaseClient(config_one_retry) as client: + with ( + patch.object(client, "_execute_request", return_value=response) as request, + patch("scrapebadger._internal.client.asyncio.sleep") as sleep, + pytest.raises(RateLimitError) as error, + ): + await client.get("/v1/test") + assert error.value.status_code == 429 + assert error.value.max_concurrency == 5 + assert error.value.concurrent_requests == 5 + assert error.value.retry_after == 1 + assert error.value.message.startswith("Too many concurrent requests: this account") + assert error.value.response_data["error"] == "concurrency_limit_exceeded" + # Refused before it ran, so it is retried (config_one_retry: one retry). + assert request.await_count == 2 + assert sleep.await_args_list == [call(1)] + + async def test_429_concurrency_limit_recovers_when_a_slot_frees( + self, config_default: ClientConfig + ) -> None: + full = httpx.Response( + 429, + json={"error": "concurrency_limit_exceeded", "max_concurrency": 1}, + headers={"Retry-After": "1"}, + ) + ok = httpx.Response(200, json={"ok": True}) + async with BaseClient(config_default) as client: + with ( + patch.object(client, "_execute_request", side_effect=[full] * 5 + [ok]), + patch("scrapebadger._internal.client.asyncio.sleep") as sleep, + ): + assert await client.get("/v1/test") == {"ok": True} + # Backoff grows but is capped at 10 s: a slot frees when any request ends. + assert sleep.await_args_list == [call(1), call(2), call(4), call(8), call(10)] + + async def test_429_trial_concurrency_is_a_rate_limit_error( + self, config_one_retry: ClientConfig + ) -> None: + response = httpx.Response( + 429, + json={ + "error": "trial_concurrency", + "detail": "Trial keys run one call at a time. Wait for the previous call.", + }, + headers={"Retry-After": "2"}, + ) + async with BaseClient(config_one_retry) as client: + with ( + patch.object(client, "_execute_request", return_value=response), + pytest.raises(RateLimitError) as error, + ): + await client.get("/v1/test") + assert error.value.max_concurrency == 1 + assert error.value.concurrent_requests is None + assert error.value.retry_after == 2 + + @pytest.mark.parametrize( + "body", + [ + {}, + {"error": "rate_limited", "detail": "Too many reports from this key"}, + {"error": "concurrency_limit_exceeded", "max_concurrency": "5"}, + {"error": "concurrency_limit_exceeded", "max_concurrency": True}, + ], + ) + async def test_429_without_usable_concurrency_fields( + self, config_one_retry: ClientConfig, body: dict[str, object] + ) -> None: + response = httpx.Response(429, json=body) + async with BaseClient(config_one_retry) as client: + with ( + patch.object(client, "_execute_request", return_value=response), + pytest.raises(RateLimitError) as error, + ): + await client.get("/v1/test") + assert error.value.max_concurrency is None + assert error.value.concurrent_requests is None + assert error.value.retry_after == 1 + class TestRetryWarningLogging: """Tests that warning logs are emitted on 5xx retries and network errors.""" @@ -456,9 +554,8 @@ async def test_get_with_headers_returns_data_and_headers( """get_with_headers returns a (data, headers) tuple.""" resp_headers = httpx.Headers( { - "X-RateLimit-Limit": "300", - "X-RateLimit-Remaining": "250", - "X-RateLimit-Reset": "1700000060", + "X-Concurrency-Limit": "5", + "X-Concurrency-Remaining": "4", "Content-Type": "application/json", } ) @@ -477,9 +574,8 @@ async def test_get_with_headers_returns_data_and_headers( assert data == {"data": []} # httpx.Headers normalises names to lowercase when converted to a plain dict - assert headers["x-ratelimit-limit"] == "300" - assert headers["x-ratelimit-remaining"] == "250" - assert headers["x-ratelimit-reset"] == "1700000060" + assert headers["x-concurrency-limit"] == "5" + assert headers["x-concurrency-remaining"] == "4" async def test_get_with_headers_warning_on_5xx_retry( self, diff --git a/tests/test_twitter_tweets_aliases.py b/tests/test_twitter_tweets_aliases.py index a5cc7ae..aaa8d01 100644 --- a/tests/test_twitter_tweets_aliases.py +++ b/tests/test_twitter_tweets_aliases.py @@ -36,12 +36,9 @@ async def test_advanced_search_all_delegates_to_search_all( tweets_client: TweetsClient, ) -> None: page: dict[str, Any] = {"data": [{"id": "1"}, {"id": "2"}]} - headers: dict[str, str] = {} - tweets_client._client.get_with_headers = AsyncMock(return_value=(page, headers)) # type: ignore[method-assign] + tweets_client._client.get = AsyncMock(return_value=page) # type: ignore[method-assign] ids = [t.id async for t in tweets_client.advanced_search_all("python")] assert ids == ["1", "2"] - assert tweets_client._client.get_with_headers.call_args[0][0] == ( - "/v1/twitter/tweets/advanced_search" - ) + assert tweets_client._client.get.call_args[0][0] == ("/v1/twitter/tweets/advanced_search") diff --git a/uv.lock b/uv.lock index c53bd93..485e93d 100644 --- a/uv.lock +++ b/uv.lock @@ -930,7 +930,7 @@ wheels = [ [[package]] name = "scrapebadger" -version = "0.83.1" +version = "0.84.0" source = { editable = "." } dependencies = [ { name = "httpx" },