diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 8aff1f7e73..9eccbee7ca 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -38,6 +38,7 @@ import re import uuid import warnings +import weakref from abc import ABC, abstractmethod from collections.abc import Callable, Iterable, Iterator from dataclasses import dataclass @@ -406,16 +407,40 @@ def to_input_file(self) -> PyArrowFile: return self +def _fs_by_scheme_cache(file_io: PyArrowFileIO) -> Callable[[str, str | None], FileSystem]: + """Return a cached FileSystem factory that does not keep ``file_io`` alive. + + Caching the bound method ``file_io._initialize_fs`` directly would make the cache hold + ``file_io`` while ``file_io`` holds the cache. That reference cycle keeps the FileIO and + its cached filesystems (and their connection pools) alive until the cycle collector runs. + + The cache holds a weak reference to ``file_io`` and the properties it was built from. If the + FileIO is already gone when a filesystem is needed, a new FileIO with the same properties + builds it, so callers that use a temporary FileIO keep working. + """ + file_io_ref = weakref.ref(file_io) + properties = file_io.properties + + @lru_cache + def fs_by_scheme(scheme: str, netloc: str | None = None) -> FileSystem: + io = file_io_ref() + if io is None: + io = PyArrowFileIO(properties) + return io._initialize_fs(scheme, netloc) + + return fs_by_scheme + + class PyArrowFileIO(_TransientStateMixin, 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) + self._init_transient() def _init_transient(self) -> None: - self.fs_by_scheme = lru_cache(self._initialize_fs) + self.fs_by_scheme = _fs_by_scheme_cache(self) @staticmethod def parse_location(location: str, properties: Properties = EMPTY_DICT) -> tuple[str, str, str]: diff --git a/pyiceberg/table/__init__.py b/pyiceberg/table/__init__.py index 1c6d4c3a33..637f1b136a 100644 --- a/pyiceberg/table/__init__.py +++ b/pyiceberg/table/__init__.py @@ -2983,7 +2983,15 @@ def __init__( @cached_property def partition_filters(self) -> KeyDefaultDict[int, BooleanExpression]: - return KeyDefaultDict(self._build_partition_projection) + # Capture the inputs instead of `self`. A bound method stored on the planner would make the planner and its + # `io` part of a reference cycle, so they would only be freed when the cycle collector runs. + table_metadata, row_filter, case_sensitive = self.table_metadata, self.row_filter, self.case_sensitive + + def build_partition_projection(spec_id: int) -> BooleanExpression: + project = inclusive_projection(table_metadata.schema(), table_metadata.specs()[spec_id], case_sensitive) + return project(row_filter) + + return KeyDefaultDict(build_partition_projection) def plan_manifest_entries(self, manifests: Iterable[ManifestFile]) -> Iterator[list[ManifestEntry]]: """Filter the given manifests using partition summaries and read the matching manifest entries. @@ -3104,10 +3112,6 @@ def residual_for(data_file: DataFile) -> BooleanExpression: for data_entry in data_entries ] - def _build_partition_projection(self, spec_id: int) -> BooleanExpression: - project = inclusive_projection(self.table_metadata.schema(), self.table_metadata.specs()[spec_id], self.case_sensitive) - return project(self.row_filter) - def _build_manifest_evaluator(self, spec_id: int) -> Callable[[ManifestFile], bool]: spec = self.table_metadata.specs()[spec_id] return manifest_evaluator(spec, self.table_metadata.schema(), self.partition_filters[spec_id], self.case_sensitive) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 92d533651c..1367e2cfd0 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -15,17 +15,21 @@ # specific language governing permissions and limitations # under the License. # pylint: disable=protected-access,unused-argument,redefined-outer-name +import gc import json import logging import math import os +import pickle import struct import sys import tempfile import uuid import warnings +import weakref import zlib from collections.abc import Callable, Iterator +from contextlib import contextmanager from dataclasses import replace from datetime import UTC, date, datetime, time from decimal import Decimal @@ -4539,6 +4543,42 @@ def test_pyarrow_file_io_fs_by_scheme_cache() -> None: assert pyarrow_file_io.fs_by_scheme.cache_info().hits == 2 # type: ignore +@contextmanager +def _cycle_collector_disabled() -> Iterator[None]: + was_enabled = gc.isenabled() + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() + + +def test_pyarrow_file_io_freed_by_refcounting() -> None: + with _cycle_collector_disabled(): + file_io = PyArrowFileIO() + file_io.fs_by_scheme("file", None) + file_io_ref = weakref.ref(file_io) + del file_io + + assert file_io_ref() is None + + +def test_pyarrow_file_io_pickle_round_trip_keeps_cache_and_refcounting() -> None: + file_io = PyArrowFileIO() + file_io.fs_by_scheme("file", None) + + restored = pickle.loads(pickle.dumps(file_io)) + assert isinstance(restored.fs_by_scheme("file", None), LocalFileSystem) + assert restored.fs_by_scheme.cache_info().currsize == 1 # type: ignore + + with _cycle_collector_disabled(): + restored_ref = weakref.ref(restored) + del restored + + assert restored_ref() is None + + def test_pyarrow_io_new_input_multi_region(caplog: Any) -> None: # It's better to set up multi-region minio servers for an integration test once `endpoint_url` argument # becomes available for `resolve_s3_region` diff --git a/tests/table/test_evaluator_planning.py b/tests/table/test_evaluator_planning.py index b0dfe9fe86..611a3b7324 100644 --- a/tests/table/test_evaluator_planning.py +++ b/tests/table/test_evaluator_planning.py @@ -17,6 +17,8 @@ from __future__ import annotations +import gc +import weakref from collections.abc import Callable import pytest @@ -92,3 +94,18 @@ def eval(self, data_file: DataFile) -> bool: assert metrics_evaluator(first_file) assert metrics_evaluator(second_file) assert instances[0].calls == [first_file, second_file] + + +def test_manifest_group_planner_freed_by_refcounting(table_v2: Table) -> None: + planner = ManifestGroupPlanner(table_metadata=table_v2.metadata, io=table_v2.io, row_filter=GreaterThan("x", 5)) + assert planner.partition_filters[0] is not None # caches the partition filters on the planner + planner_ref = weakref.ref(planner) + + was_enabled = gc.isenabled() + gc.disable() + try: + del planner + assert planner_ref() is None + finally: + if was_enabled: + gc.enable()