diff --git a/pyiceberg/avro/codecs/zstandard_codec.py b/pyiceberg/avro/codecs/zstandard_codec.py index 67e2347d01..c72c260199 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..d80f83e278 100644 --- a/pyiceberg/table/puffin.py +++ b/pyiceberg/table/puffin.py @@ -14,24 +14,20 @@ # 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 as _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) +def _zstd_decompress(data: bytes) -> bytes: + return _zstd.decompress(data) # Short for: Puffin Fratercula arctica, version 1 diff --git a/pyiceberg/utils/zstd.py b/pyiceberg/utils/zstd.py new file mode 100644 index 0000000000..6590b94479 --- /dev/null +++ b/pyiceberg/utils/zstd.py @@ -0,0 +1,76 @@ +# 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 + +if sys.version_info >= (3, 14): + try: + from compression import zstd + + _compress = zstd.compress + _decompress = zstd.decompress + except ImportError: + pass + +if _compress is None or _decompress is None: + try: + from zstandard import ZstdCompressor, ZstdDecompressor, ZstdError + + def _compress_with_zstandard(data: bytes) -> bytes: + return ZstdCompressor().compress(data) + + def _decompress_with_zstandard(data: bytes) -> bytes: + 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 + except ImportError: + pass + + +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/tests/table/test_puffin.py b/tests/table/test_puffin.py index 93b16158bb..c2f6675719 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -14,9 +14,15 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. +import subprocess +import sys from os import path +import pytest + +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 +85,66 @@ 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_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_without_backend_raises_on_use(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(zstd, "_compress", None) + monkeypatch.setattr(zstd, "_decompress", None) + + with pytest.raises(ImportError, match="Zstandard support not installed"): + ZStandardCodec.compress(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]) + + +def test_zstd_decompress_truncated_frame() -> None: + compressed, _ = ZStandardCodec.compress(b"hello iceberg" * 100) + + with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error|end-of-stream"): + ZStandardCodec.decompress(compressed[:-1]) + + +def test_imports_without_zstd_backend() -> None: + script = ( + "import sys\n" + "from importlib.abc import MetaPathFinder\n" + "class Blocker(MetaPathFinder):\n" + " def find_spec(self, name, path=None, target=None):\n" + " if name == 'zstandard' or name.startswith('zstandard.') or name in ('compression', 'compression.zstd'):\n" + " raise ImportError(f'No module named {name}')\n" + " return None\n" + "sys.meta_path.insert(0, Blocker())\n" + "import pyiceberg.manifest\n" + "from pyiceberg.avro.codecs import ZStandardCodec\n" + "from pyiceberg.table.puffin import PuffinFile\n" + "try:\n" + " ZStandardCodec.compress(b'hi')\n" + " raise SystemExit('expected ImportError')\n" + "except ImportError:\n" + " print('import-ok-raise-on-use')\n" + ) + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False) + + assert result.returncode == 0, result.stderr + assert "import-ok-raise-on-use" in result.stdout + + +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(Exception, match="incomplete|truncated|ZstdError|error|end-of-stream"): + ZStandardCodec.decompress(first + second[:-1])