diff --git a/pyiceberg/avro/codecs/zstandard_codec.py b/pyiceberg/avro/codecs/zstandard_codec.py index 67e2347d01..daa5c3ebbb 100644 --- a/pyiceberg/avro/codecs/zstandard_codec.py +++ b/pyiceberg/avro/codecs/zstandard_codec.py @@ -16,53 +16,16 @@ # under the License. from __future__ import annotations -import sys -from io import BytesIO - from pyiceberg.avro.codecs.codec import Codec +from pyiceberg.utils import _zstd -if sys.version_info >= (3, 14): - from compression import zstd - - class ZStandardCodec(Codec): - @staticmethod - def compress(data: bytes) -> tuple[bytes, int]: - compressed_data = zstd.compress(data) - return compressed_data, len(compressed_data) - - @staticmethod - def decompress(data: bytes) -> bytes: - return zstd.decompress(data) - -else: - try: - from zstandard import ZstdCompressor, ZstdDecompressor - - class ZStandardCodec(Codec): - @staticmethod - def compress(data: bytes) -> tuple[bytes, int]: - compressed_data = ZstdCompressor().compress(data) - return compressed_data, len(compressed_data) - - @staticmethod - def decompress(data: bytes) -> bytes: - uncompressed = bytearray() - dctx = ZstdDecompressor() - with dctx.stream_reader(BytesIO(data)) as reader: - while True: - chunk = reader.read(16384) - if not chunk: - break - uncompressed.extend(chunk) - return bytes(uncompressed) - - except ImportError: - class ZStandardCodec(Codec): # type: ignore - @staticmethod - def compress(data: bytes) -> tuple[bytes, int]: - raise ImportError("Zstandard support not installed, please install using `pip install pyiceberg[zstandard]`") +class ZStandardCodec(Codec): + @staticmethod + def compress(data: bytes) -> tuple[bytes, int]: + compressed_data = _zstd.compress(data) + return compressed_data, len(compressed_data) - @staticmethod - def decompress(data: bytes) -> bytes: - raise ImportError("Zstandard support not installed, please install using `pip install pyiceberg[zstandard]`") + @staticmethod + def decompress(data: bytes) -> bytes: + return _zstd.decompress(data) diff --git a/pyiceberg/table/puffin.py b/pyiceberg/table/puffin.py index b0794ebbe7..e7edb77692 100644 --- a/pyiceberg/table/puffin.py +++ b/pyiceberg/table/puffin.py @@ -14,25 +14,17 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -import sys from typing import TYPE_CHECKING from pydantic import Field from pyiceberg.typedef import IcebergBaseModel +from pyiceberg.utils import _zstd from pyiceberg.utils.deprecated import deprecated if TYPE_CHECKING: import pyarrow as pa -if sys.version_info >= (3, 14): - from compression.zstd import decompress as _zstd_decompress -else: - import zstandard - - def _zstd_decompress(data: bytes) -> bytes: - return zstandard.ZstdDecompressor().decompress(data) - # Short for: Puffin Fratercula arctica, version 1 MAGIC_BYTES = b"PFA1" @@ -82,7 +74,7 @@ def get_blob_payload(self, blob: PuffinBlobMetadata) -> bytes: if blob.compression_codec is None: return raw elif blob.compression_codec == "zstd": - return _zstd_decompress(raw) + return _zstd.decompress(raw) else: raise ValueError(f"Unsupported puffin compression codec: {blob.compression_codec!r}") diff --git a/pyiceberg/utils/_zstd.py b/pyiceberg/utils/_zstd.py new file mode 100644 index 0000000000..01faec1cf1 --- /dev/null +++ b/pyiceberg/utils/_zstd.py @@ -0,0 +1,89 @@ +# 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. +"""Zstandard compression backed by the stdlib ``compression.zstd`` or the ``zstandard`` package. + +The stdlib module is optional (PEP 784): it is only built when libzstd is +available, so fall back to the ``zstandard`` package when it is missing, and +only raise when neither is available. +""" + +from __future__ import annotations + +import sys +from collections.abc import Callable + +_NOT_INSTALLED = "Zstandard support not installed, please install using `pip install zstandard`" + +_compress: Callable[[bytes], bytes] | None = None +_decompress: Callable[[bytes], bytes] | None = None +ZstdError: type[Exception] + +if sys.version_info >= (3, 14): + try: + from compression import zstd as _stdlib_zstd + + _compress = _stdlib_zstd.compress + _decompress = _stdlib_zstd.decompress + ZstdError = _stdlib_zstd.ZstdError + except ImportError: + pass + +if _compress is None or _decompress is None: + try: + from zstandard import ZstdCompressor, ZstdDecompressor + from zstandard import ZstdError as _ZstdError + + def _compress_with_zstandard(data: bytes) -> bytes: + return ZstdCompressor().compress(data) + + def _decompress_with_zstandard(data: bytes) -> bytes: + if not data: + raise _ZstdError("Compressed data ended before the end-of-stream marker was reached") + uncompressed = bytearray() + remaining = data + while remaining: + decompressor = ZstdDecompressor().decompressobj() + uncompressed.extend(decompressor.decompress(remaining)) + if not decompressor.eof: + raise _ZstdError("Zstandard frame is incomplete or truncated") + remaining = decompressor.unused_data + return bytes(uncompressed) + + _compress = _compress_with_zstandard + _decompress = _decompress_with_zstandard + ZstdError = _ZstdError + except ImportError: + pass + +if _compress is None or _decompress is None: + + class _NoBackendZstdError(Exception): + """Placeholder so ZstdError exists when no zstd backend is installed.""" + + ZstdError = _NoBackendZstdError + + +def compress(data: bytes) -> bytes: + if _compress is None: + raise ImportError(_NOT_INSTALLED) + return _compress(data) + + +def decompress(data: bytes) -> bytes: + if _decompress is None: + raise ImportError(_NOT_INSTALLED) + return _decompress(data) diff --git a/pyproject.toml b/pyproject.toml index 6ff2bac669..dc5f7df558 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,7 @@ dependencies = [ "tenacity>=8.2.3", "pyroaring>=1.1.0", "cachetools>=5.5", - "zstandard>=0.13.0; python_version < '3.14'" + "zstandard>=0.19.0; python_version < '3.14'" ] [project.urls] diff --git a/tests/avro/test_file.py b/tests/avro/test_file.py index 595fceb585..117bf880ca 100644 --- a/tests/avro/test_file.py +++ b/tests/avro/test_file.py @@ -14,12 +14,14 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import importlib import inspect from _decimal import Decimal from datetime import datetime from enum import Enum from tempfile import TemporaryDirectory from typing import Any +from unittest.mock import patch from uuid import UUID import pytest @@ -27,6 +29,7 @@ import pyiceberg.avro.file as avro from pyiceberg.avro.codecs.deflate import DeflateCodec +from pyiceberg.avro.codecs.zstandard_codec import ZStandardCodec from pyiceberg.avro.file import DEFAULT_SYNC_INTERVAL, AvroFileHeader from pyiceberg.io.pyarrow import PyArrowFileIO from pyiceberg.manifest import ( @@ -62,6 +65,7 @@ TimeType, UUIDType, ) +from pyiceberg.utils import _zstd from pyiceberg.utils.schema_conversion import AvroSchemaConversion @@ -691,3 +695,46 @@ def test_avro_output_file_tell_includes_buffered_records() -> None: out.write_block([manifest_entry(0)]) assert out.tell() > after_header + + +def test_zstd_fallback_when_stdlib_missing() -> None: + zstandard = pytest.importorskip("zstandard") + + try: + with patch.dict("sys.modules", {"compression": None, "compression.zstd": None}): + importlib.reload(_zstd) + assert _zstd.ZstdError is zstandard.ZstdError + data = b"hello iceberg" * 100 + assert _zstd.decompress(_zstd.compress(data)) == data + finally: + importlib.reload(_zstd) + + +def test_zstd_roundtrip() -> None: + data = b"hello iceberg" * 100 + compressed, size = ZStandardCodec.compress(data) + + assert size == len(compressed) + assert ZStandardCodec.decompress(compressed) == data + assert _zstd.decompress(_zstd.compress(data)) == data + + +def test_zstd_decompress_truncated_frame() -> None: + compressed, _ = ZStandardCodec.compress(b"hello iceberg" * 100) + + with pytest.raises(_zstd.ZstdError): + ZStandardCodec.decompress(compressed[:-1]) + + +def test_zstd_decompress_empty_input() -> None: + with pytest.raises(_zstd.ZstdError): + ZStandardCodec.decompress(b"") + + +def test_zstd_decompress_concatenated_frames() -> None: + first, _ = ZStandardCodec.compress(b"first") + second, _ = ZStandardCodec.compress(b"second") + + assert ZStandardCodec.decompress(first + second) == b"firstsecond" + with pytest.raises(_zstd.ZstdError): + ZStandardCodec.decompress(first + second[:-1]) diff --git a/tests/table/test_puffin.py b/tests/table/test_puffin.py index 93b16158bb..9d5766e08d 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -14,9 +14,16 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import importlib from os import path +from unittest.mock import patch +import pytest + +from pyiceberg.avro.codecs import zstandard_codec +from pyiceberg.avro.codecs.zstandard_codec import ZStandardCodec from pyiceberg.table.puffin import PuffinFile +from pyiceberg.utils import _zstd def _open_file(file: str) -> bytes: @@ -79,3 +86,30 @@ def test_read_two_blobs_uncompressed() -> None: assert pf.get_blob_payload(blob2) == ( b"some blob \x00 binary data \xf0\x9f\xa4\xaf that is not very very very very very very long, is it?" ) + + +def test_zstd_without_backend_raises_on_use() -> None: + try: + with patch.dict("sys.modules", {"compression": None, "compression.zstd": None, "zstandard": None}): + importlib.reload(_zstd) + importlib.reload(zstandard_codec) + + with pytest.raises(ImportError, match="Zstandard support not installed"): + _zstd.compress(b"hello iceberg") + + with pytest.raises(ImportError, match="Zstandard support not installed"): + _zstd.decompress(b"hello iceberg") + + with pytest.raises(ImportError, match="Zstandard support not installed"): + ZStandardCodec.compress(b"hello iceberg") + + with pytest.raises(ImportError, match="Zstandard support not installed"): + ZStandardCodec.decompress(b"hello iceberg") + + puffin_bytes = _open_file("v1/sample-metric-data-compressed-zstd.bin") + pf = PuffinFile(puffin_bytes) + with pytest.raises(ImportError, match="Zstandard support not installed"): + pf.get_blob_payload(pf.footer.blobs[0]) + finally: + importlib.reload(_zstd) + importlib.reload(zstandard_codec) diff --git a/uv.lock b/uv.lock index 4825090b0e..0b48446ccf 100644 --- a/uv.lock +++ b/uv.lock @@ -4625,7 +4625,7 @@ requires-dist = [ { name = "thrift", marker = "extra == 'hive'", specifier = ">=0.13.0" }, { name = "thrift", marker = "extra == 'hive-kerberos'", specifier = ">=0.13.0" }, { name = "thrift-sasl", marker = "extra == 'hive-kerberos'", specifier = ">=0.4.3" }, - { name = "zstandard", marker = "python_full_version < '3.14'", specifier = ">=0.13.0" }, + { name = "zstandard", marker = "python_full_version < '3.14'", specifier = ">=0.19.0" }, ] provides-extras = ["pyarrow", "pandas", "duckdb", "ray", "bodo", "daft", "polars", "snappy", "hive", "hive-kerberos", "s3fs", "glue", "adlfs", "dynamodb", "bigquery", "sql-postgres", "sql-sqlite", "gcsfs", "rest-sigv4", "hf", "pyiceberg-core", "datafusion", "gcp-auth", "entra-auth", "geoarrow", "encryption"]