Fokko commented on PR #4527:
URL: https://github.com/apache/iceberg-python/pull/4527#issuecomment-7273615974
Thanks for tracking down this race! Instead of adding a lock and pickling
logic to `ContentCache`, I'd rather delegate the caching to `cachetools`, which
is already a core dependency. Then we can drop `ContentCache` and its LRU,
expiry, byte accounting and locking altogether.
`TTLCache` gives us LRU eviction, a size bound in bytes through `getsizeof`,
and expire-after-write. `cached(cache, lock=...)` takes care of thread safety:
it only holds the lock around the cache access, reads the file outside of it,
keeps the first stored value when two threads miss the same file, and skips
values that don't fit. The whole cache becomes:
```python
cache: TTLCache[str, bytes] = TTLCache(
maxsize=max_total_bytes,
ttl=expiration_interval_ms / 1000,
# Files over max_content_length count as larger than the cache, so
cached() does not keep them
getsizeof=lambda data: len(data) if len(data) <= max_content_length else
max_total_bytes + 1,
)
@cached(cache, lock=threading.Lock())
def read(location: str) -> bytes:
with io.new_input(location).open() as stream:
return stream.read()
```
and `_open_metadata_file` becomes `_MemoryInputFile(location,
io._read_cached(location))`.
For pickling, `FileIO` itself uses `_TransientStateMixin` and rebuilds the
cached reader from its properties, so `PyArrowFileIO` and `FsspecFileIO` extend
`FileIO._transient_attrs` instead of mixing it in themselves. An unpickled
FileIO starts with an empty cache, like Java, where the content cache isn't
part of the serialized FileIO. That removes the custom `__getstate__`, and we
don't send cached manifest bytes along to every worker. Since #4335 isn't
released yet, removing the `content_cache` property is fine.
I kept your thread-safety test, now going through `_open_metadata_file`;
without the lock it fails on every run with the same `RuntimeError`/`KeyError`.
The unit tests for our own LRU/expiry logic are replaced by behavioral tests
(read once, limits, expiry, pickling, table properties). It passes `make lint`
and `make test`, also against `cachetools==5.5.0`, our lower bound. Overall
it's +100/−263 on top of this PR:
<details>
<summary>Suggested diff on top of this PR</summary>
```diff
diff --git a/pyiceberg/io/__init__.py b/pyiceberg/io/__init__.py
index 45d9e3ce1..332a25a4d 100644
--- a/pyiceberg/io/__init__.py
+++ b/pyiceberg/io/__init__.py
@@ -28,19 +28,24 @@ from __future__ import annotations
import importlib
import logging
import os
+import threading
import warnings
from abc import ABC, abstractmethod
+from collections.abc import Callable
from io import SEEK_SET
from types import TracebackType
from typing import (
+ ClassVar,
Protocol,
runtime_checkable,
)
from urllib.parse import urlparse
-from pyiceberg.io.content_cache import ContentCache
+from cachetools import TTLCache, cached
+
from pyiceberg.typedef import EMPTY_DICT, Properties
from pyiceberg.utils.properties import property_as_bool, property_as_int
+from pyiceberg.utils.transient import _TransientStateMixin
logger = logging.getLogger(__name__)
@@ -284,7 +289,9 @@ class OutputFile(ABC):
"""
-def _content_cache_from_properties(properties: Properties) -> ContentCache
| None:
+def _cached_reader(io: FileIO) -> Callable[[str], bytes] | None:
+ """Return a function that reads files through a cache bounded by total
size and entry age, or None when disabled."""
+ properties = io.properties
if not property_as_bool(properties, IO_MANIFEST_CACHE_ENABLED, False):
return None
@@ -297,26 +304,34 @@ def _content_cache_from_properties(properties:
Properties) -> ContentCache | Non
expiration_interval_ms: int = property_as_int( # type:
ignore[assignment]
properties, IO_MANIFEST_CACHE_EXPIRATION_INTERVAL_MS,
IO_MANIFEST_CACHE_EXPIRATION_INTERVAL_MS_DEFAULT
)
- return ContentCache(
- max_total_bytes=max_total_bytes,
- max_content_length=max_content_length,
- expiration_interval_ms=expiration_interval_ms,
+ cache: TTLCache[str, bytes] = TTLCache(
+ maxsize=max_total_bytes,
+ ttl=expiration_interval_ms / 1000,
+ # Files over max_content_length count as larger than the cache, so
cached() does not keep them
+ getsizeof=lambda data: len(data) if len(data) <= max_content_length
else max_total_bytes + 1,
)
+ @cached(cache, lock=threading.Lock())
+ def read(location: str) -> bytes:
+ with io.new_input(location).open() as stream:
+ return stream.read()
+
+ return read
-class FileIO(ABC):
+
+class FileIO(_TransientStateMixin, ABC):
"""A base class for FileIO implementations."""
properties: Properties
+ _transient_attrs: ClassVar[tuple[str, ...]] = ("_read_cached",)
def __init__(self, properties: Properties = EMPTY_DICT):
self.properties = properties
- self._content_cache = _content_cache_from_properties(properties)
+ self._init_transient()
- @property
- def content_cache(self) -> ContentCache | None:
- """Return the cache for immutable metadata file contents, when
enabled."""
- return self._content_cache
+ def _init_transient(self) -> None:
+ # Unpickled FileIOs start with an empty cache
+ self._read_cached = _cached_reader(self)
@abstractmethod
def new_input(self, location: str) -> InputFile:
diff --git a/pyiceberg/io/content_cache.py b/pyiceberg/io/content_cache.py
deleted file mode 100644
index 73a4a3e08..000000000
--- a/pyiceberg/io/content_cache.py
+++ /dev/null
@@ -1,117 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-"""A bounded in-memory cache for the bytes of immutable metadata files."""
-
-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(_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.
- expiration_interval_ms: Entries older than this are treated as
absent.
- clock: Returns the current time in seconds, replaced in tests.
- """
-
- _transient_attrs = ("_lock",)
-
- def __init__(
- self,
- max_total_bytes: int,
- max_content_length: int,
- expiration_interval_ms: int,
- clock: Callable[[], float] = time.monotonic,
- ) -> None:
- self.max_total_bytes = max_total_bytes
- self.max_content_length = max_content_length
- self.expiration_interval_seconds = expiration_interval_ms / 1000
- 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."""
- 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
-
- 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
-
- 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)
-
- def clear(self) -> None:
- """Remove every entry."""
- 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)
- if entry is not None:
- self._total_bytes -= len(entry[0])
-
- def _purge_expired(self) -> None:
- now = self._clock()
- for location in [
- location
- for location, (_, inserted_at) in self._entries.items()
- if now - inserted_at >= self.expiration_interval_seconds
- ]:
- self._remove(location)
diff --git a/pyiceberg/io/fsspec.py b/pyiceberg/io/fsspec.py
index 505b5eebb..87607d377 100644
--- a/pyiceberg/io/fsspec.py
+++ b/pyiceberg/io/fsspec.py
@@ -98,7 +98,6 @@ from pyiceberg.typedef import Properties
from pyiceberg.types import strtobool
from pyiceberg.utils.datetime import millis_to_datetime
from pyiceberg.utils.properties import get_first_property_value,
get_header_properties, property_as_bool
-from pyiceberg.utils.transient import _TransientStateMixin
logger = logging.getLogger(__name__)
@@ -462,17 +461,17 @@ class FsspecOutputFile(OutputFile):
return FsspecInputFile(location=self.location, fs=self._fs)
-class FsspecFileIO(_TransientStateMixin, FileIO):
+class FsspecFileIO(FileIO):
"""A FileIO implementation that uses fsspec."""
- _transient_attrs = ("_thread_locals",)
+ _transient_attrs = (*FileIO._transient_attrs, "_thread_locals")
def __init__(self, properties: Properties):
self._scheme_to_fs: dict[str, Callable[..., AbstractFileSystem]] =
dict(SCHEME_TO_FS)
- self._init_transient()
super().__init__(properties=properties)
def _init_transient(self) -> None:
+ super()._init_transient()
self._thread_locals = threading.local()
@override
diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py
index f5ddaee8f..3214d2f24 100644
--- a/pyiceberg/io/pyarrow.py
+++ b/pyiceberg/io/pyarrow.py
@@ -198,7 +198,6 @@ from pyiceberg.utils.datetime import millis_to_datetime
from pyiceberg.utils.decimal import unscaled_to_decimal
from pyiceberg.utils.properties import get_first_property_value,
property_as_bool, property_as_int
from pyiceberg.utils.singleton import Singleton
-from pyiceberg.utils.transient import _TransientStateMixin
from pyiceberg.utils.truncate import truncate_upper_bound_binary_string,
truncate_upper_bound_text_string
if TYPE_CHECKING:
@@ -407,15 +406,12 @@ class PyArrowFile(InputFile, OutputFile):
return self
-class PyArrowFileIO(_TransientStateMixin, FileIO):
+class PyArrowFileIO(FileIO):
fs_by_scheme: Callable[[str, str | None], FileSystem]
- _transient_attrs = ("fs_by_scheme",)
-
- def __init__(self, properties: Properties = EMPTY_DICT):
- self._init_transient()
- super().__init__(properties=properties)
+ _transient_attrs = (*FileIO._transient_attrs, "fs_by_scheme")
def _init_transient(self) -> None:
+ super()._init_transient()
self.fs_by_scheme = lru_cache(self._initialize_fs)
@staticmethod
diff --git a/pyiceberg/manifest.py b/pyiceberg/manifest.py
index 4a2d832ef..3a2ed4f59 100644
--- a/pyiceberg/manifest.py
+++ b/pyiceberg/manifest.py
@@ -82,17 +82,10 @@ class _MemoryInputFile(InputFile):
def _open_metadata_file(io: FileIO, location: str) -> InputFile:
"""Open a metadata file, reading its bytes through the content cache
when the FileIO has one."""
- cache = io.content_cache
- if cache is None:
+ if io._read_cached is None:
return io.new_input(location)
- if (data := cache.get(location)) is None:
- input_file = io.new_input(location)
- with input_file.open() as stream:
- data = stream.read()
- cache.put(location, data)
-
- return _MemoryInputFile(location, data)
+ return _MemoryInputFile(location, io._read_cached(location))
class DataFileContent(int, Enum):
diff --git a/tests/io/test_content_cache.py b/tests/io/test_content_cache.py
index 9533951df..816fd2335 100644
--- a/tests/io/test_content_cache.py
+++ b/tests/io/test_content_cache.py
@@ -16,9 +16,9 @@
# under the License.
import pickle
import sys
-import threading
import time
from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
from unittest.mock import patch
import pyarrow as pa
@@ -30,146 +30,97 @@ from pyiceberg.io import (
IO_MANIFEST_CACHE_EXPIRATION_INTERVAL_MS,
IO_MANIFEST_CACHE_MAX_CONTENT_LENGTH,
IO_MANIFEST_CACHE_MAX_TOTAL_BYTES,
- IO_MANIFEST_CACHE_MAX_TOTAL_BYTES_DEFAULT,
+ FileIO,
)
-from pyiceberg.io.content_cache import ContentCache
from pyiceberg.io.fsspec import FsspecFileIO
from pyiceberg.io.pyarrow import PyArrowFileIO
+from pyiceberg.manifest import _open_metadata_file
-class _FakeClock:
- def __init__(self) -> None:
- self.now = 0.0
-
- def __call__(self) -> float:
- return self.now
-
-
-def test_cache_disabled_by_default() -> None:
- assert PyArrowFileIO().content_cache is None
-
-
-def test_cache_enabled_by_properties() -> None:
- cache = PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED: "true"}).content_cache
-
- assert cache is not None
- assert cache.max_total_bytes ==
IO_MANIFEST_CACHE_MAX_TOTAL_BYTES_DEFAULT
-
-
-def test_cache_returns_put_bytes() -> None:
- cache = ContentCache(max_total_bytes=10, max_content_length=10,
expiration_interval_ms=60_000)
-
- assert cache.get("a") is None
- cache.put("a", b"123")
- assert cache.get("a") == b"123"
-
-
-def test_cache_skips_entries_over_max_content_length() -> None:
- cache = ContentCache(max_total_bytes=100, max_content_length=3,
expiration_interval_ms=60_000)
-
- cache.put("a", b"1234")
+def _count_reads(io: FileIO, location: str) -> int:
+ """Open a file twice and return how often it was read from storage."""
+ with patch.object(io, "new_input", side_effect=io.new_input) as
new_input:
+ for _ in range(2):
+ with _open_metadata_file(io, location).open() as stream:
+ assert stream.read() == b"1234"
+ return new_input.call_count
- assert cache.get("a") is None
[email protected]
+def metadata_file(tmp_path: Path) -> str:
+ path = tmp_path / "manifest.avro"
+ path.write_bytes(b"1234")
+ return str(path)
-def test_cache_skips_entries_over_max_total_bytes() -> None:
- cache = ContentCache(max_total_bytes=3, max_content_length=10,
expiration_interval_ms=60_000)
- cache.put("a", b"1234")
+def test_cache_disabled_by_default() -> None:
+ assert PyArrowFileIO()._read_cached is None
- assert cache.get("a") is None
+def test_cache_reads_file_once(metadata_file: str) -> None:
+ assert _count_reads(PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED: "true"}),
metadata_file) == 1
-def test_cache_evicts_least_recently_used() -> None:
- cache = ContentCache(max_total_bytes=4, max_content_length=4,
expiration_interval_ms=60_000)
- cache.put("a", b"11")
- cache.put("b", b"22")
- assert cache.get("a") == b"11"
- cache.put("c", b"33")
+def test_cache_skips_files_over_the_limits(metadata_file: str) -> None:
+ for limit in (IO_MANIFEST_CACHE_MAX_CONTENT_LENGTH,
IO_MANIFEST_CACHE_MAX_TOTAL_BYTES):
+ io = PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED: "true", limit: "3"})
+ assert _count_reads(io, metadata_file) == 2, limit
- assert cache.get("b") is None
- assert cache.get("a") == b"11"
- assert cache.get("c") == b"33"
+def test_cache_expires_entries(metadata_file: str) -> None:
+ io = PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED: "true",
IO_MANIFEST_CACHE_EXPIRATION_INTERVAL_MS: "1"})
-def test_cache_expires_entries() -> None:
- clock = _FakeClock()
- cache = ContentCache(max_total_bytes=10, max_content_length=10,
expiration_interval_ms=1_000, clock=clock)
+ with patch.object(io, "new_input", side_effect=io.new_input) as
new_input:
+ _open_metadata_file(io, metadata_file)
+ time.sleep(0.01)
+ _open_metadata_file(io, metadata_file)
- cache.put("a", b"11")
- clock.now = 1.0
+ assert new_input.call_count == 2
- assert cache.get("a") is None
+def test_cache_is_thread_safe(tmp_path: Path) -> None:
+ locations = []
+ for i in range(50):
+ path = tmp_path / f"manifest-{i}.avro"
+ path.write_bytes(b"1234")
+ locations.append(str(path))
-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)
+ io = PyArrowFileIO(
+ {
+ IO_MANIFEST_CACHE_ENABLED: "true",
+ IO_MANIFEST_CACHE_MAX_TOTAL_BYTES: "160",
+ IO_MANIFEST_CACHE_MAX_CONTENT_LENGTH: "10",
+ IO_MANIFEST_CACHE_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)
+ with _open_metadata_file(io, locations[i % 50]).open() as
stream:
+ assert stream.read() == b"1234"
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)]
+ futures = [executor.submit(read_through_cache) for _ in
range(3)]
for future in futures:
future.result()
finally:
sys.setswitchinterval(switch_interval)
-def test_cache_is_kept_when_file_io_is_pickled() -> None:
+def test_cache_is_not_pickled(metadata_file: str) -> 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"
-
+ assert _count_reads(file_io, metadata_file) == 1
-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)
+ restored = pickle.loads(pickle.dumps(file_io))
- for copy in restored:
- assert copy._total_bytes == sum(len(data) for data, _ in
copy._entries.values())
- assert copy._total_bytes <= 160
+ # The copy starts with an empty cache, so it reads the file once
more
+ assert _count_reads(restored, metadata_file) == 1
def test_manifest_list_is_read_once(catalog: Catalog) -> None:
@@ -227,22 +178,22 @@ def
test_cache_properties_are_read_from_table_properties(catalog: Catalog) -> No
catalog.create_table(
"default.cache_properties",
schema=pa.schema([pa.field("x", pa.int64())]),
- properties={
- IO_MANIFEST_CACHE_ENABLED: "true",
- IO_MANIFEST_CACHE_MAX_TOTAL_BYTES: "1024",
- IO_MANIFEST_CACHE_MAX_CONTENT_LENGTH: "512",
- IO_MANIFEST_CACHE_EXPIRATION_INTERVAL_MS: "1000",
- },
- )
+ # Enabled, but too small to keep the manifest list
+ properties={IO_MANIFEST_CACHE_ENABLED: "true",
IO_MANIFEST_CACHE_MAX_CONTENT_LENGTH: "1"},
+ ).append(pa.table({"x": [1, 2, 3]}))
- cache = catalog.load_table("default.cache_properties").io.content_cache
+ table = catalog.load_table("default.cache_properties")
+ snapshot = table.current_snapshot()
+ assert snapshot is not None
+ assert table.io._read_cached is not None
- assert cache is not None
- assert cache.max_total_bytes == 1024
- assert cache.max_content_length == 512
- assert cache.expiration_interval_seconds == 1.0
+ with patch.object(table.io, "new_input",
side_effect=table.io.new_input) as new_input:
+ snapshot.manifests(table.io)
+ snapshot.manifests(table.io)
+
+ assert new_input.call_count == 2
@pytest.mark.parametrize("enabled", ["false", "0", ""])
def test_cache_stays_disabled_when_property_is_not_truthy(enabled: str) ->
None:
- assert PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED:
enabled}).content_cache is None
+ assert PyArrowFileIO({IO_MANIFEST_CACHE_ENABLED: enabled})._read_cached
is None
```
</details>
WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]