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/6] 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/6] 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/6] 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]) From b930e82121d6eba9a6a39aa852b9caa03caaed05 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Mon, 30 Nov 2026 03:09:20 -0600 Subject: [PATCH 4/6] Core: Bump zstandard floor to 0.19.0 and align the fallback with stdlib The fallback relies on ZstdDecompressionObj.eof and unused_data, so zstandard 0.19.0 is the oldest safe release on Python < 3.14. Empty input now raises the same ZstdError as the stdlib, the module exposes the active backend's ZstdError, and Puffin calls the shared module directly. --- pyiceberg/table/puffin.py | 6 +----- pyiceberg/utils/zstd.py | 23 ++++++++++++++++++----- pyproject.toml | 2 +- uv.lock | 6 +++--- 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/pyiceberg/table/puffin.py b/pyiceberg/table/puffin.py index d80f83e278..ac0fce53aa 100644 --- a/pyiceberg/table/puffin.py +++ b/pyiceberg/table/puffin.py @@ -26,10 +26,6 @@ import pyarrow as pa -def _zstd_decompress(data: bytes) -> bytes: - return _zstd.decompress(data) - - # Short for: Puffin Fratercula arctica, version 1 MAGIC_BYTES = b"PFA1" @@ -78,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 index 6590b94479..01faec1cf1 100644 --- a/pyiceberg/utils/zstd.py +++ b/pyiceberg/utils/zstd.py @@ -30,39 +30,52 @@ _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 + from compression import zstd as _stdlib_zstd - _compress = zstd.compress - _decompress = zstd.decompress + _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, ZstdError + 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") + 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: 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/uv.lock b/uv.lock index 4825090b0e..a5be847af6 100644 --- a/uv.lock +++ b/uv.lock @@ -506,8 +506,8 @@ resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "soupsieve", marker = "python_full_version >= '3.11.5'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.11.5'" }, + { name = "soupsieve" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } wheels = [ @@ -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"] From e81eac5c0662f59616865a00112ea6a1cace0cf9 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Mon, 30 Nov 2026 03:09:20 -0600 Subject: [PATCH 5/6] Tests: Move zstd codec tests to the avro file tests and cover the fallback The codec tests belong with the other codec tests in tests/avro/test_file.py, with exact ZstdError assertions. A new subprocess test blocks only compression.zstd while zstandard is installed and roundtrips through the fallback. --- tests/avro/test_file.py | 40 ++++++++++++++++++++++++++++++ tests/table/test_puffin.py | 50 ++++++++++++++++++-------------------- 2 files changed, 64 insertions(+), 26 deletions(-) diff --git a/tests/avro/test_file.py b/tests/avro/test_file.py index 595fceb585..bb253133b3 100644 --- a/tests/avro/test_file.py +++ b/tests/avro/test_file.py @@ -27,6 +27,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 +63,7 @@ TimeType, UUIDType, ) +from pyiceberg.utils import zstd from pyiceberg.utils.schema_conversion import AvroSchemaConversion @@ -691,3 +693,41 @@ def test_avro_output_file_tell_includes_buffered_records() -> None: out.write_block([manifest_entry(0)]) assert out.tell() > after_header + + +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") + + +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 c2f6675719..82ef103d83 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -16,11 +16,11 @@ # under the License. import subprocess import sys +from importlib.util import find_spec 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 @@ -87,35 +87,16 @@ def test_read_two_blobs_uncompressed() -> None: ) -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" @@ -141,10 +122,27 @@ def test_imports_without_zstd_backend() -> None: 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") +def test_zstd_fallback_when_stdlib_missing() -> None: + if find_spec("zstandard") is None: + pytest.skip("zstandard is not installed") + + 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 in ('compression', 'compression.zstd'):\n" + " raise ImportError(f'No module named {name}')\n" + " return None\n" + "sys.meta_path.insert(0, Blocker())\n" + "import zstandard\n" + "from pyiceberg.utils import zstd\n" + "assert zstd.ZstdError is zstandard.ZstdError\n" + "data = b'hello iceberg' * 100\n" + "assert zstd.decompress(zstd.compress(data)) == data\n" + "print('fallback-roundtrip-ok')\n" + ) + result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False) - assert ZStandardCodec.decompress(first + second) == b"firstsecond" - with pytest.raises(Exception, match="incomplete|truncated|ZstdError|error|end-of-stream"): - ZStandardCodec.decompress(first + second[:-1]) + assert result.returncode == 0, result.stderr + assert "fallback-roundtrip-ok" in result.stdout From 3603bd1d6b7f8936867bcd41e58b82157e391c31 Mon Sep 17 00:00:00 2001 From: TEJA P C Date: Mon, 30 Nov 2026 06:40:05 -0600 Subject: [PATCH 6/6] Core: Make the zstd helper private and test backend selection in-process Rename pyiceberg/utils/zstd.py to pyiceberg/utils/_zstd.py so compress, decompress and ZstdError do not become public API. Replace the subprocess backend tests with patch.dict and importlib.reload tests, and revert the unrelated beautifulsoup4 churn in uv.lock so only the zstandard specifier changes. --- pyiceberg/avro/codecs/zstandard_codec.py | 6 +- pyiceberg/table/puffin.py | 2 +- pyiceberg/utils/{zstd.py => _zstd.py} | 0 tests/avro/test_file.py | 27 ++++--- tests/table/test_puffin.py | 89 ++++++++---------------- uv.lock | 4 +- 6 files changed, 51 insertions(+), 77 deletions(-) rename pyiceberg/utils/{zstd.py => _zstd.py} (100%) diff --git a/pyiceberg/avro/codecs/zstandard_codec.py b/pyiceberg/avro/codecs/zstandard_codec.py index c72c260199..daa5c3ebbb 100644 --- a/pyiceberg/avro/codecs/zstandard_codec.py +++ b/pyiceberg/avro/codecs/zstandard_codec.py @@ -17,15 +17,15 @@ from __future__ import annotations from pyiceberg.avro.codecs.codec import Codec -from pyiceberg.utils import zstd +from pyiceberg.utils import _zstd class ZStandardCodec(Codec): @staticmethod def compress(data: bytes) -> tuple[bytes, int]: - compressed_data = zstd.compress(data) + compressed_data = _zstd.compress(data) return compressed_data, len(compressed_data) @staticmethod def decompress(data: bytes) -> bytes: - return zstd.decompress(data) + return _zstd.decompress(data) diff --git a/pyiceberg/table/puffin.py b/pyiceberg/table/puffin.py index ac0fce53aa..e7edb77692 100644 --- a/pyiceberg/table/puffin.py +++ b/pyiceberg/table/puffin.py @@ -19,7 +19,7 @@ from pydantic import Field from pyiceberg.typedef import IcebergBaseModel -from pyiceberg.utils import zstd as _zstd +from pyiceberg.utils import _zstd from pyiceberg.utils.deprecated import deprecated if TYPE_CHECKING: diff --git a/pyiceberg/utils/zstd.py b/pyiceberg/utils/_zstd.py similarity index 100% rename from pyiceberg/utils/zstd.py rename to pyiceberg/utils/_zstd.py diff --git a/tests/avro/test_file.py b/tests/avro/test_file.py index bb253133b3..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 @@ -63,7 +65,7 @@ TimeType, UUIDType, ) -from pyiceberg.utils import zstd +from pyiceberg.utils import _zstd from pyiceberg.utils.schema_conversion import AvroSchemaConversion @@ -695,12 +697,17 @@ def test_avro_output_file_tell_includes_buffered_records() -> None: assert out.tell() > after_header -def test_zstd_without_backend_raises_on_use(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(zstd, "_compress", None) - monkeypatch.setattr(zstd, "_decompress", None) +def test_zstd_fallback_when_stdlib_missing() -> None: + zstandard = pytest.importorskip("zstandard") - with pytest.raises(ImportError, match="Zstandard support not installed"): - ZStandardCodec.compress(b"hello iceberg") + 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: @@ -709,18 +716,18 @@ def test_zstd_roundtrip() -> None: assert size == len(compressed) assert ZStandardCodec.decompress(compressed) == data - assert zstd.decompress(zstd.compress(data)) == 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): + with pytest.raises(_zstd.ZstdError): ZStandardCodec.decompress(compressed[:-1]) def test_zstd_decompress_empty_input() -> None: - with pytest.raises(zstd.ZstdError): + with pytest.raises(_zstd.ZstdError): ZStandardCodec.decompress(b"") @@ -729,5 +736,5 @@ def test_zstd_decompress_concatenated_frames() -> None: second, _ = ZStandardCodec.compress(b"second") assert ZStandardCodec.decompress(first + second) == b"firstsecond" - with pytest.raises(zstd.ZstdError): + 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 82ef103d83..9d5766e08d 100644 --- a/tests/table/test_puffin.py +++ b/tests/table/test_puffin.py @@ -14,15 +14,16 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -import subprocess -import sys -from importlib.util import find_spec +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 +from pyiceberg.utils import _zstd def _open_file(file: str) -> bytes: @@ -87,62 +88,28 @@ def test_read_two_blobs_uncompressed() -> None: ) -def test_zstd_without_backend_raises_on_use(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(zstd, "_compress", None) - monkeypatch.setattr(zstd, "_decompress", None) +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) - 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_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_fallback_when_stdlib_missing() -> None: - if find_spec("zstandard") is None: - pytest.skip("zstandard is not installed") - - 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 in ('compression', 'compression.zstd'):\n" - " raise ImportError(f'No module named {name}')\n" - " return None\n" - "sys.meta_path.insert(0, Blocker())\n" - "import zstandard\n" - "from pyiceberg.utils import zstd\n" - "assert zstd.ZstdError is zstandard.ZstdError\n" - "data = b'hello iceberg' * 100\n" - "assert zstd.decompress(zstd.compress(data)) == data\n" - "print('fallback-roundtrip-ok')\n" - ) - result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, check=False) + 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") - assert result.returncode == 0, result.stderr - assert "fallback-roundtrip-ok" in result.stdout + 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 a5be847af6..0b48446ccf 100644 --- a/uv.lock +++ b/uv.lock @@ -506,8 +506,8 @@ resolution-markers = [ "python_full_version >= '3.11.5' and python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "soupsieve" }, - { name = "typing-extensions" }, + { name = "soupsieve", marker = "python_full_version >= '3.11.5'" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11.5'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } wheels = [