Fokko commented on code in PR #4498: URL: https://github.com/apache/iceberg-python/pull/4498#discussion_r4736281220
########## 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: Review Comment: Nit: `decompress(b"")` returns `b""` here, but `compression.zstd.decompress(b"")` raises `ZstdError: Compressed data ended before the end-of-stream marker was reached`. Since this otherwise mirrors the stdlib loop, it would be nice if both backends behaved the same. ########## 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: Review Comment: `ZstdDecompressionObj.eof` and `.unused_data` were added in zstandard 0.18.0, and 0.19.0 fixed an assertion/memory leak in the C backend when `decompressobj().decompress()` is called more than once. `pyproject.toml` still allows `zstandard>=0.13.0`, so on 3.11–3.13 with an older zstandard installed, every zstd manifest read would fail with an `AttributeError`. Can we bump the floor to `zstandard>=0.19.0; python_version < '3.14'` and regenerate the lockfile with `uv lock`? ########## 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 Review Comment: Nit: this binds the stdlib module as `zstd` inside `pyiceberg.utils.zstd`, which is a bit confusing to read. Maybe `from compression import zstd as _stdlib_zstd`? ########## 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) Review Comment: This wrapper only forwards now. The call site could use `_zstd.decompress(raw)` directly. ########## tests/table/test_puffin.py: ########## @@ -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: Review Comment: These codec tests aren't specific to Puffin. `tests/avro/test_file.py`, where the other codec tests live, seems like a better home. The Puffin assertion in the no-backend test can stay here. ########## tests/table/test_puffin.py: ########## @@ -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"): Review Comment: `pytest.raises(Exception, match="...|error|...")` passes for almost any exception. Could we assert the actual error type for each backend (`compression.zstd.ZstdError` or `zstandard.ZstdError`)? Alternatively, `pyiceberg.utils.zstd` could raise a single error type so the tests can be precise. ########## tests/table/test_puffin.py: ########## @@ -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"): Review Comment: Same as above. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
