Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 9 additions & 46 deletions pyiceberg/avro/codecs/zstandard_codec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
12 changes: 2 additions & 10 deletions pyiceberg/table/puffin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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}")

Expand Down
89 changes: 89 additions & 0 deletions pyiceberg/utils/_zstd.py
Original file line number Diff line number Diff line change
@@ -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.

Comment thread
PCTEJA marked this conversation as resolved.
Resolved
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:
Comment thread
PCTEJA marked this conversation as resolved.
Resolved
decompressor = ZstdDecompressor().decompressobj()
uncompressed.extend(decompressor.decompress(remaining))
if not decompressor.eof:
Comment thread
PCTEJA marked this conversation as resolved.
Resolved
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)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
47 changes: 47 additions & 0 deletions tests/avro/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,22 @@
# 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
from fastavro import block_reader, reader, writer

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 (
Expand Down Expand Up @@ -62,6 +65,7 @@
TimeType,
UUIDType,
)
from pyiceberg.utils import _zstd
from pyiceberg.utils.schema_conversion import AvroSchemaConversion


Expand Down Expand Up @@ -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])
34 changes: 34 additions & 0 deletions tests/table/test_puffin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading