Skip to content

Commit 180dd95

Browse files
authored
feat!: reject IDs that cannot be part of a key-value store key (#2548)
The `id` of a crawler is now checked, so it can always be part of a key-value store key. The same check runs for an explicit `id` of `SessionPool`, `Statistics` and `DefaultRenderingTypePredictor`, which use it in their keys too. - The `id` must be at most 217 characters long and contain only `a-zA-Z0-9!-_.'()`, otherwise the constructor raises `ValueError`. The limit leaves room for the longest key prefix, `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_` (39 characters), within the 256-character key limit. Crawlee JS checks the same characters but allows 256, so its derived keys can be longer than a valid key. - A non-string `id`, such as an `int` from v1, raises `TypeError` that names the class. Before, an `id` like `a/b` produced keys like `CRAWLEE_STATE_a/b`, which the Apify platform doesn't accept as keys. It's breaking, since an `id` that worked before can now raise. The new check replaces the first half of `test_id_invalid_as_request_queue_alias`, because an `id` that passes it always forms a valid RQ alias. The second half is kept as its own test. Closes: #2546 *✍️ Drafted by Claude Code*
1 parent 99fc497 commit 180dd95

8 files changed

Lines changed: 161 additions & 11 deletions

File tree

‎docs/06_upgrading/upgrading_to_v2.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,8 @@ async def main() -> None:
552552

553553
The `id` argument of `BasicCrawler` and its subclasses is now a `str`, so pass a string wherever you passed an integer. `StatisticsState.stats_id` and `EventCrawlerStatusData.crawler_id` are strings too, and `crawler_id` holds the crawler's `id`. In v1, it held the Python object ID of the crawler.
554554

555+
The crawler `id` is part of key-value store keys, such as `CRAWLEE_STATE_{id}`, so the constructor now raises `ValueError` for an `id` that can't be part of a valid key. The `id` must be at most 217 characters long and contain only the characters `a-zA-Z0-9!-_.'()`. The limit leaves room for the longest key prefix, `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_`, within the 256-character key limit. Crawlee JS checks the same characters but allows 256 characters. A non-string `id`, such as an `int` from v1, raises `TypeError`. `SessionPool`, `Statistics` and `DefaultRenderingTypePredictor` check an explicit `id` the same way.
556+
555557
The statistics a crawler creates by default now use the `id` you pass to the crawler, except those of `AdaptivePlaywrightCrawler`, which aren't persisted. Crawlers that share an `id` therefore share both the state returned by `use_state` and the persisted statistics. In v1, they shared only the state. A later crawler with the same `id` continues the statistics of the earlier one, so its `max_requests_per_crawl` counts their requests too.
556558

557559
A crawler without an `id` gets its creation index, such as `'0'`, and crawlers with an explicit `id` now count towards that index too. If you resume a v1 run with `purge_on_start=False` and mix both kinds of crawlers, a generated `id` can differ from the one v1 assigned, and the crawler won't find the state that `use_state` stored under the old one. The default statistics of a crawler without an `id` get their `id` from a per-process counter of the `Statistics` instances created without one. v2 doesn't read the statistics that v1 persisted, as described in [Internal key-value store records are renamed](#internal-key-value-store-records-are-renamed).

‎src/crawlee/_utils/ids.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from __future__ import annotations
2+
3+
import re
4+
5+
MAX_ID_LENGTH = 217
6+
"""The longest ID that keeps every key built from it within the 256-character key-value store key limit. The longest
7+
key prefix is `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_`, with 39 characters."""
8+
9+
_ID_PATTERN = re.compile(rf"[a-zA-Z0-9!\-_.'()]{{1,{MAX_ID_LENGTH}}}")
10+
11+
12+
def validate_id(value: object, owner: str) -> None:
13+
"""Check that an ID can be part of a key-value store key.
14+
15+
Args:
16+
value: The ID to check.
17+
owner: The name of the class the ID belongs to, used in the error message.
18+
19+
Raises:
20+
TypeError: If the ID isn't a string.
21+
ValueError: If the ID is empty, too long, or contains a character that a key can't contain.
22+
"""
23+
if not isinstance(value, str):
24+
raise TypeError(f'The `id` of `{owner}` must be a string, got {type(value).__name__}.')
25+
26+
if not _ID_PATTERN.fullmatch(value):
27+
raise ValueError(
28+
f'The `id` of `{owner}` must be at most {MAX_ID_LENGTH} characters long and contain only the characters '
29+
f"a-zA-Z0-9!-_.'(), got {value!r}."
30+
)

‎src/crawlee/crawlers/_adaptive_playwright/_rendering_type_predictor.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from typing_extensions import override
1717

1818
from crawlee._utils.docs import docs_group
19+
from crawlee._utils.ids import validate_id
1920
from crawlee._utils.recoverable_state import RecoverableState
2021

2122
from ._utils import sklearn_model_serializer, sklearn_model_validator
@@ -141,15 +142,18 @@ def __init__(
141142
detection_ratio: A number between 0 and 1 that determines the desired ratio of rendering type detections.
142143
id: An identifier of the predictor, used in the default `persist_state_key`. Defaults to a per-process
143144
counter of the `DefaultRenderingTypePredictor` instances created without an `id`. Explicit IDs share one
144-
namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
145+
namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. It must be at most 217
146+
characters long and contain only the characters `a-zA-Z0-9!-_.'()`.
145147
persist_state_key: Key in the key-value storage where the trained model parameters will be saved.
146148
Defaults to `CRAWLEE_RENDERING_TYPE_PREDICTOR_STATE_{id}`.
147149
persistence_enabled: Whether to enable persistence of the trained model parameters for reuse.
148150
149151
"""
150152
super().__init__()
151153

152-
if id is None:
154+
if id is not None:
155+
validate_id(id, type(self).__name__)
156+
else:
153157
id = str(DefaultRenderingTypePredictor.__next_id)
154158
DefaultRenderingTypePredictor.__next_id += 1
155159
self._id = id

‎src/crawlee/crawlers/_basic/_basic_crawler.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
from crawlee._utils.file import atomic_write, export_csv_to_stream, export_json_to_stream
4848
from crawlee._utils.globs import check_url_patterns
4949
from crawlee._utils.http import parse_retry_after_header
50+
from crawlee._utils.ids import validate_id
5051
from crawlee._utils.log import LoggerOnce, request_log_extra
5152
from crawlee._utils.recurring_task import RecurringTask
5253
from crawlee._utils.robots import RobotsTxtFile
@@ -223,7 +224,8 @@ class _BasicCrawlerOptions(TypedDict):
223224
every crawler but the first uses it in the alias of its default request queue. The crawler also passes it to the
224225
default statistics and session pool. Without it, the ID follows the order in which crawlers are created, and the
225226
statistics and the session pool generate their own IDs. Explicit IDs share one namespace with the generated ones, so
226-
avoid explicit IDs like `'0'` or `'1'`."""
227+
avoid explicit IDs like `'0'` or `'1'`. The ID is part of key-value store keys, so it must be at most 217 characters
228+
long and contain only the characters `a-zA-Z0-9!-_.'()`."""
227229

228230

229231
class _BasicCrawlerOptionsGeneric(TypedDict, Generic[TCrawlingContext, TStatisticsState]):
@@ -395,10 +397,14 @@ def __init__(
395397
statistics, and every crawler but the first uses it in the alias of its default request queue. The
396398
crawler also passes it to the default statistics and session pool. Without it, the ID follows the order
397399
in which crawlers are created, and the statistics and the session pool generate their own IDs. Explicit
398-
IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
400+
IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. The ID is
401+
part of key-value store keys, so it must be at most 217 characters long and contain only the characters
402+
`a-zA-Z0-9!-_.'()`.
399403
_context_pipeline: Enables extending the request lifecycle and modifying the crawling context.
400404
Intended for use by subclasses rather than direct instantiation of `BasicCrawler`.
401405
"""
406+
if id is not None:
407+
validate_id(id, type(self).__name__)
402408
self._id = str(BasicCrawler.__next_id) if id is None else id
403409
self._default_rq_alias = None if BasicCrawler.__next_id == 0 else f'__default_{self._id}__'
404410
BasicCrawler.__next_id += 1

‎src/crawlee/sessions/_session_pool.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from crawlee import service_locator
1111
from crawlee._utils.context import ensure_context
1212
from crawlee._utils.docs import docs_group
13+
from crawlee._utils.ids import validate_id
1314
from crawlee._utils.recoverable_state import RecoverableState
1415
from crawlee.sessions import Session
1516
from crawlee.sessions._models import SessionPoolModel
@@ -53,7 +54,8 @@ def __init__(
5354
id: An identifier of the pool, used in the default `persist_state_key`. Defaults to a per-process counter of
5455
the `SessionPool` instances created without an `id`, which includes the pools that crawlers without an
5556
`id` create. Pass an `id` to a pool you persist, so that its key doesn't depend on the creation order.
56-
Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`.
57+
Explicit IDs share one namespace with the generated ones, so avoid explicit IDs like `'0'` or `'1'`. It
58+
must be at most 217 characters long and contain only the characters `a-zA-Z0-9!-_.'()`.
5759
max_pool_size: Maximum number of sessions to maintain in the pool. You can add more sessions to the pool
5860
by using the `add_session` method.
5961
create_session_settings: Settings for creating new session instances. If None, default settings will
@@ -66,9 +68,13 @@ def __init__(
6668
persist_state_key: The key under which the session pool's state is stored in the `KeyValueStore`.
6769
Defaults to `CRAWLEE_SESSION_POOL_STATE_{id}`.
6870
"""
71+
if id is not None:
72+
validate_id(id, type(self).__name__)
73+
6974
if event_manager:
7075
service_locator.set_event_manager(event_manager)
7176

77+
# A generated ID is taken only after the calls that can raise, so a failed construction doesn't skip one.
7278
if id is None:
7379
id = str(SessionPool.__next_id)
7480
SessionPool.__next_id += 1

‎src/crawlee/statistics/_statistics.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
from crawlee._utils.context import ensure_context
1414
from crawlee._utils.docs import docs_group
15+
from crawlee._utils.ids import validate_id
1516
from crawlee._utils.recoverable_state import RecoverableState
1617
from crawlee._utils.recurring_task import RecurringTask
1718
from crawlee.statistics import FinalStatistics, StatisticsState
@@ -86,7 +87,9 @@ def __init__(
8687
save_error_snapshots: bool = False,
8788
id: str | None = None,
8889
) -> None:
89-
if id is None:
90+
if id is not None:
91+
validate_id(id, type(self).__name__)
92+
else:
9093
id = str(Statistics.__next_id)
9194
Statistics.__next_id += 1
9295
self._id = id

‎tests/unit/_utils/test_ids.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING
4+
5+
import pytest
6+
7+
from crawlee._utils.ids import MAX_ID_LENGTH, validate_id
8+
from crawlee.crawlers._adaptive_playwright._rendering_type_predictor import DefaultRenderingTypePredictor
9+
from crawlee.sessions import SessionPool
10+
from crawlee.statistics import Statistics
11+
12+
if TYPE_CHECKING:
13+
from collections.abc import Callable
14+
15+
16+
@pytest.mark.parametrize(
17+
'value',
18+
[
19+
pytest.param('my-id', id='hyphen'),
20+
pytest.param("a.b_c!(1)'", id='all allowed special characters'),
21+
pytest.param('x' * MAX_ID_LENGTH, id='max length'),
22+
],
23+
)
24+
def test_validate_id_accepts_valid_id(value: str) -> None:
25+
"""An ID that can be part of a key-value store key passes."""
26+
validate_id(value, 'Owner')
27+
28+
29+
@pytest.mark.parametrize(
30+
'value',
31+
[
32+
pytest.param('a/b', id='slash'),
33+
pytest.param('', id='empty'),
34+
pytest.param('x' * (MAX_ID_LENGTH + 1), id='too long'),
35+
],
36+
)
37+
def test_validate_id_rejects_invalid_id(value: str) -> None:
38+
"""An ID that can't be part of a key-value store key raises `ValueError` naming the owner."""
39+
with pytest.raises(ValueError, match='The `id` of `Owner` must'):
40+
validate_id(value, 'Owner')
41+
42+
43+
def test_validate_id_rejects_non_string() -> None:
44+
"""An ID that isn't a string raises `TypeError` naming the owner and the type."""
45+
with pytest.raises(TypeError, match='The `id` of `Owner` must be a string, got int'):
46+
validate_id(5, 'Owner')
47+
48+
49+
@pytest.mark.parametrize(
50+
'create_component',
51+
[
52+
pytest.param(lambda id: SessionPool(id=id), id='session pool'),
53+
pytest.param(lambda id: Statistics.with_default_state(id=id), id='statistics'),
54+
pytest.param(lambda id: DefaultRenderingTypePredictor(id=id), id='rendering type predictor'),
55+
],
56+
)
57+
def test_components_reject_invalid_id(create_component: Callable[[str], object]) -> None:
58+
"""The components that use their ID in a key-value store key reject an invalid ID."""
59+
with pytest.raises(ValueError, match='must be at most'):
60+
create_component('a/b')
61+
62+
63+
def test_longest_key_of_max_length_id_fits_key_limit() -> None:
64+
"""The longest key built from an ID of the maximum length is a valid 256-character key."""
65+
predictor = DefaultRenderingTypePredictor(id='x' * MAX_ID_LENGTH)
66+
assert len(predictor._state._persist_state_key) == 256

‎tests/unit/crawlers/_basic/test_basic_crawler.py‎

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,13 +1521,46 @@ async def test_crawlers_do_not_share_requests() -> None:
15211521
assert stats_2.requests_finished == 1
15221522

15231523

1524-
async def test_id_invalid_as_request_queue_alias() -> None:
1525-
"""A later crawler whose ID can't form an RQ alias fails to open its RQ, unless it gets a request manager."""
1524+
@pytest.mark.parametrize(
1525+
'crawler_id',
1526+
[
1527+
pytest.param('shop/products', id='slash'),
1528+
pytest.param('my crawler', id='space'),
1529+
pytest.param('crawler-\u00fc', id='non-ascii'),
1530+
pytest.param('', id='empty'),
1531+
pytest.param('x' * 218, id='too long'),
1532+
],
1533+
)
1534+
def test_invalid_id_is_rejected(crawler_id: str) -> None:
1535+
"""A crawler `id` that can't be part of a key-value store key is rejected."""
1536+
with pytest.raises(ValueError, match='The `id` of `BasicCrawler` must'):
1537+
BasicCrawler(id=crawler_id)
1538+
1539+
1540+
def test_non_string_id_is_rejected() -> None:
1541+
"""A crawler `id` that isn't a string, such as a v1 `int`, is rejected with a `TypeError` that names it."""
1542+
with pytest.raises(TypeError, match='The `id` of `BasicCrawler` must be a string, got int'):
1543+
BasicCrawler(id=5) # ty: ignore[invalid-argument-type]
1544+
1545+
1546+
@pytest.mark.parametrize(
1547+
'crawler_id',
1548+
[
1549+
pytest.param('my-crawler', id='hyphen'),
1550+
pytest.param("a.b_c!(1)'", id='all allowed special characters'),
1551+
pytest.param('x' * 217, id='max length'),
1552+
],
1553+
)
1554+
def test_valid_id_is_accepted(crawler_id: str) -> None:
1555+
"""A crawler `id` that can be part of a key-value store key is accepted."""
1556+
assert BasicCrawler(id=crawler_id)._id == crawler_id
1557+
1558+
1559+
async def test_later_crawler_with_request_manager_uses_it() -> None:
1560+
"""A crawler created after the first one, with an explicit ID and a `request_manager`, uses that manager."""
15261561
BasicCrawler()
1527-
with pytest.raises(ValueError, match='Invalid storage alias'):
1528-
await BasicCrawler(id='shop/products').get_request_manager()
15291562
request_manager = Mock()
1530-
crawler = BasicCrawler(id='shop/products', request_manager=request_manager)
1563+
crawler = BasicCrawler(id='shop-products', request_manager=request_manager)
15311564
assert await crawler.get_request_manager() is request_manager
15321565

15331566

0 commit comments

Comments
 (0)