diff --git a/pyiceberg/io/content_cache.py b/pyiceberg/io/content_cache.py index 776b055497..73a4a3e080 100644 --- a/pyiceberg/io/content_cache.py +++ b/pyiceberg/io/content_cache.py @@ -18,14 +18,20 @@ from __future__ import annotations +import threading import time from collections import OrderedDict from collections.abc import Callable +from typing import Any +from pyiceberg.utils.transient import _TransientStateMixin -class ContentCache: + +class ContentCache(_TransientStateMixin): """Cache file contents by location, bounded by total size and by entry age. + Scan planning reads manifests from several threads, so every public method holds a lock. + Args: max_total_bytes: The maximum number of bytes to keep across all entries. max_content_length: Entries larger than this are not cached. @@ -33,6 +39,8 @@ class ContentCache: clock: Returns the current time in seconds, replaced in tests. """ + _transient_attrs = ("_lock",) + def __init__( self, max_total_bytes: int, @@ -46,39 +54,53 @@ def __init__( self._clock = clock self._entries: OrderedDict[str, tuple[bytes, float]] = OrderedDict() self._total_bytes = 0 + self._init_transient() + + def _init_transient(self) -> None: + self._lock = threading.Lock() def get(self, location: str) -> bytes | None: """Return the cached bytes for a location, or None when absent or expired.""" - entry = self._entries.get(location) - if entry is None: - return None + with self._lock: + entry = self._entries.get(location) + if entry is None: + return None - data, inserted_at = entry - if self._clock() - inserted_at >= self.expiration_interval_seconds: - self._remove(location) - return None + data, inserted_at = entry + if self._clock() - inserted_at >= self.expiration_interval_seconds: + self._remove(location) + return None - self._entries.move_to_end(location) - return data + self._entries.move_to_end(location) + return data def put(self, location: str, data: bytes) -> None: """Cache the bytes for a location, evicting the least recently used entries when needed.""" if len(data) > self.max_content_length or len(data) > self.max_total_bytes or self.max_content_length <= 0: return - self._remove(location) - self._purge_expired() - while self._entries and self._total_bytes + len(data) > self.max_total_bytes: - _, (evicted, _) = self._entries.popitem(last=False) - self._total_bytes -= len(evicted) + with self._lock: + self._remove(location) + self._purge_expired() + while self._entries and self._total_bytes + len(data) > self.max_total_bytes: + _, (evicted, _) = self._entries.popitem(last=False) + self._total_bytes -= len(evicted) - self._entries[location] = (data, self._clock()) - self._total_bytes += len(data) + self._entries[location] = (data, self._clock()) + self._total_bytes += len(data) def clear(self) -> None: """Remove every entry.""" - self._entries.clear() - self._total_bytes = 0 + with self._lock: + self._entries.clear() + self._total_bytes = 0 + + def __getstate__(self) -> dict[str, Any]: + """Return the entries and byte count as of one moment, without the lock.""" + with self._lock: + state = super().__getstate__() + state["_entries"] = self._entries.copy() + return state def _remove(self, location: str) -> None: entry = self._entries.pop(location, None) diff --git a/tests/io/test_content_cache.py b/tests/io/test_content_cache.py index ce52d37465..9533951dfe 100644 --- a/tests/io/test_content_cache.py +++ b/tests/io/test_content_cache.py @@ -14,6 +14,11 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import pickle +import sys +import threading +import time +from concurrent.futures import ThreadPoolExecutor from unittest.mock import patch import pyarrow as pa @@ -28,6 +33,7 @@ IO_MANIFEST_CACHE_MAX_TOTAL_BYTES_DEFAULT, ) from pyiceberg.io.content_cache import ContentCache +from pyiceberg.io.fsspec import FsspecFileIO from pyiceberg.io.pyarrow import PyArrowFileIO @@ -97,6 +103,75 @@ def test_cache_expires_entries() -> None: assert cache.get("a") is None +def test_cache_is_thread_safe() -> None: + # Too small for all files and short-lived, so entries are evicted and expire while other threads read them + cache = ContentCache(max_total_bytes=160, max_content_length=10, expiration_interval_ms=5) + + def read_through_cache() -> None: + for i in range(4_000): + location = f"manifest-{i % 50}.avro" + if cache.get(location) is None: + cache.put(location, b"1234") + + def clear_cache() -> None: + for _ in range(400): + cache.clear() + time.sleep(0.0005) + + switch_interval = sys.getswitchinterval() + # Switch threads often, so the cache operations of the threads interleave + sys.setswitchinterval(1e-6) + try: + with ThreadPoolExecutor(max_workers=3) as executor: + futures = [executor.submit(task) for task in (read_through_cache, read_through_cache, clear_cache)] + for future in futures: + future.result() + finally: + sys.setswitchinterval(switch_interval) + + +def test_cache_is_kept_when_file_io_is_pickled() -> None: + properties = {IO_MANIFEST_CACHE_ENABLED: "true"} + for file_io in (PyArrowFileIO(properties), FsspecFileIO(properties)): + cache = file_io.content_cache + assert cache is not None + cache.put("a", b"123") + + restored = pickle.loads(pickle.dumps(file_io)).content_cache + + assert restored is not None + assert restored.get("a") == b"123" + + +def test_cache_is_consistent_when_pickled_during_updates() -> None: + cache = ContentCache(max_total_bytes=160, max_content_length=10, expiration_interval_ms=60_000) + stop = threading.Event() + + def update_cache() -> None: + i = 0 + while not stop.is_set(): + cache.put(f"manifest-{i % 50}.avro", b"1234") + i += 1 + if i % 100 == 0: + cache.clear() + + switch_interval = sys.getswitchinterval() + # Switch threads often, so pickling interleaves with the updates + sys.setswitchinterval(1e-6) + updater = threading.Thread(target=update_cache) + updater.start() + try: + restored = [pickle.loads(pickle.dumps(cache)) for _ in range(2_000)] + finally: + stop.set() + updater.join() + sys.setswitchinterval(switch_interval) + + for copy in restored: + assert copy._total_bytes == sum(len(data) for data, _ in copy._entries.values()) + assert copy._total_bytes <= 160 + + def test_manifest_list_is_read_once(catalog: Catalog) -> None: catalog.create_namespace("default") table = catalog.create_table("default.cached_manifest_list", schema=pa.schema([pa.field("x", pa.int64())]))