diff --git a/CHANGELOG.md b/CHANGELOG.md index a5bb7c4..eb36787 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 2.5.0 + +### Added +- **`concurrency="auto"`** finds how many requests at once the servers handle well, like TCP congestion control: it starts at 8 attempts on the wire, doubles while responses stay healthy, backs off to three quarters as soon as the servers push back (429/502/503/504, timeouts, dropped connections on more than 5 % of recent attempts) and to nine tenths when responses take twice as long as the host's normal, then stops just below the level that caused pushback and probes it again only after a few healthy windows. It grows only when the whole limit is in use, and a request waiting to retry does not hold a place. `max_concurrency` (default 500) caps it. Against a local server that rejects anything over 12 at a time, it settled at 12 with 1 % extra attempts, where `concurrency=100` needed 46 % more; against one that slows down under load, it kept 9 requests in flight instead of 100. +- The progress line shows `active 12/16` (in flight / allowed) with `concurrency="auto"`; every change is logged at `DEBUG` and a summary at `INFO`. `ProgressInfo.concurrency` holds the current limit. +- **Open file limit:** before sending, the concurrency is checked against the process's open file limit (`ulimit -n`; one file per connection, plus one pool per SOCKS proxy). A limit that is too low is raised as far as the system allows; if that is not enough, the concurrency is lowered to fit, with a warning naming the `ulimit -n` value to use. This replaces "Too many open files" failures, for example with `concurrency=1000` in a shell limited to 256. Not applicable on Windows. +- Command line: `-c auto`, `--max-concurrency`. + +### Fixed +- On Python 3.9 and 3.10, the built-in `TimeoutError` (raised for example by SOCKS proxies) was not treated as retryable, because it differs from `asyncio.TimeoutError` before Python 3.11. + ## 2.4.3 ### Fixed diff --git a/README.md b/README.md index 742d418..4764578 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ reqstorm does all of that for you, with one call. |---|---| | One result per request | Failures are recorded, never raised; every attempt is kept | | Rate limits | Per host, in any unit (`"100/min"`), or `"auto"` from the server's 429s and headers | -| Concurrency | Overall and per host | +| Concurrency | Overall and per host, or `"auto"` to find it from the responses | | Retries | Exponential backoff with a cap and jitter, `Retry-After`; plus end-of-run rounds | | Reports | Failures by reason, p50/p95/p99 response times, per-host figures | | Pagination | Next links, `Link` headers, cursors and page numbers | @@ -264,6 +264,10 @@ results = reqstorm.fetch_all_sync( The limit applies to each host (`host:port`) separately and counts retries too, so requests to different APIs never slow each other down. Requests to one host are spaced evenly. +**Don't know how much the server can take?** `concurrency="auto"` finds out, like TCP congestion control: it starts at 8 requests at once, doubles while responses stay healthy, and backs off on 429/5xx, timeouts or slowdowns. Against a server that rejects anything over 12 at a time it settles at 12 with 1 % extra attempts, where a fixed 100 needs 46 % more. + +Concurrency does not depend on CPU cores: requests mostly wait for the network, and one core keeps hundreds in flight. If the concurrency needs more open connections than `ulimit -n` allows, the limit is raised automatically, or the concurrency is lowered with a warning. + **Don't know the limit?** `rate_limit="auto"` learns it from the server. A `429 Too Many Requests` pauses the host for `Retry-After` and slows it down; `X-RateLimit-Remaining` and `X-RateLimit-Reset` spread the remaining requests over the window; the rate recovers when the server stops pushing back. 429 responses are retried without using up `retries`. **Plan before you send.** `estimate` predicts the duration and names the bottleneck, without sending anything: diff --git a/docs/guide/cli.md b/docs/guide/cli.md index de99322..f54d151 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -50,7 +50,8 @@ $ reqstorm urls.txt -o results.jsonl --report | `--bearer TOKEN` | Send `Authorization: Bearer TOKEN`; the `REQSTORM_TOKEN` environment variable works too, and keeps the token out of your shell history | | `--proxy URL` | Send through a proxy (`http://`, `socks5://`, `socks5h://`, `socks4://`, `socks4a://`); repeat the option to rotate through several | | `--rate` | Per-host rate limit: `5`, `10/s`, `100/min`, `1000/h`, or `auto` | -| `-c`, `--per-host` | Concurrency in total and per host | +| `-c N`, `--per-host N` | Concurrency in total and per host | +| `-c auto`, `--max-concurrency N` | Find the concurrency from the responses, up to N (default 500); see [Rate limits and concurrency](limits.md#finding-the-concurrency-automatically-concurrencyauto) | | `--timeout`, `--retries`, `--backoff` | Per attempt timeout, retries and the first wait between them | | `--max-backoff`, `--no-jitter` | Longest wait between retries (default 30 s); wait exactly instead of a random part of it | | `--retry-rounds`, `--retry-round-delay` | Send failed requests again at the end (needs `-o`) | diff --git a/docs/guide/limits.md b/docs/guide/limits.md index 71337ad..bba9931 100644 --- a/docs/guide/limits.md +++ b/docs/guide/limits.md @@ -43,6 +43,46 @@ Pauses are capped at 5 minutes. `concurrency` and `concurrency_per_host` still a `concurrency` caps how many requests are in flight at once (default 100). `concurrency_per_host` caps it per host (default: no per-host cap). Requests are spread over a fixed number of workers that read your URLs lazily, so a generator of millions of URLs is fine. +Concurrency is not tied to the number of CPU cores. reqstorm runs every request on one thread with asyncio, and a request spends almost all its time waiting for the network, so one core easily keeps hundreds of requests in flight. What limits a batch is the server, and on your side the number of open connections, both covered below. + +### Finding the concurrency automatically: `concurrency="auto"` + +When you don't know how much a server can take, let reqstorm find out: + +```python +results = reqstorm.fetch_all_sync(urls, concurrency="auto", retries=3) +``` + +It works like TCP congestion control: + +- It starts with 8 attempts on the wire and **doubles** that after each healthy window of time (about three times the response time, at least a quarter of a second). +- It **backs off** to three quarters as soon as the servers push back: 429, 502, 503 or 504 responses, timeouts or dropped connections on more than 5 % of recent attempts. It **eases off** to nine tenths when responses take more than twice as long as that host's normal. +- After the first backoff it grows by about 10 % per window, stops just below the level where the servers pushed back, and tries that level again only after a few healthy windows. +- It grows only when the whole limit is in use, and a request waiting to retry does not hold a place, so the limit is what the servers actually see. + +`max_concurrency` (default 500) is the highest it may go. With `progress=True` the line shows the current limit as `active 12/16` (in flight / allowed), and the log reports every change at `DEBUG` and a summary at `INFO`. + +How it compares with the default `concurrency=100`, measured against a local server that rejects with a 503 anything over its capacity (600 requests, `retries=3`): + +| Server capacity | `concurrency=100` | `concurrency="auto"` | +|---|---|---| +| 3 at a time | 494 of 600 succeed, 105 % extra attempts | 600 succeed, 2 % extra; settles at 3 | +| 12 at a time | 600 succeed, 46 % extra | 600 succeed, 1 % extra, faster; settles at 12 | +| 40 at a time | 600 succeed, 20 % extra | 600 succeed, 6 % extra; settles at 39 | +| 100 at a time | 600 succeed, 0.2 s | 600 succeed, 1.0 s (it starts at 8 and needs time to grow) | +| never rejects, slows down under load | 100 requests at once | at most 9 at once | + +So `"auto"` is gentle with servers that are already busy and close to ideal for unknown capacity. For a short batch against a server that easily handles your fixed number, a fixed number is faster, because `"auto"` spends the first second or so finding out. It treats the batch as a whole; to limit one busy host among several, combine it with `concurrency_per_host`. + +### Open file limit + +Every connection is an open file, and the operating system limits how many a process may have (`ulimit -n`; some macOS shells start at 256). Asking for more connections than that used to fail with "Too many open files". Now, before sending anything, reqstorm compares the concurrency with the limit: + +- If the limit is too low, it is raised as far as the system allows, and an `INFO` message says so. +- If it cannot be raised far enough, the concurrency is lowered to fit, with a `WARNING` that names the `ulimit -n` value to use for the full concurrency. + +64 file descriptors are kept free for log and output files, and each SOCKS proxy (which has its own connection pool) counts separately. Windows has no such limit, so nothing changes there. + ## Estimating a batch `reqstorm.estimate` tells you how long a batch should take and which setting is the bottleneck, without sending anything: diff --git a/docs/guide/observability.md b/docs/guide/observability.md index 3f87ebb..5a3688a 100644 --- a/docs/guide/observability.md +++ b/docs/guide/observability.md @@ -16,7 +16,7 @@ reqstorm: 3500/7000 (50%) ok 3493 failed 7 active 12 retries 41 1.7 req/s |---|---| | `3500/7000 (50%)` | Requests with a final result, of all requests | | `ok`, `failed` | How those ended | -| `active` | Requests being sent, waiting for a response, or waiting to retry right now | +| `active` | Requests being sent, waiting for a response, or waiting to retry right now. With `concurrency="auto"`, shown as `active 12/16`: in flight / currently allowed | | `retries` | Retries so far, of all requests | | `1.7 req/s` | Finished requests per second over the last minute | | `round 1/2` | With `retry_rounds`: the round being sent | diff --git a/docs/index.md b/docs/index.md index 852b2c8..4bdea30 100644 --- a/docs/index.md +++ b/docs/index.md @@ -47,7 +47,7 @@ print(results.summary()) --- - `"10/s"`, `"100/min"`, `"1000/h"` per host, or `"auto"` to follow the server's 429s and rate-limit headers. Know how long a batch takes before you start it. + `"10/s"`, `"100/min"`, `"1000/h"` per host, or `"auto"` to follow the server's 429s and rate-limit headers. `concurrency="auto"` finds how many requests at once a server handles well. Know how long a batch takes before you start it. [:octicons-arrow-right-24: Rate limits](guide/limits.md) diff --git a/reqstorm/__init__.py b/reqstorm/__init__.py index a56caf7..73a272f 100644 --- a/reqstorm/__init__.py +++ b/reqstorm/__init__.py @@ -35,7 +35,7 @@ async def main(): from ._sync import fetch_all_sync, fetch_to_db_sync, fetch_to_file_sync, stream_sync from ._template import from_template, read_csv, read_sql -__version__ = "2.4.3" +__version__ = "2.5.0" # A library must not print log messages the application did not ask for: without this, # Python's last-resort handler would print reqstorm's warnings and errors to stderr in diff --git a/reqstorm/_cli.py b/reqstorm/_cli.py index e6b5369..6e617dd 100644 --- a/reqstorm/_cli.py +++ b/reqstorm/_cli.py @@ -83,8 +83,10 @@ def _parser() -> argparse.ArgumentParser: add = pace.add_argument add("--rate", metavar="LIMIT", help="per-host rate limit: 5, 10/s, 100/min, 1000/h, or auto (default: none)") - add("-c", "--concurrency", type=int, default=100, metavar="N", - help="requests in flight at once (default: 100)") + add("-c", "--concurrency", type=_concurrency, default=100, metavar="N", + help="requests in flight at once, or auto to find the number from the responses (default: 100)") + add("--max-concurrency", type=int, default=500, metavar="N", + help="with -c auto: the highest number it may reach (default: 500)") add("--per-host", type=int, default=0, metavar="N", help="requests in flight per host (default: no limit)") add("--timeout", type=float, default=30.0, metavar="SECONDS", @@ -157,6 +159,15 @@ def _parser() -> argparse.ArgumentParser: # fmt: on +def _concurrency(text: str) -> Union[int, str]: + if text == "auto": + return text + try: + return int(text) + except ValueError: + raise argparse.ArgumentTypeError(f"invalid concurrency {text!r}; use a number or auto") from None + + def _paginator(text: Optional[str], max_pages: int) -> Optional[Paginator]: if not text: return None @@ -291,7 +302,9 @@ def _batch(args: argparse.Namespace, cache: Optional[Cache]) -> int: if total is None: raise ValueError("--estimate needs an input file, not standard input") print(estimate(total, rate_limit=None if rate == "auto" else rate, hosts=_hosts(args), - concurrency=args.concurrency, concurrency_per_host=args.per_host, + # with -c auto, the best case: the highest concurrency it may reach + concurrency=args.max_concurrency if args.concurrency == "auto" else args.concurrency, + concurrency_per_host=args.per_host, latency=args.latency)) # fmt: skip return 0 @@ -308,6 +321,7 @@ def _batch(args: argparse.Namespace, cache: Optional[Cache]) -> int: json=json.loads(args.json) if args.json else None, data=args.data, concurrency=args.concurrency, + max_concurrency=args.max_concurrency, concurrency_per_host=args.per_host, timeout=args.timeout, retries=args.retries, diff --git a/reqstorm/_client.py b/reqstorm/_client.py index d0d3486..ed58e3d 100644 --- a/reqstorm/_client.py +++ b/reqstorm/_client.py @@ -7,6 +7,7 @@ import collections import itertools import json as jsonlib +import logging import random import ssl as ssllib import time @@ -33,8 +34,10 @@ from multidict import CIMultiDict, CIMultiDictProxy from ._adaptive import AdaptiveRateLimiter +from ._concurrency import AutoConcurrency from ._limits import HostRateLimiter, RateLimit, host_key from ._observe import LogLevel, LogTarget, ProgressTarget, Run, describe +from ._resources import fit_concurrency from ._socks import SocksSessions, check_available, is_proxy_error, is_socks __all__ = ["Attempt", "HTTPStatusError", "Request", "Result", "Results", "fetch_all", "stream"] @@ -251,6 +254,7 @@ class _Options: max_backoff: float = 30.0 jitter: bool = True run: Optional[Run] = None + gate: Optional[AutoConcurrency] = None def backoff_delay(self, retry: int) -> float: """Seconds to wait before retry number ``retry`` (1 for the first).""" @@ -284,7 +288,10 @@ def _resolve(request: Union[str, Request], options: _Options) -> Request: def _is_retryable_error(error: BaseException) -> bool: if isinstance(error, (aiohttp.InvalidURL, ValueError)): return False - return isinstance(error, (aiohttp.ClientError, asyncio.TimeoutError)) or is_proxy_error(error) + # asyncio.TimeoutError and the built-in TimeoutError are different classes before Python 3.11 + return isinstance(error, (aiohttp.ClientError, asyncio.TimeoutError, TimeoutError)) or is_proxy_error( + error + ) def _should_retry(result: Result, retry_statuses: frozenset) -> bool: @@ -303,6 +310,23 @@ def _retry_after(headers: Mapping[str, str]) -> Optional[float]: return None +async def _ungate( + options: _Options, + url: str, + status: Optional[int], + error: Optional[BaseException], + took: float, + epoch: int, +) -> None: + """Give back an attempt's place in the concurrency="auto" limit and learn from it.""" + gate = options.gate + assert gate is not None + await gate.release() + change = gate.attempt(url, status, error, took, epoch) + if change is not None and options.run is not None: + options.run.log(logging.DEBUG, "%s", change, event="concurrency", concurrency=gate.limit) + + MAX_THROTTLED_RETRIES = 10 # with rate_limit="auto": 429 retries, not counted in `retries` @@ -334,6 +358,8 @@ async def _send(session: aiohttp.ClientSession, request: Request, index: int, op delay = 0.0 attempt_started = time.monotonic() used_proxy: Optional[str] = None + gated = False + epoch = 0 try: headers: Dict[str, str] = dict(request.headers or {}) generation = None @@ -345,6 +371,9 @@ async def _send(session: aiohttp.ClientSession, request: Request, index: int, op headers.setdefault(name, value) if limiter is not None: await limiter.wait(request.url) + if options.gate is not None: + epoch = await options.gate.acquire() + gated = True attempt_started = time.monotonic() proxy = used_proxy = request.proxy or options.next_proxy() sender = session @@ -366,6 +395,9 @@ async def _send(session: aiohttp.ClientSession, request: Request, index: int, op body = await response.read() status, response_headers, final_url = response.status, response.headers, str(response.url) took = time.monotonic() - attempt_started + if gated: + gated = False + await _ungate(options, request.url, status, None, took, epoch) result.history.append(Attempt(attempt, status, None, took)) if run is not None: run.attempted(request, status, None, took, attempt, used_proxy) @@ -400,11 +432,16 @@ async def _send(session: aiohttp.ClientSession, request: Request, index: int, op if run is not None: run.retrying(request, f"HTTP {status}", attempt, options.retries + 1, delay, used_proxy) except asyncio.CancelledError: + if gated and options.gate is not None: + await options.gate.release() raise except Exception as error: # one failing request must not stop the others result.error = error result.status = None took = time.monotonic() - attempt_started + if gated: + gated = False + await _ungate(options, request.url, None, error, took, epoch) result.history.append(Attempt(attempt, None, error, took)) if run is not None: run.attempted(request, None, error, took, attempt, used_proxy) @@ -431,7 +468,8 @@ async def stream( params: Optional[Mapping[str, Any]] = None, json: Any = None, data: Any = None, - concurrency: int = 100, + concurrency: Union[int, str] = 100, + max_concurrency: int = 500, timeout: Optional[float] = 30.0, retries: int = 0, backoff: float = 0.5, @@ -464,8 +502,11 @@ async def stream( owns_run = _run is None run = _run or Run(total=_total(urls, total, paginate), progress=progress, log_level=log_level, log_file=log_file, log_format=log_format) # fmt: skip - if concurrency < 1: - raise ValueError("concurrency must be at least 1") + auto = concurrency == "auto" + if not auto and (not isinstance(concurrency, int) or isinstance(concurrency, bool) or concurrency < 1): + raise ValueError('concurrency must be a number of at least 1, or "auto"') + if max_concurrency < 1: + raise ValueError("max_concurrency must be at least 1") if retries < 0: raise ValueError("retries must not be negative") if concurrency_per_host < 0: @@ -479,6 +520,15 @@ async def stream( else: limiter = None proxies = [proxy] if isinstance(proxy, str) else list(proxy or []) + # Each SOCKS proxy has its own connection pool, which may hold as many connections + pools = 1 + len({item for item in proxies if is_socks(item)}) + + def file_limit(level: int, message: str) -> None: + run.log(level, "%s", message, event="file_limit") + + workers = fit_concurrency(max_concurrency if auto else int(concurrency), pools, file_limit) + controller = AutoConcurrency(maximum=workers) if auto else None + run.controller = controller if any(is_socks(item) for item in proxies): check_available() # fail before sending anything, not on every request if session is not None: @@ -500,22 +550,24 @@ async def stream( auth=auth, cache=cache, proxies=itertools.cycle(proxies) if proxies else None, - socks=SocksSessions(concurrency, concurrency_per_host) if session is None else None, + socks=SocksSessions(workers, concurrency_per_host) if session is None else None, run=run, + gate=controller, ) if limiter is not None: run.limiters.append(limiter) if owns_run: - run.start(describe(concurrency=concurrency, rate_limit=rate_limit, retries=retries)) + shown = f"auto (max {workers})" if auto else workers + run.start(describe(concurrency=shown, rate_limit=rate_limit, retries=retries)) owns_session = session is None if session is None: session = aiohttp.ClientSession( - connector=aiohttp.TCPConnector(limit=concurrency, limit_per_host=concurrency_per_host) + connector=aiohttp.TCPConnector(limit=workers, limit_per_host=concurrency_per_host) ) pending = enumerate(urls) - queue: asyncio.Queue = asyncio.Queue(maxsize=concurrency * 2) + queue: asyncio.Queue = asyncio.Queue(maxsize=workers * 2) finished = object() # Pages found while paginating are sent before new input, so a long input does not # leave pages waiting. Workers stop when the input is used up and nothing is in flight. @@ -574,7 +626,7 @@ async def worker() -> None: async def supervise() -> None: try: - await asyncio.gather(*(worker() for _ in range(concurrency))) + await asyncio.gather(*(worker() for _ in range(workers))) except BaseException as error: # surfaces a failure while reading `urls` await queue.put(error) else: @@ -666,7 +718,8 @@ async def fetch_all( params: Optional[Mapping[str, Any]] = ..., json: Any = ..., data: Any = ..., - concurrency: int = ..., + concurrency: Union[int, str] = ..., + max_concurrency: int = ..., timeout: Optional[float] = ..., retries: int = ..., backoff: float = ..., @@ -713,7 +766,8 @@ async def fetch_all( params: Optional[Mapping[str, Any]] = None, json: Any = None, data: Any = None, - concurrency: int = 100, + concurrency: Union[int, str] = 100, + max_concurrency: int = 500, timeout: Optional[float] = 30.0, retries: int = 0, backoff: float = 0.5, @@ -748,7 +802,15 @@ async def fetch_all( params: Query parameters for every request, unless a ``Request`` sets its own. json: JSON body for every request, unless a ``Request`` sets its own. data: Form or raw body for every request, unless a ``Request`` sets its own. - concurrency: Maximum number of requests in flight at once. + concurrency: Maximum number of requests in flight at once, or ``"auto"`` to find + the best number from the responses: it starts at 8, doubles while responses + stay healthy, and backs off when servers answer 429/5xx, time out, drop + connections or slow down to more than twice their normal response time. + When the number is higher than the open file limit allows (one file per + connection), the limit is raised if the system permits, else the number is + lowered with a warning. + max_concurrency: With ``concurrency="auto"``, the highest number it may reach + (default 500). timeout: Seconds allowed per attempt, including reading the body. ``None`` disables it. retries: How many times to retry a request right away after a connection error, a timeout or a status in ``retry_statuses``. Invalid URLs are not retried. @@ -820,6 +882,7 @@ async def fetch_all( json=json, data=data, concurrency=concurrency, + max_concurrency=max_concurrency, timeout=timeout, retries=retries, backoff=backoff, @@ -837,7 +900,8 @@ async def fetch_all( session=session, _run=run, ) - run.start(describe(concurrency=concurrency, rate_limit=rate_limit, retries=retries, + shown = f"auto (max {max_concurrency})" if concurrency == "auto" else concurrency + run.start(describe(concurrency=shown, rate_limit=rate_limit, retries=retries, retry_rounds=retry_rounds)) # fmt: skip try: async for result in _execute(urls, retry_rounds, retry_round_delay, stream_options): diff --git a/reqstorm/_concurrency.py b/reqstorm/_concurrency.py new file mode 100644 index 0000000..532e7ce --- /dev/null +++ b/reqstorm/_concurrency.py @@ -0,0 +1,188 @@ +"""concurrency="auto": find how many requests at once the servers handle well.""" + +from __future__ import annotations + +import asyncio +import statistics +import time +from typing import Callable, Dict, List, Optional + +from ._limits import host_key + +__all__ = ["AutoConcurrency"] + +_OVERLOAD_STATUSES = frozenset({429, 502, 503, 504}) +_SLOW = 2.0 # a response this many times slower than the host's normal counts as slow +_OVERLOADED = 0.05 # share of attempts with an overload signal that triggers a backoff +_MIN_WINDOW = 0.25 # seconds +_HOLD_WINDOWS = 8 # healthy windows just below the ceiling before probing it again + + +class AutoConcurrency: + """Limits the attempts on the wire at once, and adjusts the limit from the responses. + + The limit counts attempts being sent or awaiting a response. A request waiting to retry + does not hold a place, so the limit is what the servers actually see. + + It works like TCP congestion control: + + - **Back off** to three quarters when the servers push back: more than 5 % of recent + attempts met a 429, 502, 503 or 504 response, a timeout or a dropped connection. This + does not wait for the end of a window: as soon as a quarter of the limit has been + rejected, the limit drops, so a server that rejects instantly is not flooded. Each + backoff starts a new epoch; attempts sent before it are not counted afterwards, so one + burst is not punished twice. + - **Ease off** to nine tenths when the median response of a window takes more than twice + as long as that host's normal (its fastest typical time). + - **Grow** once per window (at least 0.25 s and three times the recent response time), + and only when the window used the whole limit: double it until the first backoff + ("slow start"), then add about 10 %. A limit that is never reached says nothing about + whether a higher one would work. + - **Remember the ceiling**, the limit at which the servers last pushed back. Growth stops + just below it and probes it again only after a few healthy windows (as TCP CUBIC does). + A probe without pushback lifts the ceiling. + """ + + def __init__(self, maximum: int, start: int = 8, clock: Callable[[], float] = time.monotonic) -> None: + if maximum < 1: + raise ValueError("max_concurrency must be at least 1") + self.maximum = maximum + self.limit = min(start, maximum) + self.slow_start = True + self.lowest = self.highest = self.limit + self.changes = 0 + self.active = 0 + self.epoch = 0 + self.ceiling: Optional[int] = None + self._holding = 0 + self._clock = clock + self._condition: Optional[asyncio.Condition] = None + self._normal: Dict[str, float] = {} + self._latencies: List[float] = [] + self._window_started = clock() + self._attempts = self._overloads = self._peak = 0 + self._ratios: List[float] = [] + + # -- the gate ---------------------------------------------------------------------- + + async def acquire(self) -> int: + """Wait for a place; returns the epoch to pass back to ``attempt``.""" + if self._condition is None: + self._condition = asyncio.Condition() + async with self._condition: + while self.active >= self.limit: + await self._condition.wait() + self.active += 1 + self._peak = max(self._peak, self.active) + return self.epoch + + async def release(self) -> None: + assert self._condition is not None + async with self._condition: + self.active -= 1 + self._condition.notify_all() + + # -- learning ---------------------------------------------------------------------- + + def _new_window(self) -> None: + self._window_started = self._clock() + self._attempts = self._overloads = 0 + self._ratios = [] + self._peak = self.active + + def _window(self) -> float: + if not self._latencies: + return _MIN_WINDOW + return max(_MIN_WINDOW, 3 * statistics.median(self._latencies[-50:])) + + def attempt( + self, url: str, status: Optional[int], error: Optional[BaseException], elapsed: float, epoch: int + ) -> Optional[str]: + """Learn from one finished attempt. Returns a description when the limit changed.""" + host = host_key(url) + if host is None or epoch < self.epoch: + return None # an invalid URL, or sent before the last backoff + self._attempts += 1 + if status in _OVERLOAD_STATUSES or (error is not None and _is_overload(error)): + self._overloads += 1 + elif status is not None and elapsed > 0: + normal = self._normal.get(host) + if normal is None or elapsed < normal: + self._normal[host] = elapsed + else: + # Let the normal drift up slowly, so a lasting change of the network is accepted + self._normal[host] = normal * 1.002 + self._ratios.append(elapsed / self._normal[host]) + self._latencies.append(elapsed) + del self._latencies[:-200] + if self._overloads >= max(2, self.limit // 4) and self._overloads / self._attempts > _OVERLOADED: + return self._back_off( + f"the servers pushed back on {self._overloads} of {self._attempts} attempts" + ) + if self._clock() - self._window_started < self._window() or self._attempts < min(10, self.limit): + return None + return self._end_window() + + def _back_off(self, reason: str, factor: float = 0.75) -> Optional[str]: + previous = self.limit + if factor == 0.75: + self.ceiling, self._holding = self.limit, 0 + self.limit = max(1, int(self.limit * factor)) + self.slow_start = False + self.epoch += 1 + self._new_window() + return self._changed(previous, reason) + + def _end_window(self) -> Optional[str]: + if self._attempts and self._overloads / self._attempts > _OVERLOADED: + return self._back_off( + f"the servers pushed back on {self._overloads} of {self._attempts} attempts" + ) + if len(self._ratios) >= 3 and statistics.median(self._ratios) > _SLOW: + return self._back_off("responses slowed down", factor=0.9) + previous = self.limit + if self._peak >= self.limit: # the whole limit was used + if self.ceiling is not None and self.limit >= self.ceiling: + self.ceiling = None # a probe at the old ceiling went well + grown = self.limit * 2 if self.slow_start else self.limit + max(1, self.limit // 10) + if self.ceiling is not None and grown >= self.ceiling: + if self.limit < self.ceiling - 1: + grown = self.ceiling - 1 # close in, but stay below + elif self._holding < _HOLD_WINDOWS: + self._holding += 1 + grown = self.limit + else: + self._holding = 0 + grown = self.ceiling # probe the ceiling once + self.limit = min(self.maximum, grown) + self._new_window() + if self.limit > previous and self._condition is not None: + asyncio.ensure_future(self._wake()) + return self._changed(previous, "responses are healthy") + + def _changed(self, previous: int, reason: str) -> Optional[str]: + if self.limit == previous: + return None + self.changes += 1 + self.lowest, self.highest = min(self.lowest, self.limit), max(self.highest, self.limit) + return f"concurrency {previous} -> {self.limit}: {reason}" + + async def _wake(self) -> None: + assert self._condition is not None + async with self._condition: + self._condition.notify_all() + + +def _is_overload(error: BaseException) -> bool: + import aiohttp + + from ._socks import is_proxy_error + + not_load = [aiohttp.InvalidURL, ValueError, aiohttp.ClientSSLError] + if hasattr(aiohttp, "ClientConnectorDNSError"): + not_load.append(aiohttp.ClientConnectorDNSError) # a name that does not resolve + if isinstance(error, tuple(not_load)): + return False + # asyncio.TimeoutError and the built-in TimeoutError are different classes before Python 3.11 + timeouts = (asyncio.TimeoutError, TimeoutError) + return isinstance(error, (*timeouts, aiohttp.ClientConnectionError)) or is_proxy_error(error) diff --git a/reqstorm/_files.py b/reqstorm/_files.py index 9c16b9c..35b64a9 100644 --- a/reqstorm/_files.py +++ b/reqstorm/_files.py @@ -439,7 +439,10 @@ def pending() -> Iterator[Union[str, Request]]: report = Report() writer = _Writer(sink, ordered=ordered, batch_size=batch_size, flush_interval=flush_interval) writer.start() - run.start(describe(concurrency=options.get("concurrency", 100), rate_limit=options.get("rate_limit"), + concurrency = options.get("concurrency", 100) + if concurrency == "auto": + concurrency = f"auto (max {options.get('max_concurrency', 500)})" + run.start(describe(concurrency=concurrency, rate_limit=options.get("rate_limit"), retries=options.get("retries"), retry_rounds=retry_rounds, output=target, skipped=len(done) if resume else 0)) # fmt: skip try: diff --git a/reqstorm/_observe.py b/reqstorm/_observe.py index 614b60e..36fa68f 100644 --- a/reqstorm/_observe.py +++ b/reqstorm/_observe.py @@ -59,6 +59,8 @@ class ProgressInfo: rounds: int = 0 paused: Dict[str, float] = field(default_factory=dict) """Hosts the server asked to wait (``rate_limit="auto"``), with seconds left.""" + concurrency: Optional[int] = None + """With ``concurrency="auto"``: the number of requests currently allowed in flight.""" finished: bool = False def __str__(self) -> str: @@ -68,7 +70,10 @@ def __str__(self) -> str: count = str(self.done) parts = [f"reqstorm: {count}", f"ok {self.ok}", f"failed {self.failed}"] if not self.finished: - parts.append(f"active {self.in_flight}") + active = f"active {self.in_flight}" + if self.concurrency is not None: + active += f"/{self.concurrency}" # with concurrency="auto": in flight / allowed + parts.append(active) if self.retries: parts.append(f"retries {self.retries}") parts.append(f"{self.rate:.1f} req/s") @@ -216,6 +221,7 @@ def __init__( self.done = self.ok = self.failed = self.in_flight = self.retries = self.attempts = 0 self.round = self.rounds = 0 self.limiters: list = [] + self.controller: Any = None # AutoConcurrency with concurrency="auto" self._recent: Deque[float] = collections.deque() self._task: Optional[asyncio.Task] = None self._closers: list = [] @@ -362,6 +368,7 @@ def snapshot(self, finished: bool = False) -> ProgressInfo: total=self.total, done=self.done, ok=self.ok, failed=self.failed, in_flight=self.in_flight, retries=self.retries, rate=rate, elapsed=elapsed, eta=eta, round=self.round, rounds=self.rounds, paused=paused, finished=finished, + concurrency=self.controller.limit if self.controller is not None else None, ) # fmt: skip def _report(self, info: ProgressInfo) -> None: @@ -398,6 +405,11 @@ async def finish(self) -> None: format_duration(info.elapsed), self.ok, self.failed, self.retries, event="finish", total=self.done, ok=self.ok, failed=self.failed, retries=self.retries, elapsed=round(info.elapsed, 3)) # fmt: skip + if self.controller is not None: + c = self.controller + self.log(logging.INFO, "concurrency auto: ended at %d, ranged from %d to %d over %d changes", + c.limit, c.lowest, c.highest, c.changes, event="concurrency_summary", + concurrency=c.limit, lowest=c.lowest, highest=c.highest) # fmt: skip for close in self._closers: close() self._closers.clear() diff --git a/reqstorm/_resources.py b/reqstorm/_resources.py new file mode 100644 index 0000000..668f624 --- /dev/null +++ b/reqstorm/_resources.py @@ -0,0 +1,77 @@ +"""Keep the number of open connections within the process's open file limit.""" + +from __future__ import annotations + +import sys +from typing import Callable, Optional, Tuple + +# File descriptors kept free for everything else: log and output files, the cache, +# DNS lookups, the interpreter itself +RESERVED = 64 + +Notify = Callable[[int, str], None] # (log level, message) + + +def _limits() -> Optional[Tuple[int, int]]: + if sys.platform == "win32": + return None # no RLIMIT_NOFILE; Windows sockets are not bound by it + try: + import resource + except ImportError: + return None + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + return soft, hard + + +def _raise_to(target: int, hard: int) -> int: + """Raise the soft limit towards ``target``; returns the soft limit now in effect.""" + import resource + + soft = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + candidates = [target] + if sys.platform == "darwin": + candidates.append(10240) # macOS refuses more than OPEN_MAX for many processes + for candidate in candidates: + if hard != resource.RLIM_INFINITY: + candidate = min(candidate, hard) + if candidate <= soft: + continue + try: + resource.setrlimit(resource.RLIMIT_NOFILE, (candidate, hard)) + return candidate + except (ValueError, OSError): + continue + return soft + + +def fit_concurrency(concurrency: int, pools: int, notify: Notify) -> int: + """The concurrency to use so that connections never run out of file descriptors. + + Each connection is an open file. ``pools`` is the number of connection pools that may + each hold ``concurrency`` connections (the main session plus one per SOCKS proxy). + The soft limit is raised as far as the system allows; if that is still not enough, + the concurrency is lowered and ``notify`` explains why. + """ + limits = _limits() + if limits is None: + return concurrency + soft, hard = limits + needed = concurrency * max(pools, 1) + RESERVED + if needed <= soft: + return concurrency + import logging + + available = _raise_to(needed, hard) + if available >= needed: + notify( + logging.INFO, + f"raised the open file limit from {soft} to {available} for concurrency {concurrency}", + ) + return concurrency + fitted = max(1, (available - RESERVED) // max(pools, 1)) + notify( + logging.WARNING, + f"concurrency lowered from {concurrency} to {fitted}: the open file limit is {available} " + f"and each connection needs one. Raise it with `ulimit -n {needed}` to use {concurrency}.", + ) + return fitted diff --git a/tests/conftest.py b/tests/conftest.py index 23090fc..02d8b20 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -134,9 +134,42 @@ async def proxy_check(request: web.Request) -> web.Response: {"host": request.host, "port": request.transport.get_extra_info("sockname")[1]} ) + active: collections.Counter = collections.Counter() + peak: collections.Counter = collections.Counter() + + async def capacity(request: web.Request) -> web.Response: + """Serves `max` requests at a time per `key`; more at once get a 503, like an overloaded API.""" + key = request.query["key"] + if active[key] >= int(request.query["max"]): + return web.Response(status=503, text="busy") + active[key] += 1 + peak[key] = max(peak[key], active[key]) + try: + await asyncio.sleep(float(request.query.get("delay", "0.03"))) + finally: + active[key] -= 1 + return web.Response(text="ok") + + async def congested(request: web.Request) -> web.Response: + """Never fails, but each request in flight adds `per` seconds to every response.""" + key = request.query["key"] + active[key] += 1 + peak[key] = max(peak[key], active[key]) + try: + await asyncio.sleep(0.01 + float(request.query.get("per", "0.01")) * active[key]) + finally: + active[key] -= 1 + return web.Response(text="ok") + + async def peaks(request: web.Request) -> web.Response: + return web.json_response(dict(peak)) + app = web.Application() app.add_routes( [ + web.get("/capacity", capacity), + web.get("/congested", congested), + web.get("/peaks", peaks), web.get("/pages/next", pages_next), web.get("/pages/link", pages_link), web.get("/pages/cursor", pages_cursor), diff --git a/tests/test_cli.py b/tests/test_cli.py index 3c7814d..06ccffd 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -156,3 +156,24 @@ def test_progress_is_shown_when_writing_to_stdout(thread_server, tmp_path, capsy assert main([str(urls), "--flush-interval", "0"]) == 0 captured = capsys.readouterr() assert "1/1 (100%)" in captured.err and len(_lines(captured.out)) == 1 + + +def test_auto_concurrency_from_the_command_line(thread_server, tmp_path, capsys): + urls = tmp_path / "urls.txt" + urls.write_text(f"{thread_server}/ok\n" * 5) + assert ( + main([str(urls), "-c", "auto", "--max-concurrency", "4", "-v", "-o", str(tmp_path / "out.jsonl")]) + == 0 + ) + err = capsys.readouterr().err + assert "concurrency auto (max 4)" in err and "concurrency auto: ended at" in err + assert main([str(urls), "-c", "auto", "--estimate"]) == 0 # estimates with the maximum + assert "5 requests" in capsys.readouterr().out + + +def test_invalid_concurrency_on_the_command_line(tmp_path, capsys): + urls = tmp_path / "urls.txt" + urls.write_text("https://api.example.com/\n") + with pytest.raises(SystemExit) as exit_info: + main([str(urls), "-c", "fast"]) + assert exit_info.value.code == 2 and "invalid concurrency 'fast'" in capsys.readouterr().err diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py new file mode 100644 index 0000000..c018919 --- /dev/null +++ b/tests/test_concurrency.py @@ -0,0 +1,302 @@ +import logging + +import aiohttp +import pytest + +import reqstorm +from reqstorm import _resources +from reqstorm._concurrency import AutoConcurrency +from reqstorm._resources import fit_concurrency + + +class Clock: + def __init__(self): + self.now = 0.0 + + def __call__(self): + return self.now + + +def _feed(control, clock, count, status=200, elapsed=0.03, error=None, url="https://api.test/x", epoch=None): + """`count` attempts sent together, so all in the same epoch.""" + epoch = control.epoch if epoch is None else epoch + change = None + for _ in range(count): + change = control.attempt(url, status, error, elapsed, epoch) or change + return change + + +def _window(control, clock, status=200, elapsed=0.03): + """One window in which the whole limit was in use and every attempt got `status`.""" + control._peak = control.limit + clock.now += 1.0 + return _feed(control, clock, max(10, control.limit), status=status, elapsed=elapsed) + + +async def _peaks(server): + async with aiohttp.ClientSession() as session: + async with session.get(server + "/peaks") as response: + return await response.json() + + +# -- the controller --------------------------------------------------------------------- + + +def test_slow_start_doubles_then_grows_by_ten_percent(): + clock = Clock() + control = AutoConcurrency(maximum=500, clock=clock) + assert control.limit == 8 + _window(control, clock) + assert control.limit == 16 + _window(control, clock, status=503) + assert control.limit == 12 and not control.slow_start and control.ceiling == 16 + control.ceiling = None + _window(control, clock) + assert control.limit == 13 + + +def test_pushback_lowers_the_limit_without_waiting_for_the_window(): + clock = Clock() + control = AutoConcurrency(maximum=500, start=40, clock=clock) + change = _feed(control, clock, 10, status=503) # no time has passed + assert control.limit == 30 and change.startswith("concurrency 40 -> 30: the servers pushed back") + + +SIGNALS = [ + (429, None), + (502, None), + (504, None), + (None, aiohttp.ServerDisconnectedError()), + (None, TimeoutError()), +] + + +@pytest.mark.parametrize("status, error", SIGNALS) +def test_overload_signals(status, error): + clock = Clock() + control = AutoConcurrency(maximum=500, start=20, clock=clock) + _feed(control, clock, 5, status=status, error=error) + assert control.limit == 15 + + +def test_attempts_sent_before_a_backoff_are_not_counted_again(): + clock = Clock() + control = AutoConcurrency(maximum=500, start=40, clock=clock) + old_epoch = control.epoch + _feed(control, clock, 10, status=503) + assert control.limit == 30 + _feed(control, clock, 50, status=503, epoch=old_epoch) # stragglers from the burst + assert control.limit == 30 + + +def test_errors_that_say_nothing_about_load_are_ignored(): + clock = Clock() + control = AutoConcurrency(maximum=500, clock=clock) + _window(control, clock, status=404) # a missing page is not overload + assert control.limit == 16 + control = AutoConcurrency(maximum=500, clock=clock) + _feed(control, clock, 20, status=None, error=aiohttp.InvalidURL("x"), url="not a url") + clock.now += 1 + _feed(control, clock, 1, status=None, error=aiohttp.InvalidURL("x"), url="not a url") + assert control.limit == 8 and control._attempts == 0 + + +def test_slow_responses_ease_off_relative_to_each_host(): + clock = Clock() + control = AutoConcurrency(maximum=500, start=10, clock=clock) + control.slow_start = False + for _ in range(5): + control.attempt("https://fast.test/", 200, None, 0.02, 0) + control.attempt("https://slow.test/", 200, None, 1.0, 0) + control._peak = control.limit + clock.now += 5 + control.attempt("https://fast.test/", 200, None, 0.02, 0) + assert control.limit == 11 # each host at its own normal speed: healthy + for _ in range(9): + control.attempt("https://fast.test/", 200, None, 0.2, control.epoch) # ten times its normal + clock.now += 5 + control.attempt("https://fast.test/", 200, None, 0.2, control.epoch) + assert control.limit == 9 # nine tenths + + +def test_the_limit_grows_only_when_it_is_used(): + clock = Clock() + control = AutoConcurrency(maximum=500, clock=clock) + control._peak = 3 # only 3 of 8 places were ever used + clock.now += 1 + _feed(control, clock, 10) + assert control.limit == 8 + + +def test_the_ceiling_is_approached_then_probed_after_a_pause(): + clock = Clock() + control = AutoConcurrency(maximum=500, start=16, clock=clock) + _window(control, clock, status=503) # pushback at 16 + assert control.limit == 12 and control.ceiling == 16 + for expected in (13, 14, 15): # normal growth up to just below the ceiling + _window(control, clock) + assert control.limit == expected + for _ in range(8): + _window(control, clock) + assert control.limit == 15 # holding + _window(control, clock) + assert control.limit == 16 # one probe + _window(control, clock) + assert control.ceiling is None and control.limit == 17 # the probe went well + + +def test_limit_stays_between_one_and_the_maximum(): + clock = Clock() + control = AutoConcurrency(maximum=10, clock=clock) + for _ in range(10): + _window(control, clock) + assert control.limit == 10 + for _ in range(20): + _feed(control, clock, 10, status=503) + assert control.limit == 1 + + +async def test_the_gate_holds_attempts_at_the_limit(): + import asyncio + + control = AutoConcurrency(maximum=500, start=2) + await control.acquire() + await control.acquire() + third = asyncio.ensure_future(control.acquire()) + await asyncio.sleep(0.05) + assert not third.done() and control.active == 2 + await control.release() + assert await asyncio.wait_for(third, 1) == 0 and control.active == 2 + + +# -- end to end --------------------------------------------------------------------------- + + +async def test_auto_finds_the_capacity_of_an_overloaded_api(server): + urls = [server + "/capacity?key=cap12&max=12"] * 400 + seen = [] + results = await reqstorm.fetch_all( + urls, concurrency="auto", retries=10, backoff=0.01, progress=seen.append + ) + assert all(result.ok for result in results) + attempts = sum(result.attempts for result in results) + assert attempts < 400 * 1.15, attempts # few attempts were turned away + final = seen[-1] + assert final.concurrency is not None and 6 <= final.concurrency <= 16 + + +async def test_auto_backs_off_when_responses_slow_down(server): + urls = [server + "/congested?key=slow&per=0.01"] * 300 + seen = [] + await reqstorm.fetch_all(urls, concurrency="auto", progress=seen.append) + peak = (await _peaks(server))["slow"] + assert peak < 60, peak # without backing off it would climb towards 500 + assert seen[-1].concurrency < 60 + + +async def test_auto_respects_max_concurrency(server): + seen = [] + await reqstorm.fetch_all( + [server + "/ok"] * 200, concurrency="auto", max_concurrency=12, progress=seen.append + ) + assert max(info.concurrency for info in seen) <= 12 + + +async def test_auto_with_pagination_and_files(server, tmp_path): + paginate = reqstorm.NextLink("links.next") + target = tmp_path / "pages.jsonl" + summary = await reqstorm.fetch_to_file( + [server + "/pages/next"] * 3, target, concurrency="auto", paginate=paginate + ) + assert summary.ok == 9 + + +async def test_auto_is_logged(server): + import io + + output = io.StringIO() + urls = [server + "/capacity?key=logged&max=1000&delay=0.03"] * 300 # long enough for a few windows + await reqstorm.fetch_all(urls, concurrency="auto", log_level="DEBUG", log_file=output) + text = output.getvalue() + assert "concurrency auto (max 500)" in text + assert "concurrency 8 -> 16: responses are healthy" in text + assert "concurrency auto: ended at" in text + + +@pytest.mark.parametrize("value", [0, -1, "fast", 1.5, True]) +async def test_invalid_concurrency(server, value): + with pytest.raises(ValueError, match="concurrency"): + await reqstorm.fetch_all([server + "/ok"], concurrency=value) + + +# -- open file limit ------------------------------------------------------------------------ + + +def _fake_limits(monkeypatch, soft, hard, can_raise_to=None): + state = {"soft": soft} + monkeypatch.setattr(_resources, "_limits", lambda: (state["soft"], hard)) + + def raise_to(target, hard_limit): + allowed = min(target, can_raise_to if can_raise_to is not None else hard_limit) + state["soft"] = max(state["soft"], allowed) + return state["soft"] + + monkeypatch.setattr(_resources, "_raise_to", raise_to) + return state + + +def test_enough_file_descriptors_change_nothing(monkeypatch): + _fake_limits(monkeypatch, 1024, 4096) + notes = [] + assert fit_concurrency(100, 1, lambda level, text: notes.append(text)) == 100 and notes == [] + + +def test_the_limit_is_raised_when_the_system_allows(monkeypatch): + state = _fake_limits(monkeypatch, 256, 65536) + notes = [] + assert fit_concurrency(1000, 1, lambda level, text: notes.append((level, text))) == 1000 + assert state["soft"] == 1064 + assert notes == [(logging.INFO, "raised the open file limit from 256 to 1064 for concurrency 1000")] + + +def test_concurrency_is_lowered_when_the_limit_cannot_be_raised(monkeypatch): + _fake_limits(monkeypatch, 256, 256) + notes = [] + assert fit_concurrency(1000, 1, lambda level, text: notes.append((level, text))) == 192 + level, text = notes[0] + assert level == logging.WARNING + assert text.startswith("concurrency lowered from 1000 to 192: the open file limit is 256") + assert "ulimit -n 1064" in text + + +def test_socks_pools_count_towards_the_limit(monkeypatch): + _fake_limits(monkeypatch, 1024, 1024) + assert fit_concurrency(500, 3, lambda level, text: None) == (1024 - 64) // 3 + + +def test_windows_has_no_file_limit(monkeypatch): + monkeypatch.setattr(_resources.sys, "platform", "win32") + assert _resources._limits() is None + assert fit_concurrency(100_000, 1, lambda level, text: None) == 100_000 + + +def test_the_real_limit_is_raised_in_a_fresh_process(thread_server): + """End to end on this machine: lower the soft limit, then ask for more connections.""" + import subprocess + import sys + + if sys.platform == "win32": + pytest.skip("no RLIMIT_NOFILE on Windows") + code = f""" +import resource, reqstorm +soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) +resource.setrlimit(resource.RLIMIT_NOFILE, (256, hard)) +results = reqstorm.fetch_all_sync(['{thread_server}/ok'] * 20, concurrency=600, log_level='INFO') +print(resource.getrlimit(resource.RLIMIT_NOFILE)[0] > 256 or 'lowered', all(r.ok for r in results)) +""" + completed = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=120) + assert completed.returncode == 0, completed.stderr + raised = "raised the open file limit from 256" in completed.stderr + lowered = "concurrency lowered from 600" in completed.stderr + assert raised or lowered, completed.stderr + assert completed.stdout.split()[-1] == "True"