scrapely-python 0.1.51__tar.gz → 0.1.56__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/CHANGELOG.md +25 -0
  2. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/PKG-INFO +2 -2
  3. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/pyproject.toml +2 -2
  4. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/__init__.py +1 -1
  5. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/actor.py +50 -2
  6. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/charging.py +13 -4
  7. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_client.py +48 -2
  8. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/resume_dedupe.py +82 -20
  9. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/solver.py +45 -2
  10. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/api_client.py +183 -17
  11. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/client.py +6 -0
  12. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely_python.egg-info/PKG-INFO +2 -2
  13. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely_python.egg-info/requires.txt +1 -1
  14. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/LICENSE +0 -0
  15. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/LICENSE-APACHE +0 -0
  16. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/MANIFEST.in +0 -0
  17. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/NOTICE +0 -0
  18. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/README.md +0 -0
  19. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/setup.cfg +0 -0
  20. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/_browser_locations.py +0 -0
  21. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/browser_configuration.py +0 -0
  22. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/cdp_retry.py +0 -0
  23. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/charging_client.py +0 -0
  24. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/configuration.py +0 -0
  25. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/crypto/__init__.py +0 -0
  26. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/crypto/_secrets.py +0 -0
  27. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/errors.py +0 -0
  28. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/events/__init__.py +0 -0
  29. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/events/_types.py +0 -0
  30. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/events/event_manager.py +0 -0
  31. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/__init__.py +0 -0
  32. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_capture.py +0 -0
  33. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_compat.py +0 -0
  34. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_detect.py +0 -0
  35. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_headers.py +0 -0
  36. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_options.py +0 -0
  37. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_policy.py +0 -0
  38. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_profiles.py +0 -0
  39. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_response.py +0 -0
  40. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_stats.py +0 -0
  41. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/_transport.py +0 -0
  42. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/http/profiles.json +0 -0
  43. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/log.py +0 -0
  44. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/patch_browser_pool.py +0 -0
  45. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/pricing_types.py +0 -0
  46. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/proxy_configuration.py +0 -0
  47. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/py.typed +0 -0
  48. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/request_loaders/__init__.py +0 -0
  49. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  50. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/__init__.py +0 -0
  51. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/_actor_runner.py +0 -0
  52. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/_async_thread.py +0 -0
  53. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/_logging_config.py +0 -0
  54. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/_serialization.py +0 -0
  55. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/_warnings.py +0 -0
  56. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  57. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  58. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  59. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  60. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  61. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  62. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  63. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/requests.py +0 -0
  64. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/scheduler.py +0 -0
  65. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/scrapy/utils.py +0 -0
  66. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/__init__.py +0 -0
  67. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/_file_system/__init__.py +0 -0
  68. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  69. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  70. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/_metadata.py +0 -0
  71. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/patch_storage.py +0 -0
  72. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  73. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  74. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  75. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  76. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  77. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/types.py +0 -0
  78. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage/utils.py +0 -0
  79. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storage_clients/__init__.py +0 -0
  80. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/storages/__init__.py +0 -0
  81. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/types.py +0 -0
  82. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely/webhook.py +0 -0
  83. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely_python.egg-info/SOURCES.txt +0 -0
  84. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  85. {scrapely_python-0.1.51 → scrapely_python-0.1.56}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,31 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.56] - 2026-12-05
8
+
9
+ - **A charged dataset push cut off by a stop signal no longer leaves its charge standing.** When the platform ends a run (a forced worker update after its drain limit), the container gets `SIGTERM` and the SDK exits within a few seconds. A push whose rows had been charged but that was still waiting out a `429` retry (`Retry-After` up to 60 s) never landed, and its charge was billed for rows that were not stored. On a stop signal such a push now stops retrying (an attempt in flight gets 2 seconds), fails, and its charge is voided as for any failed push. The platform settles a run it ends this way only after the container stopped, so the void is accepted. Pushes that were not charged keep their retries.
10
+
11
+ ## [0.1.55] - 2026-12-05
12
+
13
+ - **A dataset push or record write refused with `503 schema-validation-busy` is sent again.** The API answers it when every schema-validation slot of the account is in use (many parallel runs writing to datasets or stores with a schema), with `Retry-After: 1`, before it reads the push's `Idempotency-Key` or stores anything. The SDK re-sent it only when it took the API to de-duplicate keyed pushes: in 0.1.51 and earlier only after an earlier push of the run had shown that, so the first push of a run that got this answer raised the error to the Actor and the run failed; from 0.1.54 until a keyed push is stored without the `X-Scrapely-Idempotency` header. Such a `503` is now retried like the rate limiter's own `503`, for every write: exponential backoff with jitter, never sooner than `Retry-After`, within the same retry window (5 minutes, `SCRAPELY_API_RETRY_WINDOW_SECS`). It is recognised by its error type, not its message. A push that still fails after the window certainly stored nothing, so its charge is voided as before.
14
+
15
+ ## [0.1.54] - 2026-12-02
16
+
17
+ - **A dataset push whose answer was lost is sent again with its key, also the first push of a run.** Pushes carry an `Idempotency-Key` and the API stores a re-sent push once, but the SDK re-sent one only after an earlier keyed push of the run had shown that the API de-duplicates. The first push of a run that timed out or lost its connection was therefore raised to the Actor, whose own retry sent the rows again under a new key: stored twice and charged twice (prod 2026-12-02, while Cloudflare routed our traffic through distant locations). The SDK now presumes de-duplication for dataset pushes, as it already did for key-value record writes, until a keyed push is stored without the API's `X-Scrapely-Idempotency` header (an API without the feature).
18
+ - **Request-queue adds are sent again after a lost answer.** The API stores a request once per id (derived from its `uniqueKey`) and answers a repeat with `wasAlreadyPresent`, so a single or batch add that timed out after sending is now retried instead of failing.
19
+ - **Per-attempt timeouts.** Connecting to the API gets 10 s (a connect failure is retried for every call: nothing was sent yet). A call that is safe to send again waits 20 s on its first attempt, then 30, 45 and 60 s, so a slow answer on a bad network path is retried sooner and a slow but progressing call still completes. A call that must not be sent again waits 60 s (was 30 s), since its timeout is final. A client created with its own `timeout` keeps it.
20
+
21
+ ## [0.1.53] - 2026-12-01
22
+
23
+ - **A resumed run's rows without `id` are not charged again either.** When a resurrected or rebooted run's saved rows have no `id` and the Actor named no key (`Actor.set_result_key`), the SDK now tells them apart by the saved rows' own id fields: the fields whose name ends in `Id` or `_id` (`reviewId`, `place_id`) and that differ in every saved row, together. A charged row whose values of those fields were already saved is not saved or charged again. Before, such rows were all saved and charged a second time (a resurrected Google Maps reviews run: 3,720 of its 3,787 reviews). Nothing changes when no such field identifies every saved row, when the Actor named its key, or in a run that was not resumed.
24
+ - **`scrapely.http` writes the `HTTP_STATS` record once per run.** Every client wrote it on close, so an Actor with N clients stored the same key N times (each a billed key-value write). The record already holds the run totals of all clients and keeps its keys; it is now written when the last open client closes (at most once per 30 s) and at Actor shutdown for anything still pending, so it also no longer misses requests made by clients that were open when another one closed.
25
+ - Requires `scrapely-client-python` 1.0.13 or newer for the API client the SDK hands to Actors (it was on 1.0.9). That client no longer sends an unkeyed `POST` or `PATCH` again when the API answers that the write may or may not have been applied (a `503` with `X-Scrapely-Status: 504`, type `outcome-unknown`, sent when a platform database switch cut the write).
26
+ - `Actor.start()`, `Actor.call()` and `Actor.call_task()` send an `Idempotency-Key`, so a run start whose answer was lost (a timeout while the platform waits out a database switch) is sent again safely and returns the same run, never a second one.
27
+
28
+ ## [0.1.52] - 2026-11-25
29
+
30
+ - **A crash says why.** When an Actor raises inside `async with Actor:` (or `Actor.main`), the run now ends with the status message "Actor failed: <error type>: <message>" (at most 300 characters), stored as final. Before, the error was only logged and the run kept its last progress line ("page 4, 18 stores saved..."), so the run page did not say why it failed. A `status_message` the Actor gave for its exit is kept, and `Actor.fail()` / `Actor.exit()` are unchanged. Best effort: when the message cannot be stored, the exit goes on as before.
31
+
7
32
  ## [0.1.51] - 2026-11-18
8
33
 
9
34
  - **A charged push that fails is always voided.** `Actor.push_data(items, charged_event_name)` and `push_data(rows, charges={...})` charge before the push; when the push then fails, its charge is now voided also when the outcome is unknown: a read timeout or dropped connection after sending, an error after a re-send that may have been stored, or the API's `503 push-outcome-unknown`. Before, the charge stood in those cases because the rows might be in the dataset. A user is now never charged for rows that may not have been stored; rows that were stored anyway are free. Pushes that succeed are charged exactly as before.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.51
3
+ Version: 0.1.56
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <hello@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0
@@ -26,7 +26,7 @@ License-File: NOTICE
26
26
  Requires-Dist: httpx>=0.25.0
27
27
  Requires-Dist: crawlee<2.0.0,>=1.8.0
28
28
  Requires-Dist: websockets>=12.0
29
- Requires-Dist: scrapely-client-python<2,>=1.0.2
29
+ Requires-Dist: scrapely-client-python<2,>=1.0.13
30
30
  Requires-Dist: pydantic>=2.0.0
31
31
  Requires-Dist: cryptography>=42.0.0
32
32
  Requires-Dist: wreq<0.14,>=0.13; python_version >= "3.11"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scrapely-python"
7
- version = "0.1.51"
7
+ version = "0.1.56"
8
8
  description = "Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform"
9
9
  readme = "README.md"
10
10
  license = "MIT AND Apache-2.0"
@@ -28,7 +28,7 @@ dependencies = [
28
28
  "httpx>=0.25.0",
29
29
  "crawlee>=1.8.0,<2.0.0",
30
30
  "websockets>=12.0",
31
- "scrapely-client-python>=1.0.2,<2",
31
+ "scrapely-client-python>=1.0.13,<2",
32
32
  "pydantic>=2.0.0",
33
33
  "cryptography>=42.0.0",
34
34
  "wreq>=0.13,<0.14; python_version>='3.11'",
@@ -325,7 +325,7 @@ if TYPE_CHECKING: # Static analysers and IDEs see the lazy names as plain impor
325
325
  )
326
326
  from .webhook import Webhook, WebhookEventType
327
327
 
328
- __version__ = '0.1.51'
328
+ __version__ = '0.1.56'
329
329
  __all__ = [
330
330
  # Core
331
331
  'Actor',
@@ -50,6 +50,7 @@ from .types import (
50
50
  WebhookOptions,
51
51
  )
52
52
  from .webhook import Webhook
53
+ from uuid import uuid4
53
54
 
54
55
  if TYPE_CHECKING:
55
56
  from crawlee.events import EventManager
@@ -262,6 +263,18 @@ def _system_exit_code(exc: Any) -> int:
262
263
  return code if isinstance(code, int) else 1
263
264
 
264
265
 
266
+
267
+ #: Longest crash reason stored as the run's final status message.
268
+ CRASH_STATUS_MESSAGE_CHARS = 300
269
+
270
+
271
+ def crash_status_message(exc_type: Any, exc_val: Any) -> str:
272
+ """The final status message of a run whose Actor raised: "Actor failed: <type>: <message>", shortened."""
273
+ name = getattr(exc_type, '__name__', None) or 'Error'
274
+ text = ' '.join(str(exc_val or '').split())
275
+ msg = f'Actor failed: {name}: {text}' if text else f'Actor failed: {name}'
276
+ return msg if len(msg) <= CRASH_STATUS_MESSAGE_CHARS else msg[: CRASH_STATUS_MESSAGE_CHARS - 1] + '…'
277
+
265
278
  class _ActorMeta(type):
266
279
  """Metaclass enabling async with Actor: by delegating to classmethods."""
267
280
 
@@ -282,6 +295,11 @@ class _ActorMeta(type):
282
295
  elif exc_type is not None:
283
296
  cls._exit_code = 1
284
297
  logger.error(f'Actor failed: {exc_val}')
298
+ # The crash is the run's final message, not its last progress line (prod 2026-11-18: square-online-stores-scraper
299
+ # FAILED on a DatasetItemTooLargeError and showed "Searching 'usb camera': page 4, 18 stores saved..."). Best
300
+ # effort: a failed update never blocks the exit.
301
+ if cls._failure is None:
302
+ await cls._persist_terminal_status_message(crash_status_message(exc_type, exc_val))
285
303
  await cls._shutdown()
286
304
 
287
305
 
@@ -396,6 +414,12 @@ class Actor(metaclass=_ActorMeta):
396
414
  elif exc_type is not None:
397
415
  cls._exit_code = 1
398
416
  logger.error(f'Actor failed: {exc_val}')
417
+ # The crash is the run's final message, not its last progress line (prod 2026-11-18: square-online-stores-scraper
418
+ # FAILED on a DatasetItemTooLargeError and showed "Searching 'usb camera': page 4, 18 stores saved..."). Best
419
+ # effort: a failed update never blocks the exit.
420
+ # A status_message the Actor gave for its exit (Actor(status_message=...)) is its own final word: kept.
421
+ if cls._failure is None and not self._instance_status_message:
422
+ await cls._persist_terminal_status_message(crash_status_message(exc_type, exc_val))
399
423
  elif cls._failure is not None:
400
424
  cls._exit_code = cls._failure[0] # fail(exit=False) earlier: the run stays failed
401
425
  else:
@@ -417,6 +441,9 @@ class Actor(metaclass=_ActorMeta):
417
441
  if cls._initialized:
418
442
  return
419
443
  cls._failure = None # a new lifecycle starts unfailed
444
+ from .storage.api_client import reset_shutdown
445
+
446
+ reset_shutdown() # a stop signal of an earlier lifecycle does not cut this one's pushes
420
447
 
421
448
  if options is None or options.configure_logging:
422
449
  _lazy('_configure_logging')()
@@ -534,6 +561,15 @@ class Actor(metaclass=_ActorMeta):
534
561
  cls._signal_shutdown_started = True
535
562
 
536
563
  def _run_shutdown() -> None:
564
+ # First: a charged push still retrying gives up, so its charge
565
+ # is voided before the hard exit (storage.api_client).
566
+ try:
567
+ from .storage.api_client import signal_shutdown
568
+
569
+ signal_shutdown()
570
+ except Exception:
571
+ pass
572
+
537
573
  async def _bounded() -> None:
538
574
  # Independent hard-exit timer: fires even if teardown hangs on a
539
575
  # stuck close() — the deadline cannot be swallowed by exceptions.
@@ -583,6 +619,16 @@ class Actor(metaclass=_ActorMeta):
583
619
  # the next Actor.init() retry.
584
620
  cleanup_error: Optional[BaseException] = None
585
621
  try:
622
+ # HTTP_STATS (run totals of every scrapely.http client) is written once, here,
623
+ # while storage is still open.
624
+ try:
625
+ http_client = sys.modules.get(__package__ + '.http._client') # only if scrapely.http was used
626
+ if http_client is not None:
627
+ await asyncio.wait_for(http_client.flush_http_stats(), timeout=10)
628
+ except BaseException as e: # noqa: BLE001 - best effort, never block teardown
629
+ if isinstance(e, asyncio.CancelledError):
630
+ cleanup_error = cleanup_error or e
631
+ logger.debug('HTTP_STATS flush at shutdown failed: %s', e)
586
632
  if cls._event_manager is not None:
587
633
  try:
588
634
  await cls._event_manager.__aexit__(None, None, None)
@@ -1703,7 +1749,9 @@ class Actor(metaclass=_ActorMeta):
1703
1749
  )
