scrapely-python 0.1.46__tar.gz → 0.1.48__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.46 → scrapely_python-0.1.48}/CHANGELOG.md +10 -0
  2. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/PKG-INFO +1 -1
  3. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/pyproject.toml +1 -1
  4. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/__init__.py +1 -1
  5. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/actor.py +29 -0
  6. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/charging.py +117 -18
  7. scrapely_python-0.1.48/src/scrapely/resume_dedupe.py +304 -0
  8. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely_python.egg-info/PKG-INFO +1 -1
  9. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely_python.egg-info/SOURCES.txt +1 -0
  10. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/LICENSE +0 -0
  11. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/LICENSE-APACHE +0 -0
  12. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/MANIFEST.in +0 -0
  13. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/NOTICE +0 -0
  14. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/README.md +0 -0
  15. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/setup.cfg +0 -0
  16. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/_browser_locations.py +0 -0
  17. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/browser_configuration.py +0 -0
  18. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/cdp_retry.py +0 -0
  19. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/charging_client.py +0 -0
  20. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/configuration.py +0 -0
  21. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/crypto/__init__.py +0 -0
  22. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/crypto/_secrets.py +0 -0
  23. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/errors.py +0 -0
  24. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/events/__init__.py +0 -0
  25. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/events/_types.py +0 -0
  26. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/events/event_manager.py +0 -0
  27. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/__init__.py +0 -0
  28. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_capture.py +0 -0
  29. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_client.py +0 -0
  30. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_compat.py +0 -0
  31. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_detect.py +0 -0
  32. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_headers.py +0 -0
  33. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_options.py +0 -0
  34. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_policy.py +0 -0
  35. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_profiles.py +0 -0
  36. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_response.py +0 -0
  37. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_stats.py +0 -0
  38. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/_transport.py +0 -0
  39. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/http/profiles.json +0 -0
  40. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/log.py +0 -0
  41. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/patch_browser_pool.py +0 -0
  42. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/pricing_types.py +0 -0
  43. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/proxy_configuration.py +0 -0
  44. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/py.typed +0 -0
  45. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/request_loaders/__init__.py +0 -0
  46. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/request_loaders/_scrapely_request_list.py +0 -0
  47. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/__init__.py +0 -0
  48. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/_actor_runner.py +0 -0
  49. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/_async_thread.py +0 -0
  50. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/_logging_config.py +0 -0
  51. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/_serialization.py +0 -0
  52. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/_warnings.py +0 -0
  53. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/extensions/__init__.py +0 -0
  54. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/extensions/_graceful_stop.py +0 -0
  55. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/extensions/_httpcache.py +0 -0
  56. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/middlewares/__init__.py +0 -0
  57. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/middlewares/apify_proxy.py +0 -0
  58. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/pipelines/__init__.py +0 -0
  59. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/pipelines/actor_dataset_push.py +0 -0
  60. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/requests.py +0 -0
  61. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/scheduler.py +0 -0
  62. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/scrapy/utils.py +0 -0
  63. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/solver.py +0 -0
  64. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/__init__.py +0 -0
  65. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/_file_system/__init__.py +0 -0
  66. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/_file_system/_key_value_store_client.py +0 -0
  67. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/_file_system/_storage_client.py +0 -0
  68. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/_metadata.py +0 -0
  69. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/api_client.py +0 -0
  70. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/client.py +0 -0
  71. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/patch_storage.py +0 -0
  72. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/scrapely_dataset_client.py +0 -0
  73. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/scrapely_kvs_client.py +0 -0
  74. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/scrapely_rq_client.py +0 -0
  75. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/scrapely_storage_client.py +0 -0
  76. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/smart_scrapely_storage_client.py +0 -0
  77. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/types.py +0 -0
  78. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage/utils.py +0 -0
  79. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storage_clients/__init__.py +0 -0
  80. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/storages/__init__.py +0 -0
  81. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/types.py +0 -0
  82. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely/webhook.py +0 -0
  83. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely_python.egg-info/dependency_links.txt +0 -0
  84. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely_python.egg-info/requires.txt +0 -0
  85. {scrapely_python-0.1.46 → scrapely_python-0.1.48}/src/scrapely_python.egg-info/top_level.txt +0 -0
@@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.48] - 2026-11-10
8
+
9
+ - **A resurrected or rebooted run stops at the Actor's own result limit.** A resumed run starts the Actor's code again, and with it the Actor's own result count, so an Actor whose source returns results in a different order each run (search pages, feeds) could end with more results than its limit: with `maxResults` 60, 24 rows saved before the abort plus the resumed run's own 60 (some of them saved before and skipped) gave 67. `Actor.set_result_limit(n)` declares the Actor's run-level result limit, e.g. its `maxItems` input. In a resumed run the rows saved before count towards it: once they and the new rows reach `n`, further charged rows are refused like at the spending limit (not saved, not charged, the push reports the limit), so the run ends with `n` results. Declare only a limit that counts all results of the run, not one per search. Nothing changes in a first run or for Actors that do not declare a limit.
10
+
11
+ ## [0.1.47] - 2026-11-10
12
+
13
+ - **A resurrected or rebooted run no longer charges again for results it had already saved.** Such a run keeps its default dataset, but the Actor's code starts from the beginning, and an Actor without its own progress state collects the results it saved before once more. On the first charged push to the default dataset of such a run, the SDK reads the result key of the rows already saved (one read of the dataset's `id` values; `id` by default). A charged row whose key is one of them is not saved and not charged again: the dataset already holds it and it was paid for when it was first saved. It counts as accepted in the push result (`charged_count`) and in `get_charged_event_count()`, so Actors that compare pushed and charged counts do not stop. The run's spending limit is not used by these rows.
14
+ - `Actor.set_result_key('id' | ['id', 'checkIn'] | None)` names the field(s) that identify one result row; `None` turns this off. `SCRAPELY_RESUME_DEDUPE=off` turns it off for a run.
15
+ - Nothing changes when the key does not identify a row: if the saved rows repeat a key, or the resumed run pushes one key twice (for example the same result from two different searches), every row is saved and charged as before. Nothing changes in a first run, a run that saved nothing yet, after a metamorph, for rows without the key, for named datasets or for pushes that are not charged per row. A first run reads only the dataset's item count once.
16
+
7
17
  ## [0.1.46] - 2026-11-10
8
18
 
9
19
  - `scrapely.solver.AkamaiSensor.report(session, verified)`: after `solve_sbsd()` or `solve_pixel()`, re-fetch the page and report whether the site let the session through (`True`) or still showed its bot check (`False`). The platform stores it on that solve, the same way `Solver.report()` does for step solves, so a site that starts refusing these answers shows up in solver health and in the refusal alerts. Best effort: it never raises, and a second report for the same answer is ignored. Needs a platform that sends `x-scrapely-solve-id` on compat answers; on an older one it does nothing.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.46
3
+ Version: 0.1.48
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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "scrapely-python"
7
- version = "0.1.46"
7
+ version = "0.1.48"
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"
@@ -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.46'
328
+ __version__ = '0.1.48'
329
329
  __all__ = [
330
330
  # Core
331
331
  'Actor',
@@ -1010,6 +1010,35 @@ class Actor(metaclass=_ActorMeta):
1010
1010
  target.push_data,
1011
1011
  )
1012
1012
 
1013
+ @classmethod
1014
+ def set_result_limit(cls, limit: Optional[int]) -> None:
1015
+ """Declare the Actor's run-level result limit (e.g. its ``maxItems`` input).
1016
+
1017
+ A resurrected or rebooted run starts the Actor's code again, and with it the
1018
+ Actor's own result count. With a declared limit, the rows the run saved before
1019
+ count towards it: once they and the new rows of the resumed run reach ``limit``,
1020
+ further charged rows are refused like at the spending limit (not saved, not
1021
+ charged, the push reports the limit). Only declare a limit that counts all
1022
+ results of the run, not one per search. ``None`` removes it.
1023
+ """
1024
+ from .resume_dedupe import get_resume_dedupe
1025
+
1026
+ get_resume_dedupe().set_result_limit(limit)
1027
+
1028
+ @classmethod
1029
+ def set_result_key(cls, key: Union[str, List[str], None]) -> None:
1030
+ """Name the field(s) that identify one result row (default ``'id'``).
1031
+
1032
+ When a run is resurrected or rebooted, the Actor's code starts again and
1033
+ often collects results it already saved. A charged push to the default
1034
+ dataset then skips rows whose key the run saved before: they are not
1035
+ saved or charged again, and count as accepted. Use a list for a key made
1036
+ of several fields (``['id', 'checkIn']``) and ``None`` to turn this off.
1037
+ """
1038
+ from .resume_dedupe import get_resume_dedupe
1039
+
1040
+ get_resume_dedupe().set_result_key(key)
1041
+
1013
1042
  @classmethod
1014
1043
  async def get_value(cls, key: str, default_value: Any = None) -> Any:
1015
1044
  cls._ensure_initialized('get_value')
@@ -489,6 +489,9 @@ class ChargingManager:
489
489
  # lock): charges that came back short are collected here instead of being
490
490
  # logged, because the atomic push gives them back (see _ShortCharge).
491
491
  self._short_charges: Optional[List['_ShortCharge']] = None
492
+ # Rows of a resumed run that the run had already saved (and paid for)
493
+ # before: not saved or charged again, but counted as accepted (event -> count).
494
+ self._covered_earlier: Dict[str, int] = {}
492
495
 
493
496
  def close(self) -> None:
494
497
  """Mark the manager closed; subsequent charge/push operations are rejected."""
@@ -1608,12 +1611,24 @@ class ChargingManager:
1608
1611
  Returns:
1609
1612
  Number of events charged
1610
1613
  """
1614
+ # Rows a resumed run had already saved count as charged: they were paid
1615
+ # for when they were first saved (see resume_dedupe).
1611
1616
  if is_default_dataset_item_event(event_name):
1612
1617
  return (
1613
1618
  self._charged_events.get(APIFY_DEFAULT_DATASET_ITEM_EVENT, 0)
1614
1619
  + self._charged_events.get(SCRAPELY_DEFAULT_DATASET_ITEM_EVENT, 0)
1620
+ + self._covered_earlier.get(APIFY_DEFAULT_DATASET_ITEM_EVENT, 0)
1621
+ + self._covered_earlier.get(SCRAPELY_DEFAULT_DATASET_ITEM_EVENT, 0)
1615
1622
  )
1616
- return self._charged_events.get(event_name, 0)
1623
+ return self._charged_events.get(event_name, 0) + self._covered_earlier.get(event_name, 0)
1624
+
1625
+ def _note_covered_earlier(self, event_names: List[str], count: int) -> None:
1626
+ """Rows skipped because the resumed run saved them before: count them as accepted."""
1627
+ if count <= 0:
1628
+ return
1629
+ for name in dict.fromkeys(event_names):
1630
+ if name:
1631
+ self._covered_earlier[name] = self._covered_earlier.get(name, 0) + count
1617
1632
 
1618
1633
  def get_max_total_charge_usd(self) -> Decimal:
1619
1634
  """Get the configured maximum total charge.
@@ -1878,14 +1893,88 @@ async def push_data_and_charge(
1878
1893
  fails, the earlier pieces stay stored and billed and the error is raised.
1879
1894
  """
1880
1895
  rows = items if isinstance(items, list) else [items]
1881
- groups = _push_groups(rows)
1882
- if groups is None:
1883
- return await _push_data_and_charge_one(charging_manager, rows, event_name, is_default_dataset, push_fn)
1884
- results = [
1885
- await _push_data_and_charge_one(charging_manager, group, event_name, is_default_dataset, push_fn)
1886
- for group in groups
1887
- ]
1888
- return _merge_group_results(results)
1896
+
1897
+ async def push(rows: List[Any]) -> ChargeResult:
1898
+ groups = _push_groups(rows)
1899
+ if groups is None:
1900
+ return await _push_data_and_charge_one(charging_manager, rows, event_name, is_default_dataset, push_fn)
1901
+ results = [
1902
+ await _push_data_and_charge_one(charging_manager, group, event_name, is_default_dataset, push_fn)
1903
+ for group in groups
1904
+ ]
1905
+ return _merge_group_results(results)
1906
+
1907
+ if not (is_default_dataset and rows and _paid_row_events(charging_manager, {event_name: 1} if event_name else {})):
1908
+ return await push(rows)
1909
+ return await _skip_saved_rows(
1910
+ charging_manager, rows, _paid_row_events(charging_manager, {event_name: 1} if event_name else {}), push
1911
+ )
1912
+
1913
+
1914
+ def _paid_row_events(charging_manager: ChargingManager, charges: Dict[str, int]) -> List[str]:
1915
+ """Events a default-dataset push charges per row (empty: the push is not charged per row)."""
1916
+ if charging_manager._pricing_info is None:
1917
+ return []
1918
+ names = [name for name in charges if name]
1919
+ default_event = charging_manager._config.get('default_dataset_item_event_name') or (
1920
+ resolve_default_dataset_item_event_name(charging_manager._per_event_prices)
1921
+ )
1922
+ if default_event:
1923
+ names.append(default_event)
1924
+ paid = [n for n in names if (charging_manager._calculate_event_price(n) or Decimal('0')) > 0]
1925
+ if not paid:
1926
+ return []
1927
+ return list(dict.fromkeys(names))
1928
+
1929
+
1930
+ async def _skip_saved_rows(
1931
+ charging_manager: ChargingManager,
1932
+ rows: List[Any],
1933
+ event_names: List[str],
1934
+ push: Any,
1935
+ ) -> ChargeResult:
1936
+ """A charged default-dataset push of a resumed run: rows the run saved before are skipped.
1937
+
1938
+ See resume_dedupe. A skipped row is neither stored nor charged; it counts as
1939
+ accepted in the result and in get_charged_event_count.
1940
+ """
1941
+ from .resume_dedupe import get_resume_dedupe
1942
+
1943
+ dedupe = get_resume_dedupe()
1944
+ if not await dedupe.ensure(charging_manager):
1945
+ return await push(rows)
1946
+ async with dedupe.lock:
1947
+ kept, skipped, pushed = dedupe.plan(rows)
1948
+ # The Actor's declared run-level limit counts the rows saved before.
1949
+ room = dedupe.remaining()
1950
+ capped = room is not None and len(kept) > room
1951
+ if capped:
1952
+ kept, pushed = kept[:room], pushed[:room]
1953
+ dedupe.note_capped()
1954
+ if not skipped and not capped:
1955
+ result = await push(kept)
1956
+ stored = max(0, result.charged_count)
1957
+ dedupe.commit([], pushed[:stored])
1958
+ dedupe.note_new_rows(stored)
1959
+ return result
1960
+ if kept:
1961
+ result = await push(kept)
1962
+ else:
1963
+ result = ChargeResult(
1964
+ chargeable_within_limit=charging_manager.compute_chargeable(),
1965
+ charged_count=0,
1966
+ event_charge_limit_reached=charging_manager.is_charge_limit_reached(),
1967
+ )
1968
+ stored = max(0, result.charged_count)
1969
+ n = dedupe.commit(skipped, pushed[:stored])
1970
+ dedupe.note_new_rows(stored)
1971
+ charging_manager._note_covered_earlier(event_names, n)
1972
+ return ChargeResult(
1973
+ chargeable_within_limit=result.chargeable_within_limit,
1974
+ charged_count=result.charged_count + n,
1975
+ event_charge_limit_reached=result.event_charge_limit_reached or capped,
1976
+ covered_counts=result.covered_counts,
1977
+ )
1889
1978
 
1890
1979
 
1891
1980
  async def _push_data_and_charge_one(
@@ -2278,15 +2367,25 @@ async def push_data_with_charges(
2278
2367
  """
2279
2368
  if charge_per == 'row':
2280
2369
  rows = items if isinstance(items, list) else [items]
2281
- groups = _push_groups(rows) if rows else None
2282
- if groups is not None:
2283
- results = [
2284
- await _push_data_with_charges_one(
2285
- charging_manager, group, charges, is_default_dataset, push_fn, charge_per
2286
- )
2287
- for group in groups
2288
- ]
2289
- return _merge_group_results(results)
2370
+
2371
+ async def push(rows: List[Any]) -> ChargeResult:
2372
+ groups = _push_groups(rows) if rows else None
2373
+ if groups is not None:
2374
+ results = [
2375
+ await _push_data_with_charges_one(
2376
+ charging_manager, group, charges, is_default_dataset, push_fn, charge_per
2377
+ )
2378
+ for group in groups
2379
+ ]
2380
+ return _merge_group_results(results)
2381
+ return await _push_data_with_charges_one(
2382
+ charging_manager, rows, charges, is_default_dataset, push_fn, charge_per
2383
+ )
2384
+
2385
+ paid = _paid_row_events(charging_manager, charges) if is_default_dataset and rows and isinstance(charges, dict) else []
2386
+ if paid:
2387
+ return await _skip_saved_rows(charging_manager, rows, paid, push)
2388
+ return await push(rows)
2290
2389
  return await _push_data_with_charges_one(
2291
2390
  charging_manager, items, charges, is_default_dataset, push_fn, charge_per
2292
2391
  )
@@ -0,0 +1,304 @@
1
+ """Results a resumed run already saved are not saved or charged again.
2
+
3
+ A resurrected or rebooted run keeps its default dataset, but the
4
+ Actor's code starts again from the beginning. An Actor that keeps no state of
5
+ its own (no request queue) then collects the results it saved before once more,
6
+ and each charged push would bill them a second time.
7
+
8
+ On the first charged push to the default dataset of such a run, the SDK reads
9
+ the result key (``id`` unless the Actor sets another with
10
+ ``Actor.set_result_key``) of the rows already saved. A later charged row whose
11
+ key is one of them is neither stored nor charged: the dataset already holds it
12
+ and it was paid for when it was first saved. It still counts as accepted, in
13
+ the push result and in ``get_charged_event_count``, so Actors that compare
14
+ what they pushed with what was charged do not read it as a refused charge.
15
+
16
+ The key must identify a row. When the saved rows repeat a key, or this run
17
+ pushes one key twice, it does not, and the run goes on as before: every row is
18
+ stored and charged. Nothing is skipped in a first run, in a run that saved
19
+ nothing yet, after a metamorph, or for pushes that are not charged per row.
20
+
21
+ A resumed generation also starts the Actor's own result count from zero. An
22
+ Actor that declares its run-level result limit (``Actor.set_result_limit(n)``,
23
+ e.g. its ``maxItems`` input) gets it applied across generations: once the rows
24
+ saved before plus the new rows of this generation reach ``n``, further charged
25
+ rows are refused like at the spending limit (not stored, not charged, and the
26
+ push reports the limit), so the run ends with ``n`` results, not more.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import logging
33
+ import os
34
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union
35
+
36
+ logger = logging.getLogger('scrapely.charging')
37
+
38
+ DEFAULT_RESULT_KEY: Tuple[str, ...] = ('id',)
39
+
40
+ # Saved rows read at most (keys only, ~a few MB of memory). A larger dataset
41
+ # is left as it is: reading it would delay the run's first push too long.
42
+ MAX_SAVED_ROWS = 200_000
43
+ _PAGE = 5_000
44
+
45
+ _OFF_VALUES = {'0', 'off', 'false', 'no'}
46
+
47
+ KeyValue = Tuple[Any, ...]
48
+
49
+
50
+ def _normalize_key(key: Union[str, Sequence[str], None]) -> Optional[Tuple[str, ...]]:
51
+ if key is None:
52
+ return None
53
+ if isinstance(key, str):
54
+ names: Tuple[str, ...] = (key,)
55
+ else:
56
+ names = tuple(key)
57
+ if not names or not all(isinstance(n, str) and n for n in names):
58
+ raise ValueError('result key must be a field name or a list of field names')
59
+ return names
60
+
61
+
62
+ def _scalar(value: Any) -> Any:
63
+ """A key part: a non-empty string or an integer (bool, float, None, objects are not keys)."""
64
+ if isinstance(value, bool):
65
+ return None
66
+ if isinstance(value, int):
67
+ return value
68
+ if isinstance(value, str) and value.strip():
69
+ return value
70
+ return None
71
+
72
+
73
+ def row_key(row: Any, fields: Tuple[str, ...]) -> Optional[KeyValue]:
74
+ """The row's key, or None when the row lacks a usable value for a key field."""
75
+ if not isinstance(row, dict):
76
+ return None
77
+ parts = []
78
+ for name in fields:
79
+ part = _scalar(row.get(name))
80
+ if part is None:
81
+ return None
82
+ # 123 and "123" are the same result.
83
+ parts.append(str(part))
84
+ return tuple(parts)
85
+
86
+
87
+ class ResumeDedupe:
88
+ """Per-process state: which saved rows a resumed run may skip."""
89
+
90
+ def __init__(self) -> None:
91
+ self._fields: Optional[Tuple[str, ...]] = DEFAULT_RESULT_KEY
92
+ self._state = 'unknown' # unknown | on | off
93
+ self._saved: Set[KeyValue] = set()
94
+ self._seen: Set[KeyValue] = set()
95
+ self._skipped = 0
96
+ self._announced = False
97
+ self._lock = asyncio.Lock()
98
+ # Run-level result limit the Actor declared (None: not declared).
99
+ self._limit: Optional[int] = None
100
+ # Rows the default dataset held when this resumed generation started (None: not a resumed run).
101
+ self._resumed_rows: Optional[int] = None
102
+ # New rows this generation stored through charged pushes.
103
+ self._new_rows = 0
104
+ self._limit_announced = False
105
+
106
+ # Actor API
107
+ def set_result_key(self, key: Union[str, Sequence[str], None]) -> None:
108
+ fields = _normalize_key(key)
109
+ if fields != self._fields:
110
+ self._fields = fields
111
+ # Keys read for the old fields are not valid for the new ones.
112
+ if self._state == 'on':
113
+ self._state = 'unknown'
114
+ self._saved = set()
115
+ self._seen = set()
116
+
117
+ def set_result_limit(self, limit: Optional[int]) -> None:
118
+ if limit is None:
119
+ self._limit = None
120
+ return
121
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
122
+ raise ValueError('result limit must be a positive integer or None')
123
+ self._limit = limit
124
+
125
+ def remaining(self) -> Optional[int]:
126
+ """New rows this resumed generation may still store under the declared limit (None: no cap)."""
127
+ if self._limit is None or self._resumed_rows is None:
128
+ return None
129
+ return max(0, self._limit - self._resumed_rows - self._new_rows)
130
+
131
+ def note_new_rows(self, count: int) -> None:
132
+ if count > 0:
133
+ self._new_rows += count
134
+
135
+ def note_capped(self) -> None:
136
+ if not self._limit_announced:
137
+ self._limit_announced = True
138
+ logger.info(
139
+ 'This run was resumed with %s results saved before; it stops at its limit of %s results',
140
+ self._resumed_rows,
141
+ self._limit,
142
+ )
143
+
144
+ @property
145
+ def skipped(self) -> int:
146
+ return self._skipped
147
+
148
+ @property
149
+ def active(self) -> bool:
150
+ return self._state == 'on'
151
+
152
+ def _off(self, reason: str) -> None:
153
+ if self._state == 'on':
154
+ logger.info(
155
+ 'Results this run saved before it was resumed are charged again from here on: %s', reason
156
+ )
157
+ self._state = 'off'
158
+ self._saved = set()
159
+ self._seen = set()
160
+
161
+ async def _load(self, manager: Any) -> None:
162
+ """Decide once whether this run is a resumed one with saved rows."""
163
+ if self._state != 'unknown':
164
+ return
165
+ self._state = 'off'
166
+ if (os.environ.get('SCRAPELY_RESUME_DEDUPE') or '').strip().lower() in _OFF_VALUES:
167
+ return
168
+ if self._fields is None and self._limit is None:
169
+ return
170
+ client = getattr(manager, '_client', None)
171
+ run_id = getattr(manager, '_actor_run_id', None)
172
+ from .charging import default_dataset_id_from_env
173
+
174
+ dataset_id = default_dataset_id_from_env()
175
+ if not getattr(manager, '_is_at_home', False) or client is None or not run_id or not dataset_id:
176
+ return
177
+ try:
178
+ info = await client.get_json(f'/v2/datasets/{dataset_id}')
179
+ item_count = int((info or {}).get('itemCount') or 0)
180
+ if item_count <= 0:
181
+ return # first run, or nothing saved yet: nothing to skip
182
+ run = await client.get_json(f'/v2/actor-runs/{run_id}')
183
+ stats = (run or {}).get('stats') or {}
184
+ resumed = sum(int(stats.get(k) or 0) for k in ('resurrectCount', 'rebootCount'))
185
+ if resumed <= 0 or int(stats.get('metamorph') or 0) > 0:
186
+ return
187
+ self._resumed_rows = item_count
188
+ if self._fields is None:
189
+ return # no result key: only the declared limit applies
190
+ if item_count > MAX_SAVED_ROWS:
191
+ logger.info(
192
+ 'This run was resumed with %s saved results, more than the %s the SDK reads to skip '
193
+ 'results saved before; every result is saved and charged as it comes',
194
+ item_count,
195
+ MAX_SAVED_ROWS,
196
+ )
197
+ return
198
+ saved: Set[KeyValue] = set()
199
+ keyed = 0
200
+ offset = 0
201
+ fields_param = ','.join(self._fields)
202
+ while offset < item_count:
203
+ page = await client.get_json(
204
+ f'/v2/datasets/{dataset_id}/items',
205
+ params={'fields': fields_param, 'offset': offset, 'limit': _PAGE},
206
+ )
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
+ if keyed < 2:
221
+ return
222
+ except Exception as err: # never fail a push over this
223
+ logger.debug('Could not read the saved results of the resumed run: %s', err)
224
+ return
225
+ self._saved = saved
226
+ self._seen = set()
227
+ self._state = 'on'
228
+
229
+ async def ensure(self, manager: Any) -> bool:
230
+ """True when this push needs the resumed-run path (saved rows to skip, or a declared limit)."""
231
+ if self._state == 'unknown':
232
+ async with self._lock:
233
+ await self._load(manager)
234
+ return self._state == 'on' or self.remaining() is not None
235
+
236
+ @property
237
+ def lock(self) -> asyncio.Lock:
238
+ return self._lock
239
+
240
+ def plan(self, rows: List[Any]) -> Tuple[List[Any], List[KeyValue], List[Optional[KeyValue]]]:
241
+ """Split rows into (rows to push, keys of skipped rows, key of each row to push or None).
242
+
243
+ Nothing is recorded until ``commit``; the caller holds ``lock``.
244
+ """
245
+ if self._state != 'on' or self._fields is None:
246
+ return rows, [], []
247
+ kept: List[Any] = []
248
+ skipped: List[KeyValue] = []
249
+ pushed: List[Optional[KeyValue]] = []
250
+ batch: Set[KeyValue] = set()
251
+ for row in rows:
252
+ key = row_key(row, self._fields)
253
+ if key is None:
254
+ kept.append(row)
255
+ pushed.append(None)
256
+ continue
257
+ if key in self._seen or key in batch:
258
+ # This run pushes one key twice: the key does not identify a row,
259
+ # so nothing of this push is skipped either.
260
+ self._off('the result key repeats in this run')
261
+ return rows, [], []
262
+ batch.add(key)
263
+ if key in self._saved:
264
+ skipped.append(key)
265
+ else:
266
+ kept.append(row)
267
+ pushed.append(key)
268
+ return kept, skipped, pushed
269
+
270
+ def commit(self, skipped: Iterable[KeyValue], pushed: Iterable[Optional[KeyValue]]) -> int:
271
+ """Record a push that went through: ``pushed`` = keys of the rows it stored."""
272
+ n = 0
273
+ for key in skipped:
274
+ self._saved.discard(key)
275
+ self._seen.add(key)
276
+ n += 1
277
+ for key in pushed:
278
+ if key is not None:
279
+ self._seen.add(key)
280
+ if n:
281
+ self._skipped += n
282
+ if not self._announced:
283
+ self._announced = True
284
+ logger.info(
285
+ 'This run was resumed: results it saved before (same %s) are not saved or charged again',
286
+ ' + '.join(repr(f) for f in (self._fields or ())),
287
+ )
288
+ return n
289
+
290
+
291
+ _instance: Optional[ResumeDedupe] = None
292
+
293
+
294
+ def get_resume_dedupe() -> ResumeDedupe:
295
+ global _instance
296
+ if _instance is None:
297
+ _instance = ResumeDedupe()
298
+ return _instance
299
+
300
+
301
+ def reset_resume_dedupe() -> None:
302
+ """Tests: forget the per-process state."""
303
+ global _instance
304
+ _instance = None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scrapely-python
3
- Version: 0.1.46
3
+ Version: 0.1.48
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
@@ -19,6 +19,7 @@ src/scrapely/patch_browser_pool.py
19
19
  src/scrapely/pricing_types.py
20
20
  src/scrapely/proxy_configuration.py
21
21
  src/scrapely/py.typed
22
+ src/scrapely/resume_dedupe.py
22
23
  src/scrapely/solver.py
23
24
  src/scrapely/types.py
24
25
  src/scrapely/webhook.py