From 23fb724f7d36b8a08c249760b13125859ef28720 Mon Sep 17 00:00:00 2001 From: Max Bohomolov Date: Thu, 3 Dec 2026 20:54:02 +0000 Subject: [PATCH] write metadata timestamps less often --- docs/06_upgrading/upgrading_to_v2.md | 4 + .../_file_system/_dataset_backend.py | 37 ++++++-- .../_file_system/_key_value_store_backend.py | 35 +++++-- .../_file_system/_request_queue_backend.py | 44 +++++++-- .../storage_backends/_redis/_backend_mixin.py | 35 +++++-- .../storage_backends/_sql/_backend_mixin.py | 46 +++++++--- src/crawlee/storage_backends/_utils.py | 45 +++++++++ src/crawlee/storage_backends/models.py | 4 +- .../_file_system/test_fs_dataset_backend.py | 82 ++++++++++++----- .../_file_system/test_fs_kvs_backend.py | 91 +++++++++++++++---- .../_file_system/test_fs_rq_backend.py | 91 ++++++++++++++----- .../_redis/test_redis_dataset_backend.py | 42 ++++----- .../_redis/test_redis_kvs_backend.py | 66 +++++++++----- .../_redis/test_redis_rq_backend.py | 32 +++---- .../_sql/test_sql_dataset_backend.py | 49 ++++------ .../_sql/test_sql_kvs_backend.py | 71 +++++++++------ .../_sql/test_sql_rq_backend.py | 46 +++++----- .../test_timestamp_throttle.py | 63 +++++++++++++ tests/unit/storages/conftest.py | 28 ++++++ tests/unit/storages/test_dataset.py | 23 ++++- tests/unit/storages/test_key_value_store.py | 19 +++- tests/unit/storages/test_request_queue.py | 21 ++++- 22 files changed, 712 insertions(+), 262 deletions(-) create mode 100644 tests/unit/storage_backends/test_timestamp_throttle.py diff --git a/docs/06_upgrading/upgrading_to_v2.md b/docs/06_upgrading/upgrading_to_v2.md index e0b980b763..bdb09004e4 100644 --- a/docs/06_upgrading/upgrading_to_v2.md +++ b/docs/06_upgrading/upgrading_to_v2.md @@ -315,6 +315,10 @@ A crawler keeps the lock at least as long as its longest request handler timeout `RequestQueueMetadata` no longer has the `had_multiple_clients` field, the same as in Crawlee JS. In v1, only `SqlStorageClient` set it to `True`, and the other built-in storage clients always reported `False`. A custom request queue backend can stop setting it. `SqlStorageBackend` no longer creates the `had_multiple_clients` column of the `request_queues` table and the `client_id` column of the `request_queue_metadata_buffer` table, so request queues don't work in a database created by v1. Datasets and key-value stores in such a database keep working. +### Metadata timestamps are approximate + +`FileSystemStorageBackend`, `SqlStorageBackend` and `RedisStorageBackend` now write `accessed_at` and `modified_at` to the storage metadata less often, so the stored timestamps can trail the last access or modification by a few seconds. In v1, they were written at once, and `MemoryStorageBackend` still writes them that way. A purge writes them at once on every backend. + ## Datasets `Dataset` now checks each pushed item and passes a JSON copy of it to the storage backend, and reads the items from the backend a page at a time. In v1, each storage backend did both on its own. The rules are the same for every storage backend. diff --git a/src/crawlee/storage_backends/_file_system/_dataset_backend.py b/src/crawlee/storage_backends/_file_system/_dataset_backend.py index 0ffce3dd38..8316b787b3 100644 --- a/src/crawlee/storage_backends/_file_system/_dataset_backend.py +++ b/src/crawlee/storage_backends/_file_system/_dataset_backend.py @@ -19,7 +19,7 @@ from crawlee._utils.log import LoggerOnce from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs from crawlee.storage_backends._base import DatasetBackend -from crawlee.storage_backends._utils import slice_dataset_page, warn_unsupported_list_options +from crawlee.storage_backends._utils import TimestampThrottle, slice_dataset_page, warn_unsupported_list_options from crawlee.storage_backends.models import DatasetItemsListPage, DatasetMetadata if TYPE_CHECKING: @@ -78,6 +78,9 @@ def __init__( self._logger_once = LoggerOnce(logger) """Logs the warning about each set of unsupported list options once for this dataset.""" + self._timestamp_throttle = TimestampThrottle() + """Spares the metadata file writes of timestamps alone that aren't due yet.""" + @override async def get_metadata(self) -> DatasetMetadata: return self._metadata @@ -226,6 +229,8 @@ async def purge(self) -> None: for file_path in await self._get_sorted_data_files(): await asyncio.to_thread(file_path.unlink, missing_ok=True) + # A purge writes its timestamps at once, also when the dataset was empty already. + self._timestamp_throttle.reset() await self._update_metadata( update_accessed_at=True, update_modified_at=True, @@ -338,11 +343,20 @@ async def _update_metadata( Args: new_item_count: If provided, update the item count to this value. - update_accessed_at: If True, update the `accessed_at` timestamp to the current time. - update_modified_at: If True, update the `modified_at` timestamp to the current time. + update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due. + update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due. """ now = datetime.now(UTC) + count_changed = new_item_count not in (None, self._metadata.item_count) + + if update_accessed_at or update_modified_at: + update_accessed_at, update_modified_at = self._timestamp_throttle.to_write( + now, modified=update_modified_at, with_other_changes=count_changed + ) + if not update_accessed_at: + return + if update_accessed_at: self._metadata.accessed_at = now if update_modified_at: @@ -350,12 +364,17 @@ async def _update_metadata( if new_item_count is not None: self._metadata.item_count = new_item_count - # Ensure the parent directory for the metadata file exists. - await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) - - # Dump the serialized metadata to the file. - data = await json_dumps(self._metadata.model_dump(by_alias=True)) - await atomic_write(self.path_to_metadata, data) + try: + # Ensure the parent directory for the metadata file exists. + await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) + + # Dump the serialized metadata to the file. + data = await json_dumps(self._metadata.model_dump(by_alias=True)) + await atomic_write(self.path_to_metadata, data) + except BaseException: + # The file keeps the timestamps of the last write that went through, so the next write updates it at once. + self._timestamp_throttle.reset() + raise async def _push_item(self, item: Mapping[str, JsonSerializable], item_id: int) -> None: """Push a single item to the dataset. diff --git a/src/crawlee/storage_backends/_file_system/_key_value_store_backend.py b/src/crawlee/storage_backends/_file_system/_key_value_store_backend.py index fbbfb34c57..2bffee0bf2 100644 --- a/src/crawlee/storage_backends/_file_system/_key_value_store_backend.py +++ b/src/crawlee/storage_backends/_file_system/_key_value_store_backend.py @@ -18,7 +18,7 @@ from crawlee._utils.file import atomic_write, json_dumps, validate_subdirectory from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs from crawlee.storage_backends._base import KeyValueStoreBackend -from crawlee.storage_backends._utils import SortedKeys +from crawlee.storage_backends._utils import SortedKeys, TimestampThrottle from crawlee.storage_backends.models import ( KeyValueStoreKeysListPage, KeyValueStoreMetadata, @@ -86,6 +86,9 @@ def __init__( self._next_exclusive_start_key: str | None = None """The `exclusive_start_key` of the next page after the last listed page.""" + self._timestamp_throttle = TimestampThrottle() + """Spares the metadata file writes of timestamps alone that aren't due yet.""" + @override async def get_metadata(self) -> KeyValueStoreMetadata: return self._metadata @@ -220,6 +223,8 @@ async def drop(self) -> None: async with self._lock: self._sorted_keys = None await asyncio.to_thread(shutil.rmtree, self.path_to_kvs) + # A write after the drop recreates the metadata file, whose timestamps would otherwise not be due yet. + self._timestamp_throttle.reset() @override async def purge(self) -> None: @@ -232,6 +237,8 @@ async def purge(self) -> None: continue await asyncio.to_thread(file_path.unlink, missing_ok=True) + # A purge writes its timestamps at once. + self._timestamp_throttle.reset() await self._update_metadata( update_accessed_at=True, update_modified_at=True, @@ -410,22 +417,32 @@ async def _update_metadata( """Update the KVS metadata file with current information. Args: - update_accessed_at: If True, update the `accessed_at` timestamp to the current time. - update_modified_at: If True, update the `modified_at` timestamp to the current time. + update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due. + update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due. """ now = datetime.now(UTC) + if update_accessed_at or update_modified_at: + update_accessed_at, update_modified_at = self._timestamp_throttle.to_write(now, modified=update_modified_at) + if not update_accessed_at: + return + if update_accessed_at: self._metadata.accessed_at = now if update_modified_at: self._metadata.modified_at = now - # Ensure the parent directory for the metadata file exists. - await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) - - # Dump the serialized metadata to the file. - data = await json_dumps(self._metadata.model_dump(by_alias=True)) - await atomic_write(self.path_to_metadata, data) + try: + # Ensure the parent directory for the metadata file exists. + await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) + + # Dump the serialized metadata to the file. + data = await json_dumps(self._metadata.model_dump(by_alias=True)) + await atomic_write(self.path_to_metadata, data) + except BaseException: + # The file keeps the timestamps of the last write that went through, so the next write updates it at once. + self._timestamp_throttle.reset() + raise def _read_record(self, key: str) -> KeyValueStoreRecord | None: """Read the record of the key from its files, or return `None` when it has none or they can't be read.""" diff --git a/src/crawlee/storage_backends/_file_system/_request_queue_backend.py b/src/crawlee/storage_backends/_file_system/_request_queue_backend.py index 2750203eaa..549870637e 100644 --- a/src/crawlee/storage_backends/_file_system/_request_queue_backend.py +++ b/src/crawlee/storage_backends/_file_system/_request_queue_backend.py @@ -20,6 +20,7 @@ from crawlee._utils.raise_if_too_many_kwargs import raise_if_too_many_kwargs from crawlee._utils.recoverable_state import RecoverableState from crawlee.storage_backends._base import RequestQueueBackend +from crawlee.storage_backends._utils import TimestampThrottle from crawlee.storage_backends.models import ( AddRequestsResponse, ProcessedRequest, @@ -119,6 +120,9 @@ def __init__( self._state = recoverable_state """Recoverable state to maintain request ordering, in-progress status, and handled status.""" + self._timestamp_throttle = TimestampThrottle() + """Spares the metadata file writes of timestamps alone that aren't due yet.""" + @override async def get_metadata(self) -> RequestQueueMetadata: return self._metadata @@ -306,6 +310,8 @@ async def purge(self) -> None: self._request_cache.clear() self._request_cache_needs_refresh = True + # A purge writes its timestamps at once, also when the queue was empty already. + self._timestamp_throttle.reset() await self._update_metadata( update_modified_at=True, update_accessed_at=True, @@ -678,12 +684,27 @@ async def _update_metadata( new_handled_request_count: If provided, update the handled_request_count to this value. new_pending_request_count: If provided, update the pending_request_count to this value. new_total_request_count: If provided, update the total_request_count to this value. - update_accessed_at: If True, update the `accessed_at` timestamp to the current time. - update_modified_at: If True, update the `modified_at` timestamp to the current time. + update_accessed_at: If True, update the `accessed_at` timestamp to the current time when it's due. + update_modified_at: If True, update the `modified_at` timestamp to the current time when it's due. """ - # Always create a new timestamp to ensure it's truly updated now = datetime.now(UTC) + # An add of known requests only sets the counts to their current values. + counts_changed = any( + [ + new_handled_request_count not in (None, self._metadata.handled_request_count), + new_pending_request_count not in (None, self._metadata.pending_request_count), + new_total_request_count not in (None, self._metadata.total_request_count), + ] + ) + + if update_accessed_at or update_modified_at: + update_accessed_at, update_modified_at = self._timestamp_throttle.to_write( + now, modified=update_modified_at, with_other_changes=counts_changed + ) + if not update_accessed_at: + return + # Update timestamps according to parameters if update_accessed_at: self._metadata.accessed_at = now @@ -701,12 +722,17 @@ async def _update_metadata( if new_total_request_count is not None: self._metadata.total_request_count = new_total_request_count - # Ensure the parent directory for the metadata file exists. - await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) - - # Dump the serialized metadata to the file. - data = await json_dumps(self._metadata.model_dump(by_alias=True)) - await atomic_write(self.path_to_metadata, data) + try: + # Ensure the parent directory for the metadata file exists. + await asyncio.to_thread(self.path_to_metadata.parent.mkdir, parents=True, exist_ok=True) + + # Dump the serialized metadata to the file. + data = await json_dumps(self._metadata.model_dump(by_alias=True)) + await atomic_write(self.path_to_metadata, data) + except BaseException: + # The file keeps the timestamps of the last write that went through, so the next write updates it at once. + self._timestamp_throttle.reset() + raise async def _refresh_cache(self) -> None: """Refresh the request cache from the filesystem. diff --git a/src/crawlee/storage_backends/_redis/_backend_mixin.py b/src/crawlee/storage_backends/_redis/_backend_mixin.py index bef01a3779..60a22ff6ab 100644 --- a/src/crawlee/storage_backends/_redis/_backend_mixin.py +++ b/src/crawlee/storage_backends/_redis/_backend_mixin.py @@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, TypedDict, overload from crawlee._utils.crypto import crypto_random_object_id +from crawlee.storage_backends._utils import TimestampThrottle from ._utils import await_redis_response, read_lua_script @@ -55,6 +56,9 @@ def __init__(self, storage_name: str, storage_id: str, storage_backend: RedisSto self._scripts_loaded = False + self._timestamp_throttle = TimestampThrottle() + """Spares the metadata writes of timestamps alone that aren't due yet.""" + @property def redis(self) -> Redis: """Return the Redis client instance.""" @@ -197,13 +201,19 @@ async def _ensure_scripts_loaded(self) -> None: @asynccontextmanager async def _get_pipeline(self, *, with_execute: bool = True) -> AsyncGenerator[Pipeline]: """Create a new Redis pipeline.""" - async with self.redis.pipeline() as pipe: - try: - pipe.multi() - yield pipe - finally: - if with_execute: - await pipe.execute() + try: + async with self.redis.pipeline() as pipe: + try: + pipe.multi() + yield pipe + finally: + if with_execute: + await pipe.execute() + except BaseException: + # The timestamps of a failed or cancelled transaction never reach Redis, so the next write, such as a retry, + # writes them at once. + self._timestamp_throttle.reset() + raise async def _create_storage(self, pipeline: Pipeline) -> None: """Create the actual storage structure in Redis.""" @@ -250,6 +260,8 @@ async def _purge(self, extra_keys: list[str], metadata_kwargs: MetadataUpdatePar async with self._get_pipeline() as pipe: for key in extra_keys: await pipe.delete(key) + # A purge writes its timestamps at once. + self._timestamp_throttle.reset() await self._update_metadata(pipe, **metadata_kwargs) await self._create_storage(pipe) @@ -294,12 +306,17 @@ async def _update_metadata( Args: pipeline: The Redis pipeline to use for the update. - update_accessed_at: Whether to update accessed_at timestamp. - update_modified_at: Whether to update modified_at timestamp. + update_accessed_at: Whether to update accessed_at timestamp when it's due. + update_modified_at: Whether to update modified_at timestamp when it's due. **kwargs: Additional arguments for _specific_update_metadata. """ now = datetime.now(UTC) + if update_accessed_at or update_modified_at: + update_accessed_at, update_modified_at = self._timestamp_throttle.to_write( + now, modified=update_modified_at, with_other_changes=bool(kwargs) + ) + if update_accessed_at: await await_redis_response( pipeline.json().set(self.metadata_key, '$.accessed_at', now.isoformat(), nx=False, xx=True) diff --git a/src/crawlee/storage_backends/_sql/_backend_mixin.py b/src/crawlee/storage_backends/_sql/_backend_mixin.py index ceb0966af7..0ea1743bb6 100644 --- a/src/crawlee/storage_backends/_sql/_backend_mixin.py +++ b/src/crawlee/storage_backends/_sql/_backend_mixin.py @@ -14,6 +14,7 @@ from sqlalchemy.exc import OperationalError, SQLAlchemyError from crawlee._utils.crypto import crypto_random_object_id +from crawlee.storage_backends._utils import TimestampThrottle if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -83,6 +84,9 @@ def __init__(self, *, id: str, storage_backend: SqlStorageBackend) -> None: self._id = id self._storage_backend = storage_backend + self._timestamp_throttle = TimestampThrottle() + """Spares the buffer records of timestamps alone that aren't due yet.""" + @classmethod async def _open( cls, @@ -195,18 +199,24 @@ async def _safely_open( @asynccontextmanager async def get_session(self, *, with_simple_commit: bool = False) -> AsyncGenerator[AsyncSession]: """Create a new SQLAlchemy session for this storage.""" - async with self._storage_backend.create_session() as session: - # For operations where a final commit is mandatory and does not require specific processing conditions - if with_simple_commit: - try: + try: + async with self._storage_backend.create_session() as session: + # For operations where a final commit is mandatory and does not require specific processing conditions + if with_simple_commit: + try: + yield session + await session.commit() + except SQLAlchemyError as e: + logger.warning('Error occurred during session transaction: %s', e) + await session.rollback() + raise + else: yield session - await session.commit() - except SQLAlchemyError as e: - logger.warning('Error occurred during session transaction: %s', e) - await session.rollback() - raise - else: - yield session + except BaseException: + # The timestamps of a failed or cancelled transaction never reach the database, so the next write, such as + # a retry, writes them at once. + self._timestamp_throttle.reset() + raise def _build_insert_stmt_with_ignore( self, table_model: type[DeclarativeBase], insert_values: dict[str, Any] | list[dict[str, Any]] @@ -387,18 +397,28 @@ async def _add_buffer_record( ) -> None: """Add a record to the buffer table and update metadata. + A record that would carry only timestamps that aren't due yet isn't added. + Args: session: Active database session. - update_modified_at: Whether to update modified_at timestamp. + update_modified_at: Whether to update modified_at timestamp when it's due. **kwargs: Additional arguments for _prepare_buffer_data. """ now = datetime.now(UTC) + buffer_data = self._prepare_buffer_data(**kwargs) + + update_accessed_at, update_modified_at = self._timestamp_throttle.to_write( + now, modified=update_modified_at, with_other_changes=bool(buffer_data) + ) + if not update_accessed_at: + return + values_to_set = { 'storage_id': self._id, 'accessed_at': now, # All entries in the buffer require updating `accessed_at` 'modified_at': now if update_modified_at else None, } - values_to_set.update(self._prepare_buffer_data(**kwargs)) + values_to_set.update(buffer_data) session.add(self._BUFFER_TABLE(**values_to_set)) diff --git a/src/crawlee/storage_backends/_utils.py b/src/crawlee/storage_backends/_utils.py index bcd194ff89..ce0c122733 100644 --- a/src/crawlee/storage_backends/_utils.py +++ b/src/crawlee/storage_backends/_utils.py @@ -3,16 +3,61 @@ import bisect import itertools import logging +from datetime import timedelta from typing import TYPE_CHECKING, Any, TypeVar if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence + from datetime import datetime from crawlee._utils.log import LoggerOnce from crawlee.storage_backends.models import KeyValueStoreRecordMetadata T = TypeVar('T') +_TIMESTAMP_WRITE_INTERVAL = timedelta(seconds=5) + + +class TimestampThrottle: + """Decide which of the `accessed_at` and `modified_at` metadata timestamps a storage backend writes. + + A timestamp that goes into a metadata write made anyway, such as a changed counter, is always written. On its own, + each timestamp is written at most once per interval, so the stored one trails the last access or modification by a + few seconds. Writing `modified_at` also writes `accessed_at` and restarts its interval. + """ + + def __init__(self) -> None: + self._accessed_at: datetime | None = None + self._modified_at: datetime | None = None + + def to_write(self, now: datetime, *, modified: bool, with_other_changes: bool = False) -> tuple[bool, bool]: + """Return whether to write `accessed_at` and `modified_at` for an access at `now`, and count them as written. + + Args: + now: The time to write. + modified: Whether the access modifies the storage. + with_other_changes: Whether the metadata is written anyway. + """ + write_modified_at = modified and (with_other_changes or self._is_due(self._modified_at, now)) + write_accessed_at = write_modified_at or with_other_changes or self._is_due(self._accessed_at, now) + + if write_modified_at: + self._modified_at = now + if write_accessed_at: + self._accessed_at = now + + return write_accessed_at, write_modified_at + + def reset(self) -> None: + """Forget the earlier writes, so that the next timestamps are written at once.""" + self._accessed_at = None + self._modified_at = None + + @staticmethod + def _is_due(last_written: datetime | None, now: datetime) -> bool: + # A clock set back makes the earlier write look as if it came from the future. + return last_written is None or now < last_written or now - last_written >= _TIMESTAMP_WRITE_INTERVAL + def batch_records_by_size( records: Iterable[KeyValueStoreRecordMetadata], diff --git a/src/crawlee/storage_backends/models.py b/src/crawlee/storage_backends/models.py index ce32543b43..55089596a6 100644 --- a/src/crawlee/storage_backends/models.py +++ b/src/crawlee/storage_backends/models.py @@ -32,13 +32,13 @@ class StorageMetadata(BaseModel): """The name of the storage.""" accessed_at: datetime - """The timestamp when the storage was last accessed.""" + """The approximate timestamp when the storage was last accessed.""" created_at: datetime """The timestamp when the storage was created.""" modified_at: datetime - """The timestamp when the storage was last modified.""" + """The approximate timestamp when the storage was last modified.""" @docs_group('Storage data') diff --git a/tests/unit/storage_backends/_file_system/test_fs_dataset_backend.py b/tests/unit/storage_backends/_file_system/test_fs_dataset_backend.py index 65502c2ff1..83d8d7ba1b 100644 --- a/tests/unit/storage_backends/_file_system/test_fs_dataset_backend.py +++ b/tests/unit/storage_backends/_file_system/test_fs_dataset_backend.py @@ -3,15 +3,19 @@ import asyncio import json import threading +from datetime import timedelta from pathlib import Path from typing import TYPE_CHECKING -from unittest.mock import Mock +from unittest.mock import DEFAULT, AsyncMock, Mock import pytest from crawlee._consts import METADATA_FILENAME +from crawlee._utils.file import atomic_write from crawlee.configuration import Configuration from crawlee.storage_backends import FileSystemStorageBackend +from crawlee.storage_backends._file_system import _dataset_backend +from crawlee.storage_backends.models import DatasetMetadata if TYPE_CHECKING: from collections.abc import AsyncGenerator @@ -166,44 +170,80 @@ async def test_push_after_drop_starts_from_one( assert 'File disappeared' not in caplog.text -async def test_metadata_file_updates(dataset_backend: FileSystemDatasetBackend) -> None: - """Test that metadata file is updated correctly after operations.""" - # Record initial timestamps +async def test_metadata_file_updates( + dataset_backend: FileSystemDatasetBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read writes `accessed_at` to the metadata file at most every 5 s, and a push writes both times at once.""" metadata = await dataset_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_dataset_backend, 'datetime', clock) + write_spy = AsyncMock(wraps=atomic_write) + monkeypatch.setattr(_dataset_backend, 'atomic_write', write_spy) + + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time + await dataset_backend.get_data() - # Perform an operation that updates accessed_at + write_spy.reset_mock() + clock.now.return_value = read_time + timedelta(seconds=4) await dataset_backend.get_data() + write_spy.assert_not_awaited() - # Verify timestamps metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_get = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform an operation that updates modified_at + # The second push comes within the interval of the first, but it writes the item count anyway. + clock.now.return_value = read_time + timedelta(seconds=4) + await dataset_backend.push_data([{'new': 'item'}]) + push_time = read_time + timedelta(seconds=5) + clock.now.return_value = push_time await dataset_backend.push_data([{'new': 'item'}]) - # Verify timestamps again metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_get + assert metadata.accessed_at == push_time + assert metadata.modified_at == push_time - # Verify metadata file is updated on disk with dataset_backend.path_to_metadata.open() as f: metadata_json = json.load(f) - assert metadata_json['itemCount'] == 1 + assert metadata_json['itemCount'] == 2 + + +async def test_read_after_failed_write_writes_metadata( + dataset_backend: FileSystemDatasetBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read right after a failed metadata file write writes the file with the timestamps of both.""" + metadata = await dataset_backend.get_metadata() + + clock = Mock() + monkeypatch.setattr(_dataset_backend, 'datetime', clock) + + def fail_metadata_write(path: Path, _data: str | bytes) -> object: + if path == dataset_backend.path_to_metadata: + raise OSError('No space left on device') + return DEFAULT + + write_spy = AsyncMock(wraps=atomic_write, side_effect=fail_metadata_write) + monkeypatch.setattr(_dataset_backend, 'atomic_write', write_spy) + + write_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = write_time + with pytest.raises(OSError, match='No space left on device'): + await dataset_backend.push_data([{'new': 'item'}]) + + write_spy.side_effect = None + read_time = write_time + timedelta(seconds=1) + clock.now.return_value = read_time + await dataset_backend.get_data() + + metadata = DatasetMetadata.model_validate_json(dataset_backend.path_to_metadata.read_text()) + assert metadata.accessed_at == read_time + assert metadata.modified_at == write_time async def test_data_persistence_across_reopens() -> None: diff --git a/tests/unit/storage_backends/_file_system/test_fs_kvs_backend.py b/tests/unit/storage_backends/_file_system/test_fs_kvs_backend.py index 6a54ecaa59..fa02d17c43 100644 --- a/tests/unit/storage_backends/_file_system/test_fs_kvs_backend.py +++ b/tests/unit/storage_backends/_file_system/test_fs_kvs_backend.py @@ -2,14 +2,17 @@ import asyncio import json +from datetime import timedelta from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, patch +from unittest.mock import DEFAULT, AsyncMock, Mock, patch import pytest from crawlee._consts import METADATA_FILENAME +from crawlee._utils.file import atomic_write from crawlee.configuration import Configuration from crawlee.storage_backends import FileSystemStorageBackend +from crawlee.storage_backends._file_system import _key_value_store_backend from crawlee.storage_backends.models import KeyValueStoreMetadata, KeyValueStoreRecordMetadata if TYPE_CHECKING: @@ -159,39 +162,89 @@ async def test_drop_removes_directory(kvs_backend: FileSystemKeyValueStoreBacken assert not kvs_backend.path_to_kvs.exists() -async def test_metadata_file_updates(kvs_backend: FileSystemKeyValueStoreBackend) -> None: - """Test that read/write operations properly update metadata file timestamps.""" - # Record initial timestamps +async def test_write_after_drop_writes_metadata(kvs_backend: FileSystemKeyValueStoreBackend) -> None: + """A write right after `drop()` creates the metadata file again.""" + await kvs_backend.set_value(key='first', value=b'first-value', content_type='text/plain') + await kvs_backend.drop() + + await kvs_backend.set_value(key='second', value=b'second-value', content_type='text/plain') + + assert kvs_backend.path_to_metadata.exists() + + +async def test_metadata_file_updates( + kvs_backend: FileSystemKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read writes `accessed_at` to the metadata file at most every 5 s, and a write both times at most every 5 s.""" metadata = await kvs_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_key_value_store_backend, 'datetime', clock) + write_spy = AsyncMock(wraps=atomic_write) + monkeypatch.setattr(_key_value_store_backend, 'atomic_write', write_spy) - # Perform a read operation + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time await kvs_backend.get_value(key='nonexistent') - # Verify accessed timestamp was updated + write_spy.reset_mock() + clock.now.return_value = read_time + timedelta(seconds=4) + await kvs_backend.get_value(key='nonexistent') + write_spy.assert_not_awaited() + metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_read = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform a write operation + write_time = read_time + timedelta(seconds=4) + clock.now.return_value = write_time await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') - # Verify modified timestamp was updated + write_spy.reset_mock() + clock.now.return_value = write_time + timedelta(seconds=1) + await kvs_backend.set_value(key='test', value=b'new-value', content_type='text/plain') + written_paths = [write_call.args[0] for write_call in write_spy.await_args_list] + assert kvs_backend.path_to_metadata not in written_paths + metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_read + assert metadata.accessed_at == write_time + assert metadata.modified_at == write_time + + +async def test_read_after_failed_write_writes_metadata( + kvs_backend: FileSystemKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read right after a failed metadata file write writes the file with the timestamps of both.""" + metadata = await kvs_backend.get_metadata() + + clock = Mock() + monkeypatch.setattr(_key_value_store_backend, 'datetime', clock) + + def fail_metadata_write(path: Path, _data: str | bytes) -> object: + if path == kvs_backend.path_to_metadata: + raise OSError('No space left on device') + return DEFAULT + + write_spy = AsyncMock(wraps=atomic_write, side_effect=fail_metadata_write) + monkeypatch.setattr(_key_value_store_backend, 'atomic_write', write_spy) + + write_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = write_time + with pytest.raises(OSError, match='No space left on device'): + await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') + + write_spy.side_effect = None + read_time = write_time + timedelta(seconds=1) + clock.now.return_value = read_time + await kvs_backend.get_value(key='test') + + metadata = KeyValueStoreMetadata.model_validate_json(kvs_backend.path_to_metadata.read_text()) + assert metadata.accessed_at == read_time + assert metadata.modified_at == write_time async def test_data_persistence_across_reopens(configuration: Configuration) -> None: diff --git a/tests/unit/storage_backends/_file_system/test_fs_rq_backend.py b/tests/unit/storage_backends/_file_system/test_fs_rq_backend.py index 8e8da18583..4fe7d5ed3b 100644 --- a/tests/unit/storage_backends/_file_system/test_fs_rq_backend.py +++ b/tests/unit/storage_backends/_file_system/test_fs_rq_backend.py @@ -1,15 +1,17 @@ from __future__ import annotations -import asyncio import json +from datetime import timedelta from typing import TYPE_CHECKING -from unittest.mock import patch +from unittest.mock import DEFAULT, AsyncMock, Mock, patch import pytest from crawlee import Request, service_locator +from crawlee._utils.file import atomic_write from crawlee.configuration import Configuration from crawlee.storage_backends import FileSystemStorageBackend, MemoryStorageBackend +from crawlee.storage_backends._file_system import _request_queue_backend from crawlee.storage_backends.models import RequestQueueMetadata from crawlee.storages import KeyValueStore @@ -130,44 +132,87 @@ async def test_drop_removes_directory(rq_backend: FileSystemRequestQueueBackend) assert not rq_path.exists() -async def test_metadata_file_updates(rq_backend: FileSystemRequestQueueBackend) -> None: - """Test that metadata file is updated correctly after operations.""" - # Record initial timestamps +async def test_metadata_file_updates( + rq_backend: FileSystemRequestQueueBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read writes `accessed_at` at most every 5 s, and an add both times, at once when it changes the counts.""" metadata = await rq_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_request_queue_backend, 'datetime', clock) + write_spy = AsyncMock(wraps=atomic_write) + monkeypatch.setattr(_request_queue_backend, 'atomic_write', write_spy) - # Perform a read operation + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time await rq_backend.is_empty() - - # Verify accessed timestamp was updated metadata = await rq_backend.get_metadata() - assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed assert metadata.modified_at == initial_modified - accessed_after_read = metadata.accessed_at + add_time = read_time + timedelta(seconds=1) + clock.now.return_value = add_time + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + write_spy.reset_mock() + clock.now.return_value = add_time + timedelta(seconds=1) + await rq_backend.get_request('https://example.com/1') + write_spy.assert_not_awaited() - # Perform a write operation - await rq_backend.add_batch_of_requests([Request.from_url('https://example.com')]) + metadata = await rq_backend.get_metadata() + assert metadata.accessed_at == add_time + + second_add_time = add_time + timedelta(seconds=2) + clock.now.return_value = second_add_time + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/2')]) + + # An add of a known request leaves the counts as they are. + write_spy.reset_mock() + clock.now.return_value = add_time + timedelta(seconds=3) + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) + write_spy.assert_not_awaited() - # Verify modified timestamp was updated metadata = await rq_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_read + assert metadata.accessed_at == second_add_time + assert metadata.modified_at == second_add_time - # Verify metadata file is updated on disk with rq_backend.path_to_metadata.open() as f: metadata_json = json.load(f) - assert metadata_json['totalRequestCount'] == 1 + assert metadata_json['totalRequestCount'] == 2 + + +async def test_read_after_failed_write_writes_metadata( + rq_backend: FileSystemRequestQueueBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read right after a failed metadata file write writes the file with the timestamps of both.""" + metadata = await rq_backend.get_metadata() + + clock = Mock() + monkeypatch.setattr(_request_queue_backend, 'datetime', clock) + + def fail_metadata_write(path: Path, _data: str | bytes) -> object: + if path == rq_backend.path_to_metadata: + raise OSError('No space left on device') + return DEFAULT + + write_spy = AsyncMock(wraps=atomic_write, side_effect=fail_metadata_write) + monkeypatch.setattr(_request_queue_backend, 'atomic_write', write_spy) + + write_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = write_time + with pytest.raises(OSError, match='No space left on device'): + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) + + write_spy.side_effect = None + read_time = write_time + timedelta(seconds=1) + clock.now.return_value = read_time + await rq_backend.is_empty() + + metadata = RequestQueueMetadata.model_validate_json(rq_backend.path_to_metadata.read_text()) + assert metadata.accessed_at == read_time + assert metadata.modified_at == write_time async def test_data_persistence_across_reopens() -> None: diff --git a/tests/unit/storage_backends/_redis/test_redis_dataset_backend.py b/tests/unit/storage_backends/_redis/test_redis_dataset_backend.py index b283c511b8..8aaf9bc657 100644 --- a/tests/unit/storage_backends/_redis/test_redis_dataset_backend.py +++ b/tests/unit/storage_backends/_redis/test_redis_dataset_backend.py @@ -1,14 +1,15 @@ from __future__ import annotations -import asyncio import logging +from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, Mock, patch import pytest from redis.exceptions import RedisError from crawlee.storage_backends import RedisStorageBackend +from crawlee.storage_backends._redis import _backend_mixin from crawlee.storage_backends._redis._utils import await_redis_response if TYPE_CHECKING: @@ -145,39 +146,38 @@ async def test_drop_preserves_sibling_index_entries( assert (await reopened.get_metadata()).id == sibling_metadata.id -async def test_metadata_record_updates(dataset_backend: RedisDatasetBackend) -> None: - """Test that metadata record is updated correctly after operations.""" - # Record initial timestamps +async def test_metadata_record_updates(dataset_backend: RedisDatasetBackend, monkeypatch: pytest.MonkeyPatch) -> None: + """A read stamps `accessed_at` at most every 5 s, and a push stamps both times at once.""" + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) + + # Opening the storage stamps an access too, so the clock starts after its interval. `get_metadata()` reads the + # record before stamping its own access, so it reports the earlier stamps. + read_time = datetime.now(UTC) + timedelta(seconds=5) + clock.now.return_value = read_time metadata = await dataset_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform an operation that updates accessed_at + clock.now.return_value = read_time + timedelta(seconds=4) await dataset_backend.get_data() - # Verify timestamps metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_get = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform an operation that updates modified_at + # The second push comes within the interval of the first, but it updates the item count anyway. + clock.now.return_value = read_time + timedelta(seconds=4) + await dataset_backend.push_data([{'new': 'item'}]) + push_time = read_time + timedelta(seconds=5) + clock.now.return_value = push_time await dataset_backend.push_data([{'new': 'item'}]) - # Verify timestamps again metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_get + assert metadata.accessed_at == push_time + assert metadata.modified_at == push_time async def test_error_handling_on_push_failure(dataset_backend: RedisDatasetBackend) -> None: diff --git a/tests/unit/storage_backends/_redis/test_redis_kvs_backend.py b/tests/unit/storage_backends/_redis/test_redis_kvs_backend.py index 584f6b0f7a..b22fe354d3 100644 --- a/tests/unit/storage_backends/_redis/test_redis_kvs_backend.py +++ b/tests/unit/storage_backends/_redis/test_redis_kvs_backend.py @@ -1,9 +1,10 @@ from __future__ import annotations -import asyncio import json +from datetime import UTC, datetime, timedelta +from itertools import chain, repeat from typing import TYPE_CHECKING, Any -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import DEFAULT, AsyncMock, MagicMock, Mock, patch import pytest from fakeredis import FakeAsyncRedis @@ -12,7 +13,7 @@ from crawlee.configuration import Configuration from crawlee.storage_backends import RedisStorageBackend -from crawlee.storage_backends._redis import RedisKeyValueStoreBackend +from crawlee.storage_backends._redis import RedisKeyValueStoreBackend, _backend_mixin from crawlee.storage_backends._redis._utils import await_redis_response if TYPE_CHECKING: @@ -170,39 +171,60 @@ async def test_drop_removes_keys(kvs_backend: RedisKeyValueStoreBackend) -> None assert await await_redis_response(kvs_backend.redis.exists('key_value_stores:test_kvs:keys')) == 0 -async def test_metadata_record_updates(kvs_backend: RedisKeyValueStoreBackend) -> None: - """Test that read/write operations properly update metadata file timestamps.""" - # Record initial timestamps +async def test_metadata_record_updates(kvs_backend: RedisKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch) -> None: + """A read stamps `accessed_at` at most every 5 s, and a write both times at most every 5 s.""" + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) + + # Opening the storage stamps an access too, so the clock starts after its interval. `get_metadata()` reads the + # record before stamping its own access, so it reports the earlier stamps. + read_time = datetime.now(UTC) + timedelta(seconds=5) + clock.now.return_value = read_time metadata = await kvs_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform a read operation + clock.now.return_value = read_time + timedelta(seconds=4) await kvs_backend.get_value(key='nonexistent') - # Verify accessed timestamp was updated metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_read = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform a write operation + write_time = read_time + timedelta(seconds=4) + clock.now.return_value = write_time await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') + clock.now.return_value = write_time + timedelta(seconds=1) + await kvs_backend.set_value(key='test', value=b'new-value', content_type='text/plain') - # Verify modified timestamp was updated metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_read + assert metadata.accessed_at == write_time + assert metadata.modified_at == write_time + + +async def test_retried_write_records_timestamps( + kvs_backend: RedisKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A write retried after a failed transaction stamps both timestamps.""" + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) + + # Opening the storage stamps an access too, so the clock starts after its interval. + write_time = datetime.now(UTC) + timedelta(seconds=5) + clock.now.return_value = write_time + + execute_effects = chain([RedisError('connection lost')], repeat(DEFAULT)) + with ( + patch('crawlee._utils.retry._retry_sleep', new_callable=AsyncMock), + patch.object(Pipeline, 'execute', autospec=True, side_effect=execute_effects, wraps=Pipeline.execute), + ): + await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') + + metadata = await kvs_backend.get_metadata() + assert metadata.accessed_at == write_time + assert metadata.modified_at == write_time async def test_error_handling_on_set_failure(kvs_backend: RedisKeyValueStoreBackend) -> None: diff --git a/tests/unit/storage_backends/_redis/test_redis_rq_backend.py b/tests/unit/storage_backends/_redis/test_redis_rq_backend.py index 004292006d..62cdd9af4c 100644 --- a/tests/unit/storage_backends/_redis/test_redis_rq_backend.py +++ b/tests/unit/storage_backends/_redis/test_redis_rq_backend.py @@ -203,43 +203,39 @@ async def test_drop_removes_records(rq_backend: RedisRequestQueueBackend) -> Non async def test_metadata_record_updates(rq_backend: RedisRequestQueueBackend, monkeypatch: pytest.MonkeyPatch) -> None: - """Fetching bumps only `accessed_at`, adding requests bumps `modified_at` too, and `created_at` never changes.""" - metadata = await rq_backend.get_metadata() - initial_created = metadata.created_at - initial_modified = metadata.modified_at - + """A fetch stamps `accessed_at` at most every 5 s, and an add both times at most every 5 s.""" # Stamp the metadata updates from a controlled clock, so the checks don't depend on the wall clock resolution. clock = Mock() monkeypatch.setattr(_backend_mixin, 'datetime', clock) - read_time = metadata.accessed_at + timedelta(seconds=1) + # Opening the storage stamps an access too, so the clock starts after its interval. `get_metadata()` reads the + # record before stamping its own access, so it reports the earlier stamps. + read_time = datetime.now(UTC) + timedelta(seconds=5) clock.now.return_value = read_time + metadata = await rq_backend.get_metadata() + initial_created = metadata.created_at + initial_modified = metadata.modified_at + + clock.now.return_value = read_time + timedelta(seconds=4) await rq_backend.fetch_next_request() - # `get_metadata()` reads the record before stamping its own access, so it reports the fetch's stamp. metadata = await rq_backend.get_metadata() assert metadata.created_at == initial_created assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - write_time = read_time + timedelta(seconds=1) + # The add counts the new requests in a script of its own, so it stamps the times on their own too. + write_time = read_time + timedelta(seconds=4) clock.now.return_value = write_time - await rq_backend.add_batch_of_requests([Request.from_url('https://example.com')]) + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) + clock.now.return_value = write_time + timedelta(seconds=1) + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/2')]) metadata = await rq_backend.get_metadata() assert metadata.created_at == initial_created assert metadata.accessed_at == write_time assert metadata.modified_at == write_time - # An add of a request already in the queue stamps both times too. - duplicate_time = write_time + timedelta(seconds=1) - clock.now.return_value = duplicate_time - await rq_backend.add_batch_of_requests([Request.from_url('https://example.com')]) - - metadata = await rq_backend.get_metadata() - assert metadata.accessed_at == duplicate_time - assert metadata.modified_at == duplicate_time - async def test_get_request(rq_backend: RedisRequestQueueBackend) -> None: """Test that get_request works correctly.""" diff --git a/tests/unit/storage_backends/_sql/test_sql_dataset_backend.py b/tests/unit/storage_backends/_sql/test_sql_dataset_backend.py index 85a66a4579..8010f001cb 100644 --- a/tests/unit/storage_backends/_sql/test_sql_dataset_backend.py +++ b/tests/unit/storage_backends/_sql/test_sql_dataset_backend.py @@ -1,9 +1,9 @@ from __future__ import annotations -import asyncio import logging +from datetime import timedelta from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock, Mock, patch import pytest from sqlalchemy import func, inspect, select @@ -12,6 +12,7 @@ from crawlee.configuration import Configuration from crawlee.storage_backends import SqlStorageBackend +from crawlee.storage_backends._sql import _backend_mixin from crawlee.storage_backends._sql._db_models import DatasetItemDb, DatasetMetadataBufferDb, DatasetMetadataDb if TYPE_CHECKING: @@ -169,48 +170,38 @@ async def test_drop_removes_records(dataset_backend: SqlDatasetBackend) -> None: assert metadata is None -async def test_metadata_record_updates(dataset_backend: SqlDatasetBackend) -> None: - """Test that metadata record is updated correctly after operations.""" - # Record initial timestamps +async def test_metadata_record_updates(dataset_backend: SqlDatasetBackend, monkeypatch: pytest.MonkeyPatch) -> None: + """A read records `accessed_at` at most every 5 s, and a push records both times at once.""" metadata = await dataset_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) - # Perform an operation that updates accessed_at + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time + await dataset_backend.get_data() + clock.now.return_value = read_time + timedelta(seconds=4) await dataset_backend.get_data() - # Verify timestamps metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_get = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform an operation that updates modified_at + # The second push comes within the interval of the first, but it records the item count anyway. + clock.now.return_value = read_time + timedelta(seconds=4) + await dataset_backend.push_data([{'new': 'item'}]) + push_time = read_time + timedelta(seconds=5) + clock.now.return_value = push_time await dataset_backend.push_data([{'new': 'item'}]) - # Verify timestamps again metadata = await dataset_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_get - - # Verify metadata record is updated in db - async with dataset_backend.get_session() as session: - orm_metadata = await session.get(DatasetMetadataDb, metadata.id) - assert orm_metadata is not None - orm_metadata.item_count = 1 - assert orm_metadata.created_at == initial_created - assert orm_metadata.accessed_at == metadata.accessed_at - assert orm_metadata.modified_at == metadata.modified_at + assert metadata.accessed_at == push_time + assert metadata.modified_at == push_time + assert metadata.item_count == 2 async def test_data_persistence_across_reopens(configuration: Configuration) -> None: diff --git a/tests/unit/storage_backends/_sql/test_sql_kvs_backend.py b/tests/unit/storage_backends/_sql/test_sql_kvs_backend.py index b645ea86b1..b87ad31c23 100644 --- a/tests/unit/storage_backends/_sql/test_sql_kvs_backend.py +++ b/tests/unit/storage_backends/_sql/test_sql_kvs_backend.py @@ -1,16 +1,18 @@ from __future__ import annotations -import asyncio +from datetime import timedelta +from itertools import chain, repeat from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, patch +from unittest.mock import DEFAULT, AsyncMock, Mock, patch import pytest from sqlalchemy import inspect, select -from sqlalchemy.exc import SQLAlchemyError -from sqlalchemy.ext.asyncio import create_async_engine +from sqlalchemy.exc import OperationalError, SQLAlchemyError +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from crawlee.configuration import Configuration from crawlee.storage_backends import SqlStorageBackend +from crawlee.storage_backends._sql import _backend_mixin from crawlee.storage_backends._sql._db_models import KeyValueStoreMetadataDb, KeyValueStoreRecordDb from crawlee.storage_backends.models import KeyValueStoreMetadata @@ -202,46 +204,59 @@ async def test_drop_removes_records(kvs_backend: SqlKeyValueStoreBackend) -> Non assert metadata is None -async def test_metadata_record_updates(kvs_backend: SqlKeyValueStoreBackend) -> None: - """Test that read/write operations properly update metadata record timestamps.""" - # Record initial timestamps +async def test_metadata_record_updates(kvs_backend: SqlKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch) -> None: + """A read records `accessed_at` at most every 5 s, and a write both times at most every 5 s.""" metadata = await kvs_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) - # Perform a read operation + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time + await kvs_backend.get_value(key='nonexistent') + clock.now.return_value = read_time + timedelta(seconds=4) await kvs_backend.get_value(key='nonexistent') - # Verify accessed timestamp was updated metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_read = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) - - # Perform a write operation + write_time = read_time + timedelta(seconds=4) + clock.now.return_value = write_time await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') + clock.now.return_value = write_time + timedelta(seconds=1) + await kvs_backend.set_value(key='test', value=b'new-value', content_type='text/plain') - # Verify modified timestamp was updated metadata = await kvs_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_read + assert metadata.accessed_at == write_time + assert metadata.modified_at == write_time - async with kvs_backend.get_session() as session: - orm_metadata = await session.get(KeyValueStoreMetadataDb, metadata.id) - assert orm_metadata is not None - assert orm_metadata.created_at == metadata.created_at - assert orm_metadata.accessed_at == metadata.accessed_at - assert orm_metadata.modified_at == metadata.modified_at + +async def test_retried_write_records_timestamps( + kvs_backend: SqlKeyValueStoreBackend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A write retried after a failed commit records both timestamps.""" + metadata = await kvs_backend.get_metadata() + + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) + write_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = write_time + + commit_effects = chain([OperationalError('COMMIT', None, Exception('database is locked'))], repeat(DEFAULT)) + with ( + patch('crawlee._utils.retry._retry_sleep', new_callable=AsyncMock), + patch.object(AsyncSession, 'commit', autospec=True, side_effect=commit_effects, wraps=AsyncSession.commit), + ): + await kvs_backend.set_value(key='test', value=b'test-value', content_type='text/plain') + + metadata = await kvs_backend.get_metadata() + assert metadata.accessed_at == write_time + assert metadata.modified_at == write_time async def test_data_persistence_across_reopens(configuration: Configuration) -> None: diff --git a/tests/unit/storage_backends/_sql/test_sql_rq_backend.py b/tests/unit/storage_backends/_sql/test_sql_rq_backend.py index 16961505f7..9b5b3fd46b 100644 --- a/tests/unit/storage_backends/_sql/test_sql_rq_backend.py +++ b/tests/unit/storage_backends/_sql/test_sql_rq_backend.py @@ -14,6 +14,7 @@ from crawlee import Request from crawlee.configuration import Configuration from crawlee.storage_backends import SqlStorageBackend +from crawlee.storage_backends._sql import _backend_mixin from crawlee.storage_backends._sql._db_models import RequestDb, RequestQueueMetadataDb from crawlee.storage_backends.models import RequestQueueMetadata @@ -233,46 +234,41 @@ async def test_drop_removes_records(rq_backend: SqlRequestQueueBackend) -> None: assert db_metadata is None -async def test_metadata_record_updates(rq_backend: SqlRequestQueueBackend) -> None: - """Test that metadata record updates correctly after operations.""" - # Record initial timestamps +async def test_metadata_record_updates(rq_backend: SqlRequestQueueBackend, monkeypatch: pytest.MonkeyPatch) -> None: + """A read records `accessed_at` at most every 5 s, and an add both times, at once when it adds requests.""" metadata = await rq_backend.get_metadata() initial_created = metadata.created_at - initial_accessed = metadata.accessed_at initial_modified = metadata.modified_at - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + clock = Mock() + monkeypatch.setattr(_backend_mixin, 'datetime', clock) - # Perform a read operation + read_time = metadata.accessed_at + timedelta(seconds=1) + clock.now.return_value = read_time + await rq_backend.is_empty() + clock.now.return_value = read_time + timedelta(seconds=4) await rq_backend.is_empty() - # Verify accessed timestamp was updated metadata = await rq_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.accessed_at > initial_accessed + assert metadata.accessed_at == read_time assert metadata.modified_at == initial_modified - accessed_after_read = metadata.accessed_at - - # Wait a moment to ensure timestamps can change - await asyncio.sleep(0.01) + # The second add comes within the interval of the first, but it records the new request anyway. + clock.now.return_value = read_time + timedelta(seconds=4) + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) + add_time = read_time + timedelta(seconds=5) + clock.now.return_value = add_time + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/2')]) - # Perform a write operation - await rq_backend.add_batch_of_requests([Request.from_url('https://example.com')]) + # An add of a known request records nothing new. + clock.now.return_value = read_time + timedelta(seconds=6) + await rq_backend.add_batch_of_requests([Request.from_url('https://example.com/1')]) - # Verify modified timestamp was updated metadata = await rq_backend.get_metadata() assert metadata.created_at == initial_created - assert metadata.modified_at > initial_modified - assert metadata.accessed_at > accessed_after_read - - async with rq_backend.get_session() as session: - orm_metadata = await session.get(RequestQueueMetadataDb, metadata.id) - assert orm_metadata is not None - assert orm_metadata.created_at == metadata.created_at - assert orm_metadata.accessed_at == metadata.accessed_at - assert orm_metadata.modified_at == metadata.modified_at + assert metadata.accessed_at == add_time + assert metadata.modified_at == add_time async def test_data_persistence_across_reopens(configuration: Configuration) -> None: diff --git a/tests/unit/storage_backends/test_timestamp_throttle.py b/tests/unit/storage_backends/test_timestamp_throttle.py new file mode 100644 index 0000000000..cce64201bc --- /dev/null +++ b/tests/unit/storage_backends/test_timestamp_throttle.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import pytest + +from crawlee.storage_backends._utils import TimestampThrottle + +_START = datetime(2026, 1, 1, tzinfo=UTC) + + +def _to_write(throttle: TimestampThrottle, seconds: int, call: str) -> tuple[bool, bool]: + return throttle.to_write( + _START + timedelta(seconds=seconds), + modified=call.startswith('modification'), + with_other_changes=call.endswith('with other changes'), + ) + + +@pytest.mark.parametrize( + ('earlier_calls', 'call', 'expected'), + [ + pytest.param([], (0, 'access'), (True, False), id='first access'), + pytest.param([], (0, 'modification'), (True, True), id='first modification'), + pytest.param([(0, 'access')], (4, 'access'), (False, False), id='access within the interval'), + pytest.param([(0, 'access')], (5, 'access'), (True, False), id='access after the interval'), + pytest.param([(0, 'access')], (1, 'modification'), (True, True), id='modification after an access'), + pytest.param([(0, 'access')], (-1, 'access'), (True, False), id='access after the clock was set back'), + pytest.param( + [(0, 'access'), (3, 'modification')], + (7, 'access'), + (False, False), + id='modification restarts the access interval', + ), + pytest.param([(0, 'modification')], (4, 'modification'), (False, False), id='modification within the interval'), + pytest.param([(0, 'modification')], (5, 'modification'), (True, True), id='modification after the interval'), + pytest.param([(0, 'access')], (1, 'access with other changes'), (True, False), id='access with other changes'), + pytest.param( + [(0, 'modification')], + (1, 'modification with other changes'), + (True, True), + id='modification with other changes', + ), + ], +) +def test_timestamps_throttled_per_interval( + earlier_calls: list[tuple[int, str]], call: tuple[int, str], expected: tuple[bool, bool] +) -> None: + """Each timestamp is written at most every 5 s on its own, and always with other metadata changes.""" + throttle = TimestampThrottle() + for seconds, earlier_call in earlier_calls: + _to_write(throttle, seconds, earlier_call) + + assert _to_write(throttle, *call) == expected + + +def test_reset_writes_next_timestamps_at_once() -> None: + """After `reset`, both timestamps are written at once, also within the interval of the earlier writes.""" + throttle = TimestampThrottle() + throttle.to_write(_START, modified=True) + throttle.reset() + + assert throttle.to_write(_START + timedelta(seconds=1), modified=True) == (True, True) diff --git a/tests/unit/storages/conftest.py b/tests/unit/storages/conftest.py index 406987e51a..59b63716e2 100644 --- a/tests/unit/storages/conftest.py +++ b/tests/unit/storages/conftest.py @@ -1,7 +1,9 @@ from __future__ import annotations +from datetime import UTC, datetime from importlib.util import find_spec from typing import TYPE_CHECKING +from unittest.mock import Mock import pytest @@ -20,6 +22,22 @@ from fakeredis import FakeAsyncRedis +_METADATA_TIMESTAMP_MODULES = [ + 'crawlee.storage_backends._memory._dataset_backend', + 'crawlee.storage_backends._memory._key_value_store_backend', + 'crawlee.storage_backends._memory._request_queue_backend', + 'crawlee.storage_backends._file_system._dataset_backend', + 'crawlee.storage_backends._file_system._key_value_store_backend', + 'crawlee.storage_backends._file_system._request_queue_backend', + 'crawlee.storage_backends._sql._backend_mixin', + 'crawlee.storage_backends._sql._dataset_backend', + 'crawlee.storage_backends._sql._key_value_store_backend', + 'crawlee.storage_backends._sql._request_queue_backend', + 'crawlee.storage_backends._redis._backend_mixin', + 'crawlee.storage_backends._redis._request_queue_backend', +] + + def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: """Skip the Redis request queue cases when `lupa` is missing, since the Redis RQ backend runs Lua scripts.""" if find_spec('lupa') is not None: @@ -53,3 +71,13 @@ async def storage_backend( if isinstance(storage_backend, SqlStorageBackend): await storage_backend.close() + + +@pytest.fixture +def metadata_clock(monkeypatch: pytest.MonkeyPatch) -> Mock: + """A clock, starting now, that the built-in storage backends take their metadata timestamps from.""" + clock = Mock() + clock.now.return_value = datetime.now(UTC) + for module in _METADATA_TIMESTAMP_MODULES: + monkeypatch.setattr(f'{module}.datetime', clock) + return clock diff --git a/tests/unit/storages/test_dataset.py b/tests/unit/storages/test_dataset.py index 62b6f65339..d607a7c53d 100644 --- a/tests/unit/storages/test_dataset.py +++ b/tests/unit/storages/test_dataset.py @@ -2,10 +2,10 @@ import logging from collections import UserString, deque -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from types import MappingProxyType from typing import TYPE_CHECKING -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest @@ -686,6 +686,25 @@ async def test_purge( await dataset.drop() +async def test_purge_updates_timestamps_at_once(storage_backend: StorageBackend, metadata_clock: Mock) -> None: + """A purge updates both timestamps at once, also on an empty dataset right after another purge.""" + dataset = await Dataset.open(name='purge-timestamps', storage_backend=storage_backend) + start = metadata_clock.now.return_value + await dataset.push_data({'id': 1}) + + metadata_clock.now.return_value = start + timedelta(seconds=1) + await dataset.purge() + + # The second purge finds the dataset empty, so it changes no count. + purge_time = start + timedelta(seconds=2) + metadata_clock.now.return_value = purge_time + await dataset.purge() + + metadata = await dataset.get_metadata() + assert metadata.accessed_at == purge_time + assert metadata.modified_at == purge_time + + async def test_open_with_alias( storage_backend: StorageBackend, ) -> None: diff --git a/tests/unit/storages/test_key_value_store.py b/tests/unit/storages/test_key_value_store.py index b2d46488fc..0f7382c6e9 100644 --- a/tests/unit/storages/test_key_value_store.py +++ b/tests/unit/storages/test_key_value_store.py @@ -2,9 +2,9 @@ import asyncio import json -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest from pydantic import BaseModel, Field, ValidationError @@ -941,6 +941,21 @@ async def test_purge( await kvs.drop() +async def test_purge_updates_timestamps_at_once(storage_backend: StorageBackend, metadata_clock: Mock) -> None: + """A purge updates both timestamps at once, also right after a write.""" + kvs = await KeyValueStore.open(name='purge-timestamps', storage_backend=storage_backend) + start = metadata_clock.now.return_value + await kvs.set_value('key', 'value') + + purge_time = start + timedelta(seconds=1) + metadata_clock.now.return_value = purge_time + await kvs.purge() + + metadata = await kvs.get_metadata() + assert metadata.accessed_at == purge_time + assert metadata.modified_at == purge_time + + async def test_record_exists_nonexistent(kvs: KeyValueStore) -> None: """Test that record_exists returns False for a nonexistent key.""" result = await kvs.record_exists('nonexistent-key') diff --git a/tests/unit/storages/test_request_queue.py b/tests/unit/storages/test_request_queue.py index 0896a75774..a283046f60 100644 --- a/tests/unit/storages/test_request_queue.py +++ b/tests/unit/storages/test_request_queue.py @@ -3,7 +3,7 @@ import asyncio from datetime import timedelta from typing import TYPE_CHECKING -from unittest.mock import AsyncMock, call, create_autospec, patch +from unittest.mock import AsyncMock, Mock, call, create_autospec, patch import pytest @@ -824,6 +824,25 @@ async def test_purge( await rq.drop() +async def test_purge_updates_timestamps_at_once(storage_backend: StorageBackend, metadata_clock: Mock) -> None: + """A purge updates both timestamps at once, also on an empty queue right after another purge.""" + rq = await RequestQueue.open(name='purge-timestamps', storage_backend=storage_backend) + start = metadata_clock.now.return_value + await rq.add_request('https://example.com') + + metadata_clock.now.return_value = start + timedelta(seconds=1) + await rq.purge() + + # The second purge finds the queue empty, so it changes no count. + purge_time = start + timedelta(seconds=2) + metadata_clock.now.return_value = purge_time + await rq.purge() + + metadata = await rq.get_metadata() + assert metadata.accessed_at == purge_time + assert metadata.modified_at == purge_time + + @pytest.mark.parametrize( 'name', [