From 4d489e874e93357b5eefbd07ba4f514d57664ce9 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Thu, 26 Nov 2026 00:58:41 +0000 Subject: [PATCH 1/3] Core: Fall back to zstandard when stdlib compression.zstd is missing PEP 784 makes compression.zstd optional, so on Python 3.14+ builds without libzstd the Avro codec import failed at module load and broke reading any manifest, and Puffin imports failed the same way when the zstandard package was missing. Move the backend selection into a shared pyiceberg.utils.zstd module that tries the stdlib module first, then the zstandard package, and only raises ImportError on use when neither is available. Refs #4495 --- pyiceberg/avro/codecs/zstandard_codec.py | 55 +++-------------- pyiceberg/table/puffin.py | 10 +--- pyiceberg/utils/zstd.py | 76 ++++++++++++++++++++++++ tests/table/test_puffin.py | 69 +++++++++++++++++++++ 4 files changed, 157 insertions(+), 53 deletions(-) create mode 100644 pyiceberg/utils/zstd.py 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..c2f91380cf 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 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"): + 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"): + ZStandardCodec.decompress(first + second[:-1]) From 890d196b9ef4744495d1ec9cecd7f8c74046ad80 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Wed, 25 Nov 2026 19:27:32 -0600 Subject: [PATCH 2/3] Tests: Import ZStandardCodec from its defining module in puffin tests mypy with no_implicit_reexport rejects importing ZStandardCodec through the pyiceberg.avro.codecs package, which does not explicitly re-export it. Import it from pyiceberg.avro.codecs.zstandard_codec instead. --- tests/table/test_puffin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/table/test_puffin.py b/tests/table/test_puffin.py index c2f91380cf..bc281d86fd 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -20,7 +20,7 @@ import pytest -from pyiceberg.avro.codecs import ZStandardCodec +from pyiceberg.avro.codecs.zstandard_codec import ZStandardCodec from pyiceberg.table.puffin import PuffinFile from pyiceberg.utils import zstd From 70ea3af5f357464eae450c413fb4bf77447b5f68 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Thu, 26 Nov 2026 15:25:27 +0000 Subject: [PATCH 3/3] Tests: Accept stdlib zstd wording for truncated frames in puffin tests On Python 3.14 the stdlib compression.zstd backend reports a truncated frame as 'Compressed data ended before the end-of-stream marker was reached', which the existing match terms do not cover, so the truncated frame and concatenated frames tests failed on 3.14 only. Widen both matches with end-of-stream. --- tests/table/test_puffin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/table/test_puffin.py b/tests/table/test_puffin.py index bc281d86fd..c2f6675719 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -112,7 +112,7 @@ def test_zstd_without_backend_raises_on_use(monkeypatch: pytest.MonkeyPatch) -> def test_zstd_decompress_truncated_frame() -> None: compressed, _ = ZStandardCodec.compress(b"hello iceberg" * 100) - with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error"): + with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error|end-of-stream"): ZStandardCodec.decompress(compressed[:-1]) @@ -146,5 +146,5 @@ def test_zstd_decompress_concatenated_frames() -> None: second, _ = ZStandardCodec.compress(b"second") assert ZStandardCodec.decompress(first + second) == b"firstsecond" - with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error"): + with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error|end-of-stream"): ZStandardCodec.decompress(first + second[:-1])