1704
1750
 
1705
1751
  data = _payload_dict(
1706
- await client.post_json(f'/v2/actors/{actor_id}/runs', data=run_input, params=params or None)
1752
+ # Keyed: a resend after a lost answer (a timeout while the API waits out a database switch)
1753
+ # returns the same run instead of starting a second one.
1754
+ await client.post_json(f'/v2/actors/{actor_id}/runs', data=run_input, params=params or None, idempotency_key=uuid4().hex)
1707
1755
  )
1708
1756
 
1709
1757
  return ActorRun(
@@ -1866,7 +1914,7 @@ class Actor(metaclass=_ActorMeta):
1866
1914
  )
1867
1915
 
1868
1916
  data = _payload_dict(
1869
- await client.post_json(f'/v2/actor-tasks/{task_id}/runs', data=task_input, params=params or None)
1917
+ await client.post_json(f'/v2/actor-tasks/{task_id}/runs', data=task_input, params=params or None, idempotency_key=uuid4().hex)
1870
1918
  )
1871
1919
  run_id = data.get('id', '')
1872
1920
  if not run_id:
@@ -2309,7 +2309,7 @@ async def _push_data_and_charge_one(
2309
2309
  )
2310
2310
  if accepted_for_items > 0:
2311
2311
  try:
2312
- await _gated_push(push_fn, limited_items[:accepted_for_items])
2312
+ await _gated_push(push_fn, limited_items[:accepted_for_items], charged=True)
2313
2313
  except Exception as push_err:
2314
2314
  # A result is billed only if it was saved: void this
2315
2315
  # operation's platform charges and unwind local
@@ -2582,7 +2582,7 @@ async def _push_data_with_charges_one(
2582
2582
  if is_default_dataset:
2583
2583
  charging_manager._note_refused_default_dataset_items(len(rows_in) - len(kept))
2584
2584
  try:
2585
- await _gated_push(push_fn, kept)
2585
+ await _gated_push(push_fn, kept, charged=True)
2586
2586
  except Exception as push_err:
2587
2587
  logger.error('Dataset push failed after charges accepted (rows=%s): %s; voiding the charges', rows, push_err)
2588
2588
  # Voided also when the outcome is unknown: never charge for rows that may not be stored.
@@ -2622,12 +2622,21 @@ def _push_is_paid_per_item(
2622
2622
  return any((charging_manager._calculate_event_price(name) or Decimal('0')) > 0 for name in names)
2623
2623
 
2624
2624
 
2625
- async def _gated_push(push_fn: Any, items: List[Dict[str, Any]]) -> Any:
2626
- """Run a push already decided by push_data_and_charge (storage skips its own check)."""
2625
+ async def _gated_push(push_fn: Any, items: List[Dict[str, Any]], charged: bool = False) -> Any:
2626
+ """Run a push already decided by push_data_and_charge (storage skips its own check).
2627
+
2628
+ ``charged``: its rows were charged first. On Actor shutdown such a push stops
2629
+ retrying (storage.api_client.SHUTDOWN_PUSH_GRACE_SECS), so it fails and its
2630
+ charge is voided instead of standing for rows that were never stored.
2631
+ """
2632
+ from .storage.api_client import _shutdown_interruptible
2633
+
2627
2634
  token = _charge_gated_push.set(True)
2635
+ shutdown_token = _shutdown_interruptible.set(charged)
2628
2636
  try:
2629
2637
  return await push_fn(items)
2630
2638
  finally:
2639
+ _shutdown_interruptible.reset(shutdown_token)
2631
2640
  _charge_gated_push.reset(token)
2632
2641
 
2633
2642
 
@@ -265,6 +265,7 @@ class _Base:
265
265
  self._caller_cookies = CookieStore(self)
266
266
  self.cookies: Any = self._caller_cookies
267
267
  self._closed = False
268
+ _note_client_opened()
268
269
  self._live: List[Identity] = []
269
270
  self._clock = _clock or time.monotonic
270
271
  if _transport is not None:
@@ -749,7 +750,9 @@ class AsyncClient(_Base):
749
750
  for ident in list(self._live):
750
751
  await self._retire(ident, force=True)
751
752
  self._idle.clear()
752
- await _write_http_stats_async(self._summary_and_stats())
753
+ data = self._summary_and_stats()
754
+ if _note_client_closed():
755
+ await _write_http_stats_async(data)
753
756
 
754
757
  close = aclose
755
758
 
@@ -1123,7 +1126,9 @@ class Client(_Base):
1123
1126
  for ident in list(self._live):
1124
1127
  self._retire(ident, force=True)
1125
1128
  self._idle.clear()
1126
- _write_http_stats_sync(self._summary_and_stats())
1129
+ data = self._summary_and_stats()
1130
+ if _note_client_closed():
1131
+ _write_http_stats_sync(data)
1127
1132
 
1128
1133
  def __enter__(self) -> 'Client':
1129
1134
  return self
@@ -1232,11 +1237,52 @@ def _actor() -> Any:
1232
1237
  return Actor if getattr(Actor, '_initialized', False) else None
1233
1238
 
1234
1239
 
1240
+ # HTTP_STATS holds the run totals (RUN_STATS merges every client), so it is written
1241
+ # once per run, not once per client: a client close writes only when it is the last
1242
+ # open client and the previous write is older than the throttle; otherwise the totals
1243
+ # stay pending and Actor shutdown (flush_http_stats) writes them.
1244
+ HTTP_STATS_MIN_INTERVAL_SECS = 30.0
1245
+ _stats_lock = threading.Lock()
1246
+ _open_clients = 0
1247
+ _stats_pending = False
1248
+ _stats_last_write: Optional[float] = None
1249
+
1250
+
1251
+ def _note_client_opened() -> None:
1252
+ global _open_clients
1253
+ with _stats_lock:
1254
+ _open_clients += 1
1255
+
1256
+
1257
+ def _note_client_closed() -> bool:
1258
+ """Record a close; True when this close should write HTTP_STATS now."""
1259
+ global _open_clients, _stats_pending
1260
+ with _stats_lock:
1261
+ _open_clients = max(0, _open_clients - 1)
1262
+ _stats_pending = True
1263
+ if _open_clients > 0:
1264
+ return False
1265
+ last = _stats_last_write
1266
+ return last is None or time.monotonic() - last >= HTTP_STATS_MIN_INTERVAL_SECS
1267
+
1268
+
1269
+ async def flush_http_stats() -> None:
1270
+ """Write HTTP_STATS now if totals changed since the last write (called at Actor shutdown)."""
1271
+ with _stats_lock:
1272
+ pending = _stats_pending
1273
+ if pending:
1274
+ await _write_http_stats_async(RUN_STATS.as_dict())
1275
+
1276
+
1235
1277
  async def _write_http_stats_async(data: Dict[str, Any]) -> None:
1236
1278
  """Best effort: the run's aggregate stats into the default key-value store."""
1279
+ global _stats_pending, _stats_last_write
1237
1280
  actor = _actor()
1238
1281
  if actor is None or not data.get('requests'):
1239
1282
  return
1283
+ with _stats_lock:
1284
+ _stats_pending = False
1285
+ _stats_last_write = time.monotonic()
1240
1286
  try:
1241
1287
  await actor.set_value(HTTP_STATS_KEY, data)
1242
1288
  except Exception as exc: # noqa: BLE001 - never break the run
@@ -13,6 +13,12 @@ and it was paid for when it was first saved. It still counts as accepted, in
13
13
  the push result and in ``get_charged_event_count``, so Actors that compare
14
14
  what they pushed with what was charged do not read it as a refused charge.
15
15
 
16
+ When the Actor names no key and its saved rows carry no ``id``, the SDK uses
17
+ the fields of the saved rows whose name ends in ``Id`` or ``_id`` (``reviewId``,
18
+ ``place_id``) and that hold a different value in every saved row, together as
19
+ one key. Rows of a Google Maps review search carry ``reviewId``, not ``id``: a
20
+ resurrected run of it collected and charged again 3,720 reviews it had saved.
21
+
16
22
  The key must identify a row. When the saved rows repeat a key, or this run
17
23
  pushes one key twice, it does not, and the run goes on as before: every row is
18
24
  stored and charged. Nothing is skipped in a first run, in a run that saved
@@ -31,6 +37,7 @@ from __future__ import annotations
31
37
  import asyncio
32
38
  import logging
33
39
  import os
40
+ import re
34
41
  from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union
35
42
 
36
43
  logger = logging.getLogger('scrapely.charging')
@@ -44,6 +51,11 @@ _PAGE = 5_000
44
51
 
45
52
  _OFF_VALUES = {'0', 'off', 'false', 'no'}
46
53
 
54
+ # Saved rows read in full to find a key when the Actor named none and the rows
55
+ # carry no ``id``.
56
+ AUTO_KEY_SAMPLE = 1_000
57
+ _ID_FIELD = re.compile(r'(?:[a-z0-9](?:Id|ID)|_id)$')
58
+
47
59
  KeyValue = Tuple[Any, ...]
48
60
 
49
61
 
@@ -84,11 +96,30 @@ def row_key(row: Any, fields: Tuple[str, ...]) -> Optional[KeyValue]:
84
96
  return tuple(parts)
85
97
 
86
98
 
99
+ def detect_result_key(rows: Sequence[Any]) -> Optional[Tuple[str, ...]]:
100
+ """The id fields (``...Id`` / ``..._id``) with a usable, different value in every row, or None."""
101
+ rows = [r for r in rows if isinstance(r, dict)]
102
+ if len(rows) < 2:
103
+ return None
104
+ names = sorted({n for r in rows for n in r if isinstance(n, str) and _ID_FIELD.search(n)})
105
+ chosen = []
106
+ for name in names:
107
+ values = [_scalar(r.get(name)) for r in rows]
108
+ if any(v is None for v in values):
109
+ continue
110
+ if len({str(v) for v in values}) != len(values):
111
+ continue
112
+ chosen.append(name)
113
+ return tuple(chosen) or None
114
+
115
+
87
116
  class ResumeDedupe:
88
117
  """Per-process state: which saved rows a resumed run may skip."""
89
118
 
90
119
  def __init__(self) -> None:
91
120
  self._fields: Optional[Tuple[str, ...]] = DEFAULT_RESULT_KEY
121
+ # True once the Actor named its key (set_result_key): no key is guessed then.
122
+ self._explicit = False
92
123
  self._state = 'unknown' # unknown | on | off
93
124
  self._saved: Set[KeyValue] = set()
94
125
  self._seen: Set[KeyValue] = set()
@@ -106,6 +137,7 @@ class ResumeDedupe:
106
137
  # Actor API
107
138
  def set_result_key(self, key: Union[str, Sequence[str], None]) -> None:
108
139
  fields = _normalize_key(key)
140
+ self._explicit = True
109
141
  if fields != self._fields:
110
142
  self._fields = fields
111
143
  # Keys read for the old fields are not valid for the new ones.
@@ -195,28 +227,29 @@ class ResumeDedupe:
195
227
  MAX_SAVED_ROWS,
196
228
  )
197
229
  return
198
- saved: Set[KeyValue] = set()
199
- keyed = 0
200
- offset = 0
201
- fields_param = ','.join(self._fields)
202
- while offset < item_count:
230
+ keys = await self._read_keys(client, dataset_id, item_count, self._fields)
231
+ if keys is None:
232
+ return
233
+ saved, keyed = keys
234
+ if keyed == 0 and not self._explicit:
235
+ # No saved row has an ``id``: use the saved rows' own id fields.
203
236
  page = await client.get_json(
204
- f'/v2/datasets/{dataset_id}/items',
205
- params={'fields': fields_param, 'offset': offset, 'limit': _PAGE},
237
+ f'/v2/datasets/{dataset_id}/items', params={'offset': 0, 'limit': AUTO_KEY_SAMPLE}
238
+ )
239
+ sample = page if isinstance(page, list) else (page or {}).get('items') or []
240
+ fields = detect_result_key(sample)
241
+ if fields is None:
242
+ return
243
+ keys = await self._read_keys(client, dataset_id, item_count, fields)
244
+ # A found key must be in every saved row.
245
+ if keys is None or keys[1] != item_count:
246
+ return
247
+ saved, keyed = keys
248
+ self._fields = fields
249
+ logger.info(
250
+ 'This run was resumed: its saved results are told apart by %s',
251
+ ' + '.join(repr(f) for f in fields),
206
252
  )
207
- rows = page if isinstance(page, list) else (page or {}).get('items') or []
208
- if not rows:
209
- break
210
- for row in rows:
211
- key = row_key(row, self._fields)
212
- if key is None:
213
- continue
214
- keyed += 1
215
- if key in saved:
216
- logger.debug('Saved rows repeat their result key; resumed-run dedupe is off')
217
- return
218
- saved.add(key)
219
- offset += len(rows)
220
253
  if keyed < 2:
221
254
  return
222
255
  except Exception as err: # never fail a push over this
@@ -226,6 +259,35 @@ class ResumeDedupe:
226
259
  self._seen = set()
227
260
  self._state = 'on'
228
261
 
262
+ @staticmethod
263
+ async def _read_keys(
264
+ client: Any, dataset_id: str, item_count: int, fields: Tuple[str, ...]
265
+ ) -> Optional[Tuple[Set[KeyValue], int]]:
266
+ """Keys of the saved rows and how many rows had one; None when a key repeats."""
267
+ saved: Set[KeyValue] = set()
268
+ keyed = 0
269
+ offset = 0
270
+ fields_param = ','.join(fields)
271
+ while offset < item_count:
272
+ page = await client.get_json(
273
+ f'/v2/datasets/{dataset_id}/items',
274
+ params={'fields': fields_param, 'offset': offset, 'limit': _PAGE},
275
+ )
276
+ rows = page if isinstance(page, list) else (page or {}).get('items') or []
277
+ if not rows:
278
+ break
279
+ for row in rows:
280
+ key = row_key(row, fields)
281
+ if key is None:
282
+ continue
283
+ keyed += 1
284
+ if key in saved:
285
+ logger.debug('Saved rows repeat their result key; resumed-run dedupe is off')
286
+ return None
287
+ saved.add(key)
288
+ offset += len(rows)
289
+ return saved, keyed
290
+
229
291
  async def ensure(self, manager: Any) -> bool:
230
292
  """True when this push needs the resumed-run path (saved rows to skip, or a declared limit)."""
231
293
  if self._state == 'unknown':
@@ -51,6 +51,7 @@ from __future__ import annotations
51
51
  import asyncio
52
52
  import inspect
53
53
  import json
54
+ import logging
54
55
  import os
55
56
  import random
56
57
  import re
@@ -100,6 +101,8 @@ _SOLVE_ID_HEADER = "x-scrapely-solve-id"
100
101
  _STATUS_TTL_SECS = 15.0
101
102
  _MAX_BODY = 4 * 1024 * 1024
102
103
 
104
+ logger = logging.getLogger(__name__)
105
+
103
106
 
104
107
  # ─── environment ─────────────────────────────────────────────────────────────
105
108
 
@@ -619,6 +622,11 @@ _STREAM_LIBS = ("requests", "curl_cffi")
619
622
 
620
623
 
621
624
  def _session_lib(session: Any) -> str:
625
+ # Over the MRO, so subclasses (cloudscraper's requests.Session) stream too.
626
+ for cls in type(session).__mro__:
627
+ lib = cls.__module__.split(".")[0]
628
+ if lib == "httpx" or lib in _STREAM_LIBS:
629
+ return lib
622
630
  return type(session).__module__.split(".")[0]
623
631
 
624
632
 
@@ -626,6 +634,19 @@ def _capped_text(buf: bytearray, encoding: str | None) -> str:
626
634
  return bytes(buf[: _MAX_BODY + 1]).decode(encoding or "utf-8", errors="replace")
627
635
 
628
636
 
637
+ def _capped_status_body(r: Any) -> tuple[int, str]:
638
+ """_status_body of a response the session read whole, cut to _MAX_BODY + 1 characters."""
639
+ status, text = _status_body(r)
640
+ if len(text) > _MAX_BODY:
641
+ logger.warning(
642
+ "solver step answer is over %d bytes and was cut; this session type is read whole, "
643
+ "pass fetch= / afetch= to stream it",
644
+ _MAX_BODY,
645
+ )
646
+ text = text[: _MAX_BODY + 1]
647
+ return status, text
648
+
649
+
629
650
  def _send_sync(session: Any, req: dict, timeout: float) -> tuple[int, str]:
630
651
  body = req.get("body")
631
652
  kwargs: dict[str, Any] = {"headers": req.get("headers") or {}, "timeout": timeout}
@@ -653,7 +674,18 @@ def _send_sync(session: Any, req: dict, timeout: float) -> tuple[int, str]:
653
674
  finally:
654
675
  r.close()
655
676
  r = session.request(req["method"], req["url"], **kwargs)
656
- return _status_body(r)
677
+ iter_content = getattr(r, "iter_content", None)
678
+ raw = getattr(r, "raw", None)
679
+ if callable(iter_content):
680
+ buf = bytearray()
681
+ for chunk in iter_content(65536):
682
+ buf += chunk
683
+ if len(buf) > _MAX_BODY:
684
+ break
685
+ return int(r.status_code), _capped_text(buf, getattr(r, "encoding", None))
686
+ if callable(getattr(raw, "read", None)):
687
+ return int(r.status_code), _capped_text(bytearray(raw.read(_MAX_BODY + 1)), getattr(r, "encoding", None))
688
+ return _capped_status_body(r)
657
689
 
658
690
 
659
691
  async def _send_async(session: Any, req: dict, timeout: float) -> tuple[int, str]:
@@ -682,7 +714,18 @@ async def _send_async(session: Any, req: dict, timeout: float) -> tuple[int, str
682
714
  finally:
683
715
  await r.aclose()
684
716
  r = await session.request(req["method"], req["url"], **kwargs)
685
- return _status_body(r)
717
+ if lib == "aiohttp":
718
+ try:
719
+ buf = bytearray()
720
+ while len(buf) <= _MAX_BODY:
721
+ chunk = await r.content.read(_MAX_BODY + 1 - len(buf))
722
+ if not chunk:
723
+ break
724
+ buf += chunk
725
+ return int(r.status), _capped_text(buf, r.charset)
726
+ finally:
727
+ r.release()
728
+ return _capped_status_body(r)
686
729
 
687
730
 
688
731
  class Solver:
@@ -5,6 +5,7 @@ Base API client for Scrapely storage operations.
5
5
  from __future__ import annotations
6
6
 
7
7
  import asyncio
8
+ import contextvars
8
9
  import json
9
10
  import logging
10
11
  import os
@@ -13,6 +14,7 @@ import time
13
14
  from typing import Any, Dict, Optional, Union
14
15
 
15
16
  import httpx
17
+ from urllib.parse import urlparse
16
18
 
17
19
  logger = logging.getLogger(__name__)
18
20
 
@@ -33,10 +35,19 @@ class ApiClientError(Exception):
33
35
  IDEMPOTENT_METHODS = frozenset({'GET', 'HEAD', 'DELETE', 'OPTIONS'})
34
36
  # HAProxy's own 503 page: no backend was available, so nothing was forwarded.
35
37
  NO_BACKEND_MARKER = 'No server is available to handle this request'
38
+ # Error types of a 503 that the API sends before it applies anything, so any
39
+ # method may be sent again: the rate limiter refused the request (before the
40
+ # handler), another request held the storage name (nothing changed), or the
41
+ # account's schema-validation slots were all in use (the push or record is
42
+ # refused before its Idempotency-Key is read or anything is stored).
43
+ NOT_APPLIED_503_TYPES = frozenset({'rate-limit-unavailable', 'storage-name-busy', 'schema-validation-busy'})
36
44
 
37
45
 
38
46
  def is_retryable_response(
39
- status: int, idempotent: bool, error_type: Optional[str] = None, body_text: Optional[str] = None
47
+ status: int,
48
+ idempotent: bool,
49
+ error_type: Optional[str] = None,
50
+ body_text: Optional[str] = None,
40
51
  ) -> bool:
41
52
  """Whether a non-2xx answer is retried.
42
53
 
@@ -45,8 +56,10 @@ def is_retryable_response(
45
56
  (dataset push, KV PUT, named storage create) only on a 503 that certainly
46
57
  was not processed: the rate limiter refused it ("rate-limit-unavailable",
47
58
  before the handler), another request held the storage name
48
- ("storage-name-busy", nothing changed), or HAProxy had no backend (its own
49
- page, nothing forwarded). Any other 503 may mean "outcome unknown" (a
59
+ ("storage-name-busy", nothing changed), the account's schema-validation
60
+ slots were all in use ("schema-validation-busy", refused before anything
61
+ is stored), or HAProxy had no backend (its own page, nothing forwarded).
62
+ Any other 503 may mean "outcome unknown" (a
50
63
  direct dataset write whose commit was not confirmed), and re-sending could
51
64
  store the items twice.
52
65
  """
@@ -56,7 +69,7 @@ def is_retryable_response(
56
69
  return status in (500, 502, 503, 504)
57
70
  if status != 503:
58
71
  return False
59
- return error_type in ('rate-limit-unavailable', 'storage-name-busy') or NO_BACKEND_MARKER in (body_text or '')
72
+ return error_type in NOT_APPLIED_503_TYPES or NO_BACKEND_MARKER in (body_text or '')
60
73
 
61
74
 
62
75
  def unwrap_data(value: Any) -> Any:
@@ -85,10 +98,9 @@ _MAX_BACKOFF_SECS = 30.0
85
98
 
86
99
  # Response header the API sets on every dataset push that sent an
87
100
  # Idempotency-Key, once it de-duplicates such pushes. An older API ignores the
88
- # key, and re-sending a push there could store the rows twice, so ambiguous
89
- # failures of keyed writes are retried only while the latest keyed answer from
90
- # that API origin carried this header. A 2xx without it (an older instance,
91
- # e.g. mid-deploy or after a rollback) switches the retries off again.
101
+ # key, and re-sending a push there could store the rows twice, so a 2xx without
102
+ # it (an older instance, e.g. mid-deploy) switches the retries of ambiguous
103
+ # keyed-write failures off for that API origin (api_dedupes_keyed_writes).
92
104
  IDEMPOTENCY_SUPPORT_HEADER = 'X-Scrapely-Idempotency'
93
105
  _KEY_IN_PROGRESS = 'idempotency-key-in-progress'
94
106
  _OUTCOME_UNKNOWN = 'push-outcome-unknown'
@@ -118,16 +130,19 @@ def _origin_of(url: str) -> str:
118
130
  def api_dedupes_keyed_writes(url: Optional[str] = None) -> bool:
119
131
  """Whether the API at ``url`` (default: the last one seen) de-duplicates keyed writes.
120
132
 
121
- Record PUTs count as de-duplicated until a keyed record PUT was stored
122
- without the support header: re-applying the same body to the same record
123
- leaves the same record, so the worst case on an API that ignores the key
124
- is one extra counted write, while not re-sending fails the run.
133
+ Record PUTs and dataset pushes count as de-duplicated until a keyed write of
134
+ that kind was stored without the support header. Record PUTs: re-applying
135
+ the same body to the same record leaves the same record. Dataset pushes:
136
+ the API has de-duplicated keyed pushes since 2026-10, and a push whose answer
137
+ was lost and is NOT re-sent with its key comes back to the actor as an error,
138
+ whose own retry then sends the rows again under a new key, which stored them
139
+ twice (prod 2026-12-02, Cloudflare reroute: duplicate rows, double charges).
125
140
  """
126
141
  if _keyed_writes_override is not None:
127
142
  return _keyed_writes_override
128
143
  if url is not None:
129
144
  learned = _keyed_writes_deduped.get(_origin_of(url))
130
- if learned is None and is_kv_record_url(url):
145
+ if learned is None and _reports_key_dedupe(url):
131
146
  return True
132
147
  return learned is True
133
148
  return bool(_keyed_writes_deduped) and list(_keyed_writes_deduped.values())[-1] is True
@@ -140,8 +155,18 @@ def _reset_keyed_write_support(value: Optional[bool] = None) -> None:
140
155
  _keyed_writes_override = True if value is True else None
141
156
 
142
157
 
158
+ def _reports_key_dedupe(url: str) -> bool:
159
+ """Whether ``url`` is a route that answers keyed writes with the support header (dataset pushes, KV records)."""
160
+ path = urlparse(url).path.rstrip('/')
161
+ return is_kv_record_url(url) or ('/datasets/' in path and path.endswith('/items'))
162
+
163
+
143
164
  def _note_keyed_answer(url: str, response: httpx.Response) -> None:
144
165
  global _keyed_writes_override
166
+ # Only routes that report de-duplication teach anything: other keyed writes (run starts) never
167
+ # send the header, and learning "no" from them switched off resends of later dataset pushes.
168
+ if not _reports_key_dedupe(url):
169
+ return
145
170
  origin = _origin_of(url)
146
171
  if IDEMPOTENCY_SUPPORT_HEADER in response.headers:
147
172
  _keyed_writes_deduped.pop(origin, None)
@@ -162,6 +187,127 @@ def _mark_outcome_unknown(exc: BaseException) -> BaseException:
162
187
  return exc
163
188
 
164
189
 
190
+ # Actor shutdown (SIGTERM/SIGINT). A push that was already charged
191
+ # (push_data_and_charge marks it with ``_shutdown_interruptible``) must not keep
192
+ # retrying into the hard exit: its charge would stand for rows that were never
193
+ # stored. Once shutdown is signalled it stops retrying, and an attempt still in
194
+ # flight after SHUTDOWN_PUSH_GRACE_SECS is given up, so the push fails and its
195
+ # charge is voided while the platform still accepts the void (a forced run end
196
+ # settles the run only after its container stopped).
197
+ SHUTDOWN_PUSH_GRACE_SECS = 2.0
198
+ _shutdown_interruptible: contextvars.ContextVar[bool] = contextvars.ContextVar(
199
+ 'scrapely_shutdown_interruptible', default=False
200
+ )
201
+ _shutdown_state: Dict[str, Any] = {'signalled': False, 'event': None, 'loop': None}
202
+
203
+
204
+ class ShutdownInterruptedError(Exception):
205
+ """A charged push given up because the Actor is shutting down."""
206
+
207
+
208
+ def signal_shutdown() -> None:
209
+ """The Actor got a stop signal: charged pushes stop retrying (call in the event loop)."""
210
+ _shutdown_state['signalled'] = True
211
+ event = _shutdown_state['event']
212
+ if event is not None:
213
+ event.set()
214
+
215
+
216
+ def reset_shutdown() -> None:
217
+ """A new Actor lifecycle: no shutdown pending."""
218
+ _shutdown_state['signalled'] = False
219
+ _shutdown_state['event'] = None
220
+ _shutdown_state['loop'] = None
221
+
222
+
223
+ def shutdown_signalled() -> bool:
224
+ return bool(_shutdown_state['signalled'])
225
+
226
+
227
+ def _shutdown_event() -> asyncio.Event:
228
+ """The shutdown event of the running loop (an Event belongs to one loop)."""
229
+ loop = asyncio.get_running_loop()
230
+ event = _shutdown_state['event']
231
+ if event is None or _shutdown_state['loop'] is not loop:
232
+ event = asyncio.Event()
233
+ if _shutdown_state['signalled']:
234
+ event.set()
235
+ _shutdown_state['event'] = event
236
+ _shutdown_state['loop'] = loop
237
+ return event
238
+
239
+
240
+ async def _sleep_unless_shutdown(secs: float) -> bool:
241
+ """Sleep ``secs``; False (at once) when shutdown is or gets signalled."""
242
+ if shutdown_signalled():
243
+ return False
244
+ sleeper = asyncio.ensure_future(asyncio.sleep(secs))
245
+ waiter = asyncio.ensure_future(_shutdown_event().wait())
246
+ try:
247
+ await asyncio.wait({sleeper, waiter}, return_when=asyncio.FIRST_COMPLETED)
248
+ finally:
249
+ sleeper.cancel()
250
+ waiter.cancel()
251
+ return not shutdown_signalled()
252
+
253
+
254
+ async def _until_shutdown_grace(coro: Any) -> Any:
255
+ """Await ``coro``; give it up SHUTDOWN_PUSH_GRACE_SECS after shutdown is signalled."""
256
+ task = asyncio.ensure_future(coro)
257
+
258
+ async def shutdown_then_grace() -> None:
259
+ await _shutdown_event().wait()
260
+ await asyncio.sleep(SHUTDOWN_PUSH_GRACE_SECS)
261
+
262
+ stopper = asyncio.ensure_future(shutdown_then_grace())
263
+ try:
264
+ done, _ = await asyncio.wait({task, stopper}, return_when=asyncio.FIRST_COMPLETED)
265
+ except BaseException:
266
+ task.cancel()
267
+ stopper.cancel()
268
+ raise
269
+ if task in done:
270
+ stopper.cancel()
271
+ return task.result()
272
+ task.cancel()
273
+ try:
274
+ await task
275
+ except BaseException:
276
+ pass
277
+ # The request may have reached the API: its outcome is unknown.
278
+ raise _mark_outcome_unknown(ShutdownInterruptedError(
279
+ 'Push given up: the Actor is shutting down (its charge is voided)'
280
+ ))
281
+
282
+
283
+ DEFAULT_API_TIMEOUT_SECS = 30.0
284
+ # Per-attempt timeouts (used when the client keeps the default timeout). While
285
+ # Cloudflare served our traffic from distant colos (2026-12-02, 5-15 min each
286
+ # hour) single API calls took 1-40 s, independently of each other: a call stuck
287
+ # for 30 s was often answered at once when sent again. So connecting gets 10 s
288
+ # (a connect failure is re-sent for any method: nothing was sent yet), and a
289
+ # call that is safe to re-send gets a short first wait that grows with each
290
+ # attempt, so a normal slow call still completes. A call that must not be
291
+ # re-sent gets one long wait instead: its timeout is final.
292
+ CONNECT_TIMEOUT_SECS = 10.0
293
+ RESENDABLE_READ_TIMEOUTS_SECS = (20.0, 30.0, 45.0, 60.0)
294
+ FINAL_READ_TIMEOUT_SECS = 60.0
295
+
296
+
297
+ def attempt_timeout(attempt: int, resendable: bool, base: float = DEFAULT_API_TIMEOUT_SECS) -> httpx.Timeout:
298
+ """httpx timeout for attempt number ``attempt`` (0-based) of one API call.
299
+
300
+ A client created with a non-default ``timeout`` keeps it for every phase and attempt.
301
+ """
302
+ if base != DEFAULT_API_TIMEOUT_SECS:
303
+ return httpx.Timeout(base)
304
+ if resendable:
305
+ read = RESENDABLE_READ_TIMEOUTS_SECS[min(attempt, len(RESENDABLE_READ_TIMEOUTS_SECS) - 1)]
306
+ else:
307
+ read = FINAL_READ_TIMEOUT_SECS
308
+ return httpx.Timeout(connect=CONNECT_TIMEOUT_SECS, read=read, write=read, pool=read)
309
+
310
+
165
311
  def api_retry_window_secs() -> float:
166
312
  """How long one API call keeps retrying before it gives up.
167
313
 
@@ -288,7 +434,7 @@ class ApiClient:
288
434
  api_url: str,
289
435
  token: str,
290
436
  run_id: str,
291
- timeout: float = 30.0,
437
+ timeout: float = DEFAULT_API_TIMEOUT_SECS,
292
438
  transport: Optional[httpx.AsyncBaseTransport] = None,
293
439
  ):
294
440
  self.api_url = api_url.rstrip('/')
@@ -375,6 +521,8 @@ class ApiClient:
375
521
 
376
522
  - 429 (run API rate limit, dataset backpressure): always; nothing was applied.
377
523
  - 503 from the limiter or HAProxy: always; nothing was forwarded.
524
+ - 503 ``storage-name-busy`` / ``schema-validation-busy``: always; the API
525
+ refused the request before applying anything.
378
526
  - 500/502/503/504, read/write timeouts and dropped connections:
379
527
  idempotent calls, and writes with an ``idempotency_key`` once the API
380
528
  is known to de-duplicate them (a re-send returns the original answer).
@@ -424,6 +572,8 @@ class ApiClient:
424
572
  if retry_deadline is not None:
425
573
  deadline = min(deadline, retry_deadline)
426
574
  attempt = 0
575
+ # A charged push: no retries once the Actor is shutting down (see SHUTDOWN_PUSH_GRACE_SECS).
576
+ interruptible = _shutdown_interruptible.get()
427
577
 
428
578
  async def backoff(why: str, retry_after: Optional[str]) -> bool:
429
579
  """Sleep before the next attempt; False once the retry window is used up."""
@@ -433,19 +583,34 @@ class ApiClient:
433
583
  wait = server_retry_delay(attempt, retry_after)
434
584
  if time.monotonic() + wait > deadline:
435
585
  return False
586
+ if interruptible and shutdown_signalled():
587
+ logger.warning('%s %s %s; not retried: the Actor is shutting down', method, path, why)
588
+ return False
436
589
  attempt += 1
437
590
  logger.warning('%s %s %s; retry %d in %.1fs', method, path, why, attempt, wait)
591
+ if interruptible:
592
+ if not await _sleep_unless_shutdown(wait):
593
+ logger.warning('%s %s: retry dropped, the Actor is shutting down', method, path)
594
+ return False
595
+ return True
438
596
  await asyncio.sleep(wait)
439
597
  return True
440
598
 
441
599
  while True:
442
600
  await self._rate_limiter.wait_for_slot()
443
- request_kwargs: Dict[str, Any] = {}
601
+ timeout = attempt_timeout(attempt, safe_to_resend(), self.timeout)
444
602
  if retry_deadline is not None:
445
603
  # A caller with a time budget: no attempt may outlive it.
446
- request_kwargs['timeout'] = max(0.5, min(self.timeout, retry_deadline - time.monotonic()))
604
+ left = max(0.5, retry_deadline - time.monotonic())
605
+ timeout = httpx.Timeout(
606
+ connect=min(timeout.connect or left, left),
607
+ read=min(timeout.read or left, left),
608
+ write=min(timeout.write or left, left),
609
+ pool=min(timeout.pool or left, left),
610
+ )
611
+ request_kwargs: Dict[str, Any] = {'timeout': timeout}
447
612
  try:
448
- response = await client.request(
613
+ send = client.request(
449
614
  method,
450
615
  url,
451
616
  params=params,
@@ -453,6 +618,7 @@ class ApiClient:
453
618
  headers=request_headers or None,
454
619
  **request_kwargs,
455
620
  )
621
+ response = await (_until_shutdown_grace(send) if interruptible else send)
456
622
  except (httpx.ConnectTimeout, httpx.PoolTimeout, httpx.ConnectError) as exc:
457
623
  # Never reached the API: safe for every method.
458
624
  if isinstance(exc, (httpx.ConnectTimeout, httpx.PoolTimeout)) and do_not_retry_timeouts:
@@ -525,10 +525,14 @@ class ApiStorageClient:
525
525
  client_key: str,
526
526
  forefront: bool = False,
527
527
  ) -> ProcessedRequest:
528
+ # Safe to re-send after a lost answer: the API stores a request once per
529
+ # id (derived from its uniqueKey, the same on every attempt) and answers a
530
+ # repeat with wasAlreadyPresent, atomically (routes/req-queues.ts ADD_REQUEST_LUA).
528
531
  data = await self.api_client.post_json(
529
532
  f'/v2/request-queues/{queue_id}/requests',
530
533
  request.to_dict(),
531
534
  params=build_rq_params(client_key, forefront=forefront),
535
+ idempotent=True,
532
536
  )
533
537
  return ProcessedRequest(
534
538
  id=str(data.get('requestId') or ''),
@@ -551,10 +555,12 @@ class ApiStorageClient:
551
555
  for i in range(0, len(requests), RQ_BATCH_SIZE):
552
556
  chunk = list(requests[i:i + RQ_BATCH_SIZE])
553
557
  try:
558
+ # Re-sendable like a single add: each request is stored once per id.
554
559
  data = await self.api_client.post_json(
555
560
  f'/v2/request-queues/{queue_id}/requests/batch',
556
561
  [req.to_dict() for req in chunk],
557
562
  params=build_rq_params(client_key, forefront=forefront),
563
+ idempotent=True,
558
564
  )
559
565
  except Exception:
560
566
  logger.exception(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.51
3
+ Version: 0.1.56
4
4
  Summary: Scrapely Python SDK - A toolkit for building Actors on the Scrapely platform
5
5
  Author-email: Scrapely <hello@scrape.ly>
6
6
  License-Expression: MIT AND Apache-2.0
@@ -26,7 +26,7 @@ License-File: NOTICE
26
26
  Requires-Dist: httpx>=0.25.0
27
27
  Requires-Dist: crawlee<2.0.0,>=1.8.0
28
28
  Requires-Dist: websockets>=12.0
29
- Requires-Dist: scrapely-client-python<2,>=1.0.2
29
+ Requires-Dist: scrapely-client-python<2,>=1.0.13
30
30
  Requires-Dist: pydantic>=2.0.0
31
31
  Requires-Dist: cryptography>=42.0.0
32
32
  Requires-Dist: wreq<0.14,>=0.13; python_version >= "3.11"
@@ -1,7 +1,7 @@
1
1
  httpx>=0.25.0
2
2
  crawlee<2.0.0,>=1.8.0
3
3
  websockets>=12.0
4
- scrapely-client-python<2,>=1.0.2
4
+ scrapely-client-python<2,>=1.0.13
5
5
  pydantic>=2.0.0
6
6
  cryptography>=42.0.0
7
7