From 0fe035e4e8ed4b6b74d62c99340ad2edb0050f31 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Mon, 30 Nov 2026 18:37:00 +0900 Subject: [PATCH 1/9] feat: puffin zstd serde --- README.md | 1 + .../IcebergThirdpartyToolchain.cmake | 83 +++++++++- mkdocs/docs/getting-started.md | 1 + src/iceberg/CMakeLists.txt | 14 +- src/iceberg/puffin/puffin_format.cc | 52 ++++++- src/iceberg/test/puffin_format_test.cc | 127 +++++++++++++++ src/iceberg/test/puffin_reader_writer_test.cc | 146 ++++++++++++++++++ .../test/resources/puffin/v1/README.md | 5 + .../puffin/v1/empty-puffin-uncompressed.bin | Bin 0 -> 32 bytes .../v1/sample-metric-data-compressed-zstd.bin | Bin 0 -> 417 bytes .../v1/sample-metric-data-uncompressed.bin | Bin 0 -> 355 bytes 11 files changed, 415 insertions(+), 14 deletions(-) create mode 100644 src/iceberg/test/resources/puffin/v1/README.md create mode 100644 src/iceberg/test/resources/puffin/v1/empty-puffin-uncompressed.bin create mode 100644 src/iceberg/test/resources/puffin/v1/sample-metric-data-compressed-zstd.bin create mode 100644 src/iceberg/test/resources/puffin/v1/sample-metric-data-uncompressed.bin diff --git a/README.md b/README.md index 75ba297fb7..bedbde667e 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ If you experience network issues when downloading dependencies, you can customiz - `ICEBERG_UTF8PROC_URL`: utf8proc tarball URL - `ICEBERG_NLOHMANN_JSON_URL`: nlohmann-json tarball URL - `ICEBERG_SPDLOG_URL`: spdlog tarball URL +- `ICEBERG_ZSTD_URL`: zstd tarball URL - `ICEBERG_CPR_URL`: cpr tarball URL Example: diff --git a/cmake_modules/IcebergThirdpartyToolchain.cmake b/cmake_modules/IcebergThirdpartyToolchain.cmake index 5c76f7a546..b324d693f0 100644 --- a/cmake_modules/IcebergThirdpartyToolchain.cmake +++ b/cmake_modules/IcebergThirdpartyToolchain.cmake @@ -902,16 +902,86 @@ endfunction() # ---------------------------------------------------------------------- # Zstd +# function(resolve_zstd_dependency) - find_package(zstd CONFIG) - if(zstd_FOUND) + prepare_fetchcontent() + + set(ZSTD_BUILD_PROGRAMS OFF) + set(ZSTD_BUILD_TESTS OFF) + set(ZSTD_BUILD_SHARED OFF) + set(ZSTD_BUILD_STATIC ON) + set(ZSTD_MULTITHREAD_SUPPORT OFF) + + set(ICEBERG_ZSTD_BUILD_VERSION "1.5.7") + set(ICEBERG_ZSTD_BUILD_SHA256_CHECKSUM + "eb33e51f49a15e023950cd7825ca74a4a2b43db8354825ac24fc1b7ee09e6fa3") + + if(DEFINED ENV{ICEBERG_ZSTD_URL}) + set(ZSTD_URL "$ENV{ICEBERG_ZSTD_URL}") + else() + set(ZSTD_URL + "https://github.com/facebook/zstd/releases/download/v${ICEBERG_ZSTD_BUILD_VERSION}/zstd-${ICEBERG_ZSTD_BUILD_VERSION}.tar.gz" + ) + endif() + + fetchcontent_declare(zstd + ${FC_DECLARE_COMMON_OPTIONS} + URL ${ZSTD_URL} + URL_HASH "SHA256=${ICEBERG_ZSTD_BUILD_SHA256_CHECKSUM}" + SOURCE_SUBDIR + build/cmake + FIND_PACKAGE_ARGS + NAMES + zstd + CONFIG) + fetchcontent_makeavailable(zstd) + + if(zstd_SOURCE_DIR) + set(ZSTD_VENDORED TRUE) + set_target_properties(libzstd_static PROPERTIES OUTPUT_NAME "iceberg_vendored_zstd" + POSITION_INDEPENDENT_CODE ON) + install(TARGETS libzstd_static + EXPORT iceberg_targets + RUNTIME DESTINATION "${ICEBERG_INSTALL_BINDIR}" + ARCHIVE DESTINATION "${ICEBERG_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${ICEBERG_INSTALL_LIBDIR}") + set(ICEBERG_ZSTD_STATIC_TARGET libzstd_static) + set(ICEBERG_ZSTD_SHARED_TARGET libzstd_static) + else() + set(ZSTD_VENDORED FALSE) list(APPEND ICEBERG_SYSTEM_DEPENDENCIES zstd) message(STATUS "Found zstd, version: ${zstd_VERSION}") - set(ICEBERG_SYSTEM_DEPENDENCIES - ${ICEBERG_SYSTEM_DEPENDENCIES} - PARENT_SCOPE) + # zstd exports libzstd_static and libzstd_shared; vcpkg may only provide the + # unified zstd::libzstd target. + if(TARGET zstd::libzstd_static) + set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd_static) + elseif(TARGET zstd::libzstd_shared) + set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd_shared) + else() + set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd) + endif() + if(TARGET zstd::libzstd_shared) + set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd_shared) + elseif(TARGET zstd::libzstd_static) + set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd_static) + else() + set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd) + endif() endif() + + set(ICEBERG_SYSTEM_DEPENDENCIES + ${ICEBERG_SYSTEM_DEPENDENCIES} + PARENT_SCOPE) + set(ZSTD_VENDORED + ${ZSTD_VENDORED} + PARENT_SCOPE) + set(ICEBERG_ZSTD_STATIC_TARGET + ${ICEBERG_ZSTD_STATIC_TARGET} + PARENT_SCOPE) + set(ICEBERG_ZSTD_SHARED_TARGET + ${ICEBERG_ZSTD_SHARED_TARGET} + PARENT_SCOPE) endfunction() # ---------------------------------------------------------------------- @@ -992,9 +1062,10 @@ if(ICEBERG_BUILD_BUNDLE) resolve_aws_sdk_dependency() endif() resolve_avro_dependency() - resolve_zstd_dependency() endif() +resolve_zstd_dependency() + if(ICEBERG_BUILD_REST) resolve_cpr_dependency() endif() diff --git a/mkdocs/docs/getting-started.md b/mkdocs/docs/getting-started.md index fb414d01c7..333822cb2b 100644 --- a/mkdocs/docs/getting-started.md +++ b/mkdocs/docs/getting-started.md @@ -161,6 +161,7 @@ If you experience network issues when downloading dependencies, you can override | `ICEBERG_CROARING_URL` | CRoaring tarball | | `ICEBERG_UTF8PROC_URL` | utf8proc tarball | | `ICEBERG_NLOHMANN_JSON_URL` | nlohmann-json tarball | +| `ICEBERG_ZSTD_URL` | zstd tarball | | `ICEBERG_CPR_URL` | cpr tarball | Example: diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index d459020197..ccc04f71db 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -189,26 +189,32 @@ list(APPEND nlohmann_json::nlohmann_json utf8proc::utf8proc ZLIB::ZLIB - roaring::roaring) + roaring::roaring + ${ICEBERG_ZSTD_STATIC_TARGET}) list(APPEND ICEBERG_SHARED_BUILD_INTERFACE_LIBS "$,nanoarrow::nanoarrow_static,$,nanoarrow::nanoarrow_shared,nanoarrow::nanoarrow_static>>" nlohmann_json::nlohmann_json utf8proc::utf8proc ZLIB::ZLIB - roaring::roaring) + roaring::roaring + ${ICEBERG_ZSTD_SHARED_TARGET}) list(APPEND ICEBERG_STATIC_INSTALL_INTERFACE_LIBS "$,iceberg::nanoarrow_static,$,nanoarrow::nanoarrow_static,nanoarrow::nanoarrow_shared>>" "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" - "$,iceberg::roaring,roaring::roaring>") + "$,iceberg::roaring,roaring::roaring>" + "$,iceberg::libzstd_static,${ICEBERG_ZSTD_STATIC_TARGET}>" +) list(APPEND ICEBERG_SHARED_INSTALL_INTERFACE_LIBS "$,iceberg::nanoarrow_static,$,nanoarrow::nanoarrow_shared,nanoarrow::nanoarrow_static>>" "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" - "$,iceberg::roaring,roaring::roaring>") + "$,iceberg::roaring,roaring::roaring>" + "$,iceberg::libzstd_static,${ICEBERG_ZSTD_SHARED_TARGET}>" +) if(ICEBERG_SPDLOG) set(ICEBERG_HAS_SPDLOG ON) diff --git a/src/iceberg/puffin/puffin_format.cc b/src/iceberg/puffin/puffin_format.cc index 88d378f04a..f80d71b008 100644 --- a/src/iceberg/puffin/puffin_format.cc +++ b/src/iceberg/puffin/puffin_format.cc @@ -19,7 +19,10 @@ #include "iceberg/puffin/puffin_format.h" +#include + #include +#include #include #include @@ -56,8 +59,25 @@ Result> Compress(PuffinCompressionCodec codec, return std::vector(input.begin(), input.end()); case PuffinCompressionCodec::kLz4: return NotSupported("LZ4 compression is not yet supported"); - case PuffinCompressionCodec::kZstd: - return NotSupported("Zstd compression is not yet supported"); + case PuffinCompressionCodec::kZstd: { + const size_t input_size = input.size(); + if (input_size > std::numeric_limits::max()) { + // Matches Java, which rejects content sizes beyond the int range. + return CompressError("Input size {} is too large to compress", input_size); + } + + const size_t max_compressed_size = ZSTD_compressBound(input_size); + std::vector output(max_compressed_size); + // Match Java's default compression level, which is 3. + const size_t compressed_size = ZSTD_compress( + output.data(), output.size(), input.data(), input.size(), ZSTD_CLEVEL_DEFAULT); + if (ZSTD_isError(compressed_size)) { + return CompressError("Failed to compress data: {}", + ZSTD_getErrorName(compressed_size)); + } + output.resize(compressed_size); + return output; + } } std::unreachable(); } @@ -69,8 +89,32 @@ Result> Decompress(PuffinCompressionCodec codec, return std::vector(input.begin(), input.end()); case PuffinCompressionCodec::kLz4: return NotSupported("LZ4 decompression is not yet supported"); - case PuffinCompressionCodec::kZstd: - return NotSupported("Zstd decompression is not yet supported"); + case PuffinCompressionCodec::kZstd: { + const uint64_t frame_size = ZSTD_getFrameContentSize(input.data(), input.size()); + if (frame_size == ZSTD_CONTENTSIZE_ERROR) { + return DecompressError("Content size of the compressed data is invalid"); + } + if (frame_size == ZSTD_CONTENTSIZE_UNKNOWN) { + return DecompressError("Content size of the compressed data is unknown"); + } + if (frame_size > std::numeric_limits::max()) { + // Matches Java, which rejects content sizes beyond the int range. + return DecompressError("Content size of the compressed data is too large"); + } + + std::vector output(frame_size); + const size_t decompressed_size = + ZSTD_decompress(output.data(), output.size(), input.data(), input.size()); + if (ZSTD_isError(decompressed_size)) { + return DecompressError("Failed to decompress data: {}", + ZSTD_getErrorName(decompressed_size)); + } + if (decompressed_size != frame_size) { + return DecompressError("Decompressed size {} does not match the expected size {}", + decompressed_size, frame_size); + } + return output; + } } std::unreachable(); } diff --git a/src/iceberg/test/puffin_format_test.cc b/src/iceberg/test/puffin_format_test.cc index d4493c6f3a..a3d8204af4 100644 --- a/src/iceberg/test/puffin_format_test.cc +++ b/src/iceberg/test/puffin_format_test.cc @@ -19,13 +19,81 @@ #include "iceberg/puffin/puffin_format.h" +#include #include +#include #include +#include +#include +#include +#include #include +#include "iceberg/test/matchers.h" + namespace iceberg::puffin { +namespace { + +std::vector ToBytes(std::span values) { + std::vector bytes(values.size()); + std::ranges::transform(values, bytes.begin(), + [](uint8_t value) { return std::byte{value}; }); + return bytes; +} + +std::vector ToBytes(std::string_view str) { + return {reinterpret_cast(str.data()), + reinterpret_cast(str.data() + str.size())}; +} + +// Every zstd frame starts with the magic number 0xFD2FB528 (little-endian). +constexpr std::array kZstdMagic = {0x28, 0xb5, 0x2f, 0xfd}; + +// "abcdefghi" compressed by Iceberg Java: the first blob of +// resources/puffin/v1/sample-metric-data-compressed-zstd.bin. +constexpr std::array kJavaZstdFrame = { + 0x28, 0xb5, 0x2f, 0xfd, // magic number + 0x24, // descriptor: single segment, checksum + 0x09, // content size: 9 + 0x49, 0x00, 0x00, // block header: last, raw, 9 bytes + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', // block content + 0x13, 0x5e, 0xb9, 0xdb, // content checksum +}; + +constexpr std::array kZstdFrameWithoutContentSize = { + 0x28, 0xb5, 0x2f, 0xfd, // magic number + 0x00, // descriptor: no content size + 0x58, // window descriptor: 2 MiB + 0x49, 0x00, 0x00, // block header: last, raw, 9 bytes + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', // block content +}; + +constexpr std::array kZstdHeaderClaiming2GiB = { + 0x28, 0xb5, 0x2f, 0xfd, // magic number + 0xa0, // descriptor: single segment, 4-byte content size + 0x00, 0x00, 0x00, 0x80, // content size: 0x80000000 +}; + +std::vector AllByteValues() { + std::vector bytes(256); + for (size_t i = 0; i < bytes.size(); ++i) { + bytes[i] = static_cast(i); + } + return bytes; +} + +std::vector RepetitiveBytes(size_t size) { + std::vector bytes(size); + for (size_t i = 0; i < size; ++i) { + bytes[i] = static_cast(i % 7); + } + return bytes; +} + +} // namespace + TEST(PuffinFormatTest, FlagSetAndCheck) { std::array flags{}; EXPECT_FALSE(IsFlagSet(flags, PuffinFlag::kFooterPayloadCompressed)); @@ -34,4 +102,63 @@ TEST(PuffinFormatTest, FlagSetAndCheck) { EXPECT_TRUE(IsFlagSet(flags, PuffinFlag::kFooterPayloadCompressed)); } +TEST(PuffinFormatTest, DecompressZstdRejectsInputThatIsNotAFrame) { + EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, {}), + IsError(ErrorKind::kDecompressError)); + EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, ToBytes("not a zstd frame")), + IsError(ErrorKind::kDecompressError)); +} + +TEST(PuffinFormatTest, DecompressZstdRejectsUnknownContentSize) { + EXPECT_THAT( + Decompress(PuffinCompressionCodec::kZstd, ToBytes(kZstdFrameWithoutContentSize)), + IsError(ErrorKind::kDecompressError)); +} + +TEST(PuffinFormatTest, DecompressZstdRejectsTooLargeContentSize) { + EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, ToBytes(kZstdHeaderClaiming2GiB)), + IsError(ErrorKind::kDecompressError)); +} + +TEST(PuffinFormatTest, DecompressZstdRejectsChecksumMismatch) { + auto frame = ToBytes(kJavaZstdFrame); + frame.back() ^= std::byte{0xff}; + EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, frame), + IsError(ErrorKind::kDecompressError)); +} + +struct ZstdRoundTripParam { + const char* name; + std::vector data; + + friend void PrintTo(const ZstdRoundTripParam& param, std::ostream* os) { + *os << param.name << " (" << param.data.size() << " bytes)"; + } +}; + +class PuffinZstdRoundTripTest : public ::testing::TestWithParam {}; + +TEST_P(PuffinZstdRoundTripTest, CompressThenDecompress) { + const auto& data = GetParam().data; + ICEBERG_UNWRAP_OR_FAIL(auto compressed, Compress(PuffinCompressionCodec::kZstd, data)); + ASSERT_GE(compressed.size(), kZstdMagic.size()); + EXPECT_TRUE(std::ranges::equal(std::span(compressed).first(kZstdMagic.size()), + ToBytes(kZstdMagic))); + + ICEBERG_UNWRAP_OR_FAIL(auto decompressed, + Decompress(PuffinCompressionCodec::kZstd, compressed)); + EXPECT_EQ(decompressed, data); +} + +INSTANTIATE_TEST_SUITE_P( + ZstdInputs, PuffinZstdRoundTripTest, + ::testing::Values( + ZstdRoundTripParam{.name = "empty", .data = {}}, + ZstdRoundTripParam{.name = "short_text", .data = ToBytes("abcdefghi")}, + ZstdRoundTripParam{.name = "all_byte_values", .data = AllByteValues()}, + ZstdRoundTripParam{.name = "repetitive_1mib", .data = RepetitiveBytes(1 << 20)}), + [](const ::testing::TestParamInfo& info) { + return info.param.name; + }); + } // namespace iceberg::puffin diff --git a/src/iceberg/test/puffin_reader_writer_test.cc b/src/iceberg/test/puffin_reader_writer_test.cc index 8d610cee95..31c37810c9 100644 --- a/src/iceberg/test/puffin_reader_writer_test.cc +++ b/src/iceberg/test/puffin_reader_writer_test.cc @@ -19,10 +19,15 @@ #include #include +#include +#include +#include #include +#include #include #include #include +#include #include #include @@ -32,11 +37,14 @@ #include "iceberg/puffin/puffin_writer.h" #include "iceberg/test/matchers.h" #include "iceberg/test/mock_io.h" +#include "iceberg/test/test_config.h" namespace iceberg::puffin { namespace { +using std::string_view_literals::operator""sv; + struct PuffinFile { MockFileIO io; std::string location = "memory://test.puffin"; @@ -80,6 +88,21 @@ std::vector ToBytes(std::string_view str) { reinterpret_cast(str.data() + str.size())}; } +/// \brief Read a Puffin file written by Iceberg Java from resources/puffin/v1. +std::vector ReadJavaPuffinFile(std::string_view name) { + auto path = std::filesystem::path(ICEBERG_TEST_RESOURCES) / "puffin" / "v1" / name; + std::ifstream file(path, std::ios::binary); + EXPECT_TRUE(file.good()) << "Cannot open: " << path; + std::string content{std::istreambuf_iterator(file), + std::istreambuf_iterator()}; + return ToBytes(content); +} + +// Contents of the second blob in the Java sample metric data files. +constexpr std::string_view kJavaSecondBlobContent = + "some blob \0 binary data \xF0\x9F\xA4\xAF that is not very very very very very " + "very long, is it?"sv; + } // namespace TEST(PuffinWriterTest, WriteEmptyFile) { @@ -241,6 +264,47 @@ TEST(PuffinRoundTripTest, WithProperties) { EXPECT_EQ(blob_result.second, ToBytes("hello puffin")); } +TEST(PuffinRoundTripTest, ZstdCompressedBlobs) { + PuffinFile file; + const std::string text(4096, 'z'); + const std::vector blob_data(text.begin(), text.end()); + { + ICEBERG_UNWRAP_OR_FAIL( + auto writer, + PuffinWriter::Make(file.Output(), {}, PuffinCompressionCodec::kZstd)); + ICEBERG_UNWRAP_OR_FAIL(auto compressed, writer->Write(Blob{.type = "compressed", + .input_fields = {1}, + .snapshot_id = 1, + .sequence_number = 0, + .data = blob_data})); + EXPECT_EQ(compressed.compression_codec, "zstd"); + EXPECT_LT(compressed.length, static_cast(blob_data.size())); + + ICEBERG_UNWRAP_OR_FAIL( + auto uncompressed, + writer->Write(Blob{.type = "uncompressed", + .input_fields = {2}, + .snapshot_id = 1, + .sequence_number = 0, + .data = blob_data, + .requested_compression = PuffinCompressionCodec::kNone})); + EXPECT_EQ(uncompressed.compression_codec, ""); + EXPECT_EQ(uncompressed.length, static_cast(blob_data.size())); + ASSERT_THAT(writer->Finish(), IsOk()); + } + + ICEBERG_UNWRAP_OR_FAIL(auto reader, PuffinReader::Make(file.Input())); + ICEBERG_UNWRAP_OR_FAIL(auto fm, reader->ReadFileMetadata()); + ASSERT_EQ(fm.blobs.size(), 2); + EXPECT_EQ(fm.blobs[0].compression_codec, "zstd"); + EXPECT_EQ(fm.blobs[1].compression_codec, ""); + + ICEBERG_UNWRAP_OR_FAIL(auto all, reader->ReadAll(fm.blobs)); + ASSERT_EQ(all.size(), 2); + EXPECT_EQ(all[0].second, ToBytes(text)); + EXPECT_EQ(all[1].second, ToBytes(text)); +} + TEST(PuffinReaderTest, MakeRejectsNullInput) { EXPECT_THAT(PuffinReader::Make(nullptr), IsError(ErrorKind::kInvalidArgument)); } @@ -310,4 +374,86 @@ TEST(PuffinReaderTest, EmptyPuffinCompatibility) { EXPECT_TRUE(fm.properties.empty()); } +TEST(PuffinReaderTest, ReadJavaFilesWithKnownFooterSize) { + struct JavaFile { + const char* name; + int64_t footer_size; + size_t blob_count; + }; + for (const auto& java_file : + {JavaFile{ + .name = "empty-puffin-uncompressed.bin", .footer_size = 28, .blob_count = 0}, + JavaFile{.name = "sample-metric-data-compressed-zstd.bin", + .footer_size = 314, + .blob_count = 2}}) { + SCOPED_TRACE(java_file.name); + PuffinFile file; + file.SetData(ReadJavaPuffinFile(java_file.name)); + const auto file_size = static_cast(file.Data().size()); + + ICEBERG_UNWRAP_OR_FAIL( + auto reader, + PuffinReader::Make(file.Input(file_size), java_file.footer_size, file_size)); + ICEBERG_UNWRAP_OR_FAIL(auto fm, reader->ReadFileMetadata()); + EXPECT_EQ(fm.blobs.size(), java_file.blob_count); + } +} + +struct JavaSampleMetricDataParam { + const char* name; + const char* file_name; + const char* codec; + + friend void PrintTo(const JavaSampleMetricDataParam& param, std::ostream* os) { + *os << param.file_name; + } +}; + +class PuffinJavaSampleMetricDataTest + : public ::testing::TestWithParam {}; + +TEST_P(PuffinJavaSampleMetricDataTest, ReadBlobsWrittenByJava) { + const auto& param = GetParam(); + PuffinFile file; + file.SetData(ReadJavaPuffinFile(param.file_name)); + + ICEBERG_UNWRAP_OR_FAIL(auto reader, PuffinReader::Make(file.Input())); + ICEBERG_UNWRAP_OR_FAIL(auto fm, reader->ReadFileMetadata()); + EXPECT_EQ(fm.properties, + (std::unordered_map{{"created-by", "Test 1234"}})); + ASSERT_EQ(fm.blobs.size(), 2); + + const auto& first = fm.blobs[0]; + EXPECT_EQ(first.type, "some-blob"); + EXPECT_EQ(first.input_fields, std::vector{1}); + EXPECT_EQ(first.offset, 4); + EXPECT_EQ(first.compression_codec, param.codec); + + const auto& second = fm.blobs[1]; + EXPECT_EQ(second.type, "some-other-blob"); + EXPECT_EQ(second.input_fields, std::vector{2}); + EXPECT_EQ(second.offset, first.offset + first.length); + EXPECT_EQ(second.compression_codec, param.codec); + + ICEBERG_UNWRAP_OR_FAIL(auto all, reader->ReadAll(fm.blobs)); + ASSERT_EQ(all.size(), 2); + EXPECT_EQ(all[0].first, first); + EXPECT_EQ(all[0].second, ToBytes("abcdefghi")); + EXPECT_EQ(all[1].first, second); + EXPECT_EQ(all[1].second, ToBytes(kJavaSecondBlobContent)); +} + +INSTANTIATE_TEST_SUITE_P( + JavaFiles, PuffinJavaSampleMetricDataTest, + ::testing::Values( + JavaSampleMetricDataParam{.name = "uncompressed", + .file_name = "sample-metric-data-uncompressed.bin", + .codec = ""}, + JavaSampleMetricDataParam{.name = "zstd", + .file_name = "sample-metric-data-compressed-zstd.bin", + .codec = "zstd"}), + [](const ::testing::TestParamInfo& info) { + return info.param.name; + }); + } // namespace iceberg::puffin diff --git a/src/iceberg/test/resources/puffin/v1/README.md b/src/iceberg/test/resources/puffin/v1/README.md new file mode 100644 index 0000000000..91553ac611 --- /dev/null +++ b/src/iceberg/test/resources/puffin/v1/README.md @@ -0,0 +1,5 @@ +# Puffin fixtures from Apache Iceberg Java + +These files are canonical Puffin files written by the Apache Iceberg Java +implementation. They are copied unchanged from +[`core/src/test/resources/org/apache/iceberg/puffin/v1`](https://github.com/apache/iceberg/tree/0775af10147ffa87629d39b5fabaee5e5cdcce8d/core/src/test/resources/org/apache/iceberg/puffin/v1) diff --git a/src/iceberg/test/resources/puffin/v1/empty-puffin-uncompressed.bin b/src/iceberg/test/resources/puffin/v1/empty-puffin-uncompressed.bin new file mode 100644 index 0000000000000000000000000000000000000000..142b45bd4ebe0b865064ef874325ff1c94399bb1 GIT binary patch literal 32 fcmWG=b2JP9;%cR&ocyF>C9CMzS{?=n0Eq(tjVlLb literal 0 HcmV?d00001 diff --git a/src/iceberg/test/resources/puffin/v1/sample-metric-data-compressed-zstd.bin b/src/iceberg/test/resources/puffin/v1/sample-metric-data-compressed-zstd.bin new file mode 100644 index 0000000000000000000000000000000000000000..ac8b69c76e5770823137232c7b84d8a9e4903977 GIT binary patch literal 417 zcmb7=u}Z{15Qg^@3u|9s87)K-B=PVdjo1j+9cU*fY<4HfLb4lo=Y$xpw6(IgvA43g zSMU||A$$SB%{3x|;B@oP&;QNL?Cdnze>wcz+nzEea;dN=E4_2IdRwdKTN~_Q)7u7l zUfY~Ao@*mq$CV(#KOUc+IaPwV_S{(FH|V`riUTILw4B% zbuB^$LvTE(5J91_R>L%zN8pWUePt=u3bHixc)dU)F*b`PM+aFFfh`J;1lc%(8cj)6 za0aWiP3zEmZA~n#LK!%>o)j#jpIl27x?lA4pY-(j8$X%+g%824vn@K(81C#rIuwK| X&bzSU1$yF1dNhXR@?gZ)HGJ(0r0$BX literal 0 HcmV?d00001 diff --git a/src/iceberg/test/resources/puffin/v1/sample-metric-data-uncompressed.bin b/src/iceberg/test/resources/puffin/v1/sample-metric-data-uncompressed.bin new file mode 100644 index 0000000000000000000000000000000000000000..ab8da13822c55c573b8ba925eb9ebbc33cd87f28 GIT binary patch literal 355 zcmb7PY+KhqS$DC(-` zheOd{v1(>i#}#>*2^CgSQ@bc|@HE*vl`jHw&~tW?8*fpyrKZ<2g`S#lJ{d}=q`)`~ znHbex;6!0$hw6S4KeZz}O1}v0KMAt?M%;B#;DY2*W@QQsR&14(16i?5T8D!h- Maoaw2Us3IU0?}=DoB#j- literal 0 HcmV?d00001 From 5cc37f667a4fb214a9cc4fa23ba8473b4ad9ce33 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Tue, 1 Dec 2026 20:23:02 +0900 Subject: [PATCH 2/9] fix: reject malformed input --- src/iceberg/puffin/puffin_format.cc | 17 +++++ src/iceberg/test/puffin_format_test.cc | 86 ++++++++++++++++++++------ 2 files changed, 85 insertions(+), 18 deletions(-) diff --git a/src/iceberg/puffin/puffin_format.cc b/src/iceberg/puffin/puffin_format.cc index f80d71b008..ef01359029 100644 --- a/src/iceberg/puffin/puffin_format.cc +++ b/src/iceberg/puffin/puffin_format.cc @@ -26,6 +26,8 @@ #include #include +#include "iceberg/util/endian.h" + namespace iceberg::puffin { namespace { @@ -90,6 +92,21 @@ Result> Decompress(PuffinCompressionCodec codec, case PuffinCompressionCodec::kLz4: return NotSupported("LZ4 decompression is not yet supported"); case PuffinCompressionCodec::kZstd: { + if (input.size() < sizeof(uint32_t) || + ReadLittleEndian(input.data()) != ZSTD_MAGICNUMBER) { + return DecompressError("Compressed data is not a Zstandard frame"); + } + const size_t compressed_frame_size = + ZSTD_findFrameCompressedSize(input.data(), input.size()); + if (ZSTD_isError(compressed_frame_size)) { + return DecompressError("Invalid Zstandard frame: {}", + ZSTD_getErrorName(compressed_frame_size)); + } + if (compressed_frame_size != input.size()) { + return DecompressError("Found {} bytes after the Zstandard frame", + input.size() - compressed_frame_size); + } + const uint64_t frame_size = ZSTD_getFrameContentSize(input.data(), input.size()); if (frame_size == ZSTD_CONTENTSIZE_ERROR) { return DecompressError("Content size of the compressed data is invalid"); diff --git a/src/iceberg/test/puffin_format_test.cc b/src/iceberg/test/puffin_format_test.cc index a3d8204af4..73797b001d 100644 --- a/src/iceberg/test/puffin_format_test.cc +++ b/src/iceberg/test/puffin_format_test.cc @@ -76,6 +76,25 @@ constexpr std::array kZstdHeaderClaiming2GiB = { 0x00, 0x00, 0x00, 0x80, // content size: 0x80000000 }; +constexpr std::array kEmptyZstdFrame = { + 0x28, 0xb5, 0x2f, 0xfd, // magic number + 0x20, // descriptor: single segment + 0x00, // content size: 0 + 0x01, 0x00, 0x00, // block header: last, raw, 0 bytes +}; + +constexpr std::array kSkippableFrame = { + 0x50, 0x2a, 0x4d, 0x18, // magic number of a skippable frame + 0x03, 0x00, 0x00, 0x00, // frame size: 3 + 'x', 'y', 'z', // user data +}; + +std::vector Concat(std::vector head, + std::span tail) { + head.insert(head.end(), tail.begin(), tail.end()); + return head; +} + std::vector AllByteValues() { std::vector bytes(256); for (size_t i = 0; i < bytes.size(); ++i) { @@ -102,31 +121,62 @@ TEST(PuffinFormatTest, FlagSetAndCheck) { EXPECT_TRUE(IsFlagSet(flags, PuffinFlag::kFooterPayloadCompressed)); } -TEST(PuffinFormatTest, DecompressZstdRejectsInputThatIsNotAFrame) { - EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, {}), - IsError(ErrorKind::kDecompressError)); - EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, ToBytes("not a zstd frame")), - IsError(ErrorKind::kDecompressError)); -} +struct MalformedZstdParam { + const char* name; + std::vector input; -TEST(PuffinFormatTest, DecompressZstdRejectsUnknownContentSize) { - EXPECT_THAT( - Decompress(PuffinCompressionCodec::kZstd, ToBytes(kZstdFrameWithoutContentSize)), - IsError(ErrorKind::kDecompressError)); -} + friend void PrintTo(const MalformedZstdParam& param, std::ostream* os) { + *os << param.name << " (" << param.input.size() << " bytes)"; + } +}; -TEST(PuffinFormatTest, DecompressZstdRejectsTooLargeContentSize) { - EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, ToBytes(kZstdHeaderClaiming2GiB)), - IsError(ErrorKind::kDecompressError)); +std::vector MalformedZstdInputs() { + constexpr size_t kContentSizeIndex = 5; + const auto frame = ToBytes(kJavaZstdFrame); + auto truncated = frame; + truncated.resize(12); + auto smaller_content_size = frame; + smaller_content_size[kContentSizeIndex] = std::byte{8}; + auto larger_content_size = frame; + larger_content_size[kContentSizeIndex] = std::byte{10}; + auto bad_checksum = frame; + bad_checksum.back() ^= std::byte{0xff}; + + return { + {.name = "empty_input", .input = {}}, + {.name = "not_a_frame", .input = ToBytes("not a zstd frame")}, + {.name = "no_content_size", .input = ToBytes(kZstdFrameWithoutContentSize)}, + {.name = "content_size_too_large", .input = ToBytes(kZstdHeaderClaiming2GiB)}, + {.name = "skippable_frame", .input = ToBytes(kSkippableFrame)}, + {.name = "skippable_frame_then_frame", + .input = Concat(ToBytes(kSkippableFrame), frame)}, + {.name = "frame_then_skippable_frame", + .input = Concat(frame, ToBytes(kSkippableFrame))}, + {.name = "frame_then_empty_frame", + .input = Concat(frame, ToBytes(kEmptyZstdFrame))}, + {.name = "frame_then_3_garbage_bytes", .input = Concat(frame, ToBytes("xyz"))}, + {.name = "frame_then_8_garbage_bytes", .input = Concat(frame, ToBytes("garbage!"))}, + {.name = "truncated_frame", .input = truncated}, + {.name = "content_size_smaller_than_payload", .input = smaller_content_size}, + {.name = "content_size_larger_than_payload", .input = larger_content_size}, + {.name = "checksum_mismatch", .input = bad_checksum}, + }; } -TEST(PuffinFormatTest, DecompressZstdRejectsChecksumMismatch) { - auto frame = ToBytes(kJavaZstdFrame); - frame.back() ^= std::byte{0xff}; - EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, frame), +class PuffinZstdMalformedInputTest : public ::testing::TestWithParam { +}; + +TEST_P(PuffinZstdMalformedInputTest, DecompressReturnsError) { + EXPECT_THAT(Decompress(PuffinCompressionCodec::kZstd, GetParam().input), IsError(ErrorKind::kDecompressError)); } +INSTANTIATE_TEST_SUITE_P(MalformedInputs, PuffinZstdMalformedInputTest, + ::testing::ValuesIn(MalformedZstdInputs()), + [](const ::testing::TestParamInfo& info) { + return info.param.name; + }); + struct ZstdRoundTripParam { const char* name; std::vector data; From 9dd0631fbae3384f4fe6031c0e06d1a65e705ed3 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Wed, 2 Dec 2026 20:10:33 +0900 Subject: [PATCH 3/9] fix: cmake --- .../IcebergThirdpartyToolchain.cmake | 35 ++++++++----------- src/iceberg/CMakeLists.txt | 13 ++++--- 2 files changed, 21 insertions(+), 27 deletions(-) diff --git a/cmake_modules/IcebergThirdpartyToolchain.cmake b/cmake_modules/IcebergThirdpartyToolchain.cmake index b324d693f0..5b716777d1 100644 --- a/cmake_modules/IcebergThirdpartyToolchain.cmake +++ b/cmake_modules/IcebergThirdpartyToolchain.cmake @@ -939,6 +939,11 @@ function(resolve_zstd_dependency) if(zstd_SOURCE_DIR) set(ZSTD_VENDORED TRUE) + # FetchContent supports EXCLUDE_FROM_ALL only since CMake 3.28. Exclude the zstd + # directory here as well, so that older CMake versions skip zstd's own install + # rules. + set_property(DIRECTORY "${zstd_SOURCE_DIR}/build/cmake" PROPERTY EXCLUDE_FROM_ALL + TRUE) set_target_properties(libzstd_static PROPERTIES OUTPUT_NAME "iceberg_vendored_zstd" POSITION_INDEPENDENT_CODE ON) install(TARGETS libzstd_static @@ -946,27 +951,20 @@ function(resolve_zstd_dependency) RUNTIME DESTINATION "${ICEBERG_INSTALL_BINDIR}" ARCHIVE DESTINATION "${ICEBERG_INSTALL_LIBDIR}" LIBRARY DESTINATION "${ICEBERG_INSTALL_LIBDIR}") - set(ICEBERG_ZSTD_STATIC_TARGET libzstd_static) - set(ICEBERG_ZSTD_SHARED_TARGET libzstd_static) + install(FILES "${zstd_SOURCE_DIR}/LICENSE" + DESTINATION "${ICEBERG_INSTALL_DOCDIR}" + RENAME "LICENSE.zstd") + set(ICEBERG_ZSTD_TARGET libzstd_static) else() set(ZSTD_VENDORED FALSE) list(APPEND ICEBERG_SYSTEM_DEPENDENCIES zstd) message(STATUS "Found zstd, version: ${zstd_VERSION}") - # zstd exports libzstd_static and libzstd_shared; vcpkg may only provide the - # unified zstd::libzstd target. - if(TARGET zstd::libzstd_static) - set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd_static) + if(TARGET zstd::libzstd) + set(ICEBERG_ZSTD_TARGET zstd::libzstd) elseif(TARGET zstd::libzstd_shared) - set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd_shared) + set(ICEBERG_ZSTD_TARGET zstd::libzstd_shared) else() - set(ICEBERG_ZSTD_STATIC_TARGET zstd::libzstd) - endif() - if(TARGET zstd::libzstd_shared) - set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd_shared) - elseif(TARGET zstd::libzstd_static) - set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd_static) - else() - set(ICEBERG_ZSTD_SHARED_TARGET zstd::libzstd) + set(ICEBERG_ZSTD_TARGET zstd::libzstd_static) endif() endif() @@ -976,11 +974,8 @@ function(resolve_zstd_dependency) set(ZSTD_VENDORED ${ZSTD_VENDORED} PARENT_SCOPE) - set(ICEBERG_ZSTD_STATIC_TARGET - ${ICEBERG_ZSTD_STATIC_TARGET} - PARENT_SCOPE) - set(ICEBERG_ZSTD_SHARED_TARGET - ${ICEBERG_ZSTD_SHARED_TARGET} + set(ICEBERG_ZSTD_TARGET + ${ICEBERG_ZSTD_TARGET} PARENT_SCOPE) endfunction() diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index ccc04f71db..a2cb12306d 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -176,7 +176,8 @@ set(ICEBERG_SOURCES util/truncate_util.cc util/type_util.cc util/url_encoder.cc - util/uuid.cc) + util/uuid.cc + util/zstd_internal.cc) set(ICEBERG_STATIC_BUILD_INTERFACE_LIBS) set(ICEBERG_SHARED_BUILD_INTERFACE_LIBS) @@ -190,7 +191,7 @@ list(APPEND utf8proc::utf8proc ZLIB::ZLIB roaring::roaring - ${ICEBERG_ZSTD_STATIC_TARGET}) + ${ICEBERG_ZSTD_TARGET}) list(APPEND ICEBERG_SHARED_BUILD_INTERFACE_LIBS "$,nanoarrow::nanoarrow_static,$,nanoarrow::nanoarrow_shared,nanoarrow::nanoarrow_static>>" @@ -198,23 +199,21 @@ list(APPEND utf8proc::utf8proc ZLIB::ZLIB roaring::roaring - ${ICEBERG_ZSTD_SHARED_TARGET}) + ${ICEBERG_ZSTD_TARGET}) list(APPEND ICEBERG_STATIC_INSTALL_INTERFACE_LIBS "$,iceberg::nanoarrow_static,$,nanoarrow::nanoarrow_static,nanoarrow::nanoarrow_shared>>" "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,${ICEBERG_ZSTD_STATIC_TARGET}>" -) + "$,iceberg::libzstd_static,${ICEBERG_ZSTD_TARGET}>") list(APPEND ICEBERG_SHARED_INSTALL_INTERFACE_LIBS "$,iceberg::nanoarrow_static,$,nanoarrow::nanoarrow_shared,nanoarrow::nanoarrow_static>>" "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,${ICEBERG_ZSTD_SHARED_TARGET}>" -) + "$,iceberg::libzstd_static,${ICEBERG_ZSTD_TARGET}>") if(ICEBERG_SPDLOG) set(ICEBERG_HAS_SPDLOG ON) From 06d051683d43843a36522a2d595c5fb4de7e6474 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Wed, 2 Dec 2026 20:10:47 +0900 Subject: [PATCH 4/9] chore: ignore test fixtures --- dev/release/rat_exclude_files.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/dev/release/rat_exclude_files.txt b/dev/release/rat_exclude_files.txt index 7b5b3b10c8..7a1c33b478 100644 --- a/dev/release/rat_exclude_files.txt +++ b/dev/release/rat_exclude_files.txt @@ -26,4 +26,5 @@ dist/** requirements.txt test/resources/** *.json +src/iceberg/test/resources/puffin/v1/*.bin src/iceberg/util/murmurhash3_internal.* From 6172bfdc2a53c04efd53cc7f1e688622830863b2 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Wed, 2 Dec 2026 20:15:16 +0900 Subject: [PATCH 5/9] refactor: move to util --- src/iceberg/puffin/puffin_format.cc | 70 ++-------------------- src/iceberg/util/zstd_internal.cc | 93 +++++++++++++++++++++++++++++ src/iceberg/util/zstd_internal.h | 39 ++++++++++++ 3 files changed, 138 insertions(+), 64 deletions(-) create mode 100644 src/iceberg/util/zstd_internal.cc create mode 100644 src/iceberg/util/zstd_internal.h diff --git a/src/iceberg/puffin/puffin_format.cc b/src/iceberg/puffin/puffin_format.cc index ef01359029..fb608e0e6f 100644 --- a/src/iceberg/puffin/puffin_format.cc +++ b/src/iceberg/puffin/puffin_format.cc @@ -19,14 +19,11 @@ #include "iceberg/puffin/puffin_format.h" -#include - #include -#include #include #include -#include "iceberg/util/endian.h" +#include "iceberg/util/zstd_internal.h" namespace iceberg::puffin { @@ -61,25 +58,8 @@ Result> Compress(PuffinCompressionCodec codec, return std::vector(input.begin(), input.end()); case PuffinCompressionCodec::kLz4: return NotSupported("LZ4 compression is not yet supported"); - case PuffinCompressionCodec::kZstd: { - const size_t input_size = input.size(); - if (input_size > std::numeric_limits::max()) { - // Matches Java, which rejects content sizes beyond the int range. - return CompressError("Input size {} is too large to compress", input_size); - } - - const size_t max_compressed_size = ZSTD_compressBound(input_size); - std::vector output(max_compressed_size); - // Match Java's default compression level, which is 3. - const size_t compressed_size = ZSTD_compress( - output.data(), output.size(), input.data(), input.size(), ZSTD_CLEVEL_DEFAULT); - if (ZSTD_isError(compressed_size)) { - return CompressError("Failed to compress data: {}", - ZSTD_getErrorName(compressed_size)); - } - output.resize(compressed_size); - return output; - } + case PuffinCompressionCodec::kZstd: + return ZstdCompress(input); } std::unreachable(); } @@ -91,47 +71,9 @@ Result> Decompress(PuffinCompressionCodec codec, return std::vector(input.begin(), input.end()); case PuffinCompressionCodec::kLz4: return NotSupported("LZ4 decompression is not yet supported"); - case PuffinCompressionCodec::kZstd: { - if (input.size() < sizeof(uint32_t) || - ReadLittleEndian(input.data()) != ZSTD_MAGICNUMBER) { - return DecompressError("Compressed data is not a Zstandard frame"); - } - const size_t compressed_frame_size = - ZSTD_findFrameCompressedSize(input.data(), input.size()); - if (ZSTD_isError(compressed_frame_size)) { - return DecompressError("Invalid Zstandard frame: {}", - ZSTD_getErrorName(compressed_frame_size)); - } - if (compressed_frame_size != input.size()) { - return DecompressError("Found {} bytes after the Zstandard frame", - input.size() - compressed_frame_size); - } - - const uint64_t frame_size = ZSTD_getFrameContentSize(input.data(), input.size()); - if (frame_size == ZSTD_CONTENTSIZE_ERROR) { - return DecompressError("Content size of the compressed data is invalid"); - } - if (frame_size == ZSTD_CONTENTSIZE_UNKNOWN) { - return DecompressError("Content size of the compressed data is unknown"); - } - if (frame_size > std::numeric_limits::max()) { - // Matches Java, which rejects content sizes beyond the int range. - return DecompressError("Content size of the compressed data is too large"); - } - - std::vector output(frame_size); - const size_t decompressed_size = - ZSTD_decompress(output.data(), output.size(), input.data(), input.size()); - if (ZSTD_isError(decompressed_size)) { - return DecompressError("Failed to decompress data: {}", - ZSTD_getErrorName(decompressed_size)); - } - if (decompressed_size != frame_size) { - return DecompressError("Decompressed size {} does not match the expected size {}", - decompressed_size, frame_size); - } - return output; - } + case PuffinCompressionCodec::kZstd: + // The Puffin spec requires a single Zstandard frame with the content size present. + return ZstdDecompress(input); } std::unreachable(); } diff --git a/src/iceberg/util/zstd_internal.cc b/src/iceberg/util/zstd_internal.cc new file mode 100644 index 0000000000..63774a0532 --- /dev/null +++ b/src/iceberg/util/zstd_internal.cc @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#include "iceberg/util/zstd_internal.h" + +#include + +#include +#include + +#include "iceberg/util/endian.h" + +namespace iceberg { + +Result> ZstdCompress(std::span input) { + const size_t input_size = input.size(); + if (input_size > std::numeric_limits::max()) { + // ZstdDecompress() and Java reject content sizes beyond the int range. + return CompressError("Input size {} is too large to compress", input_size); + } + + const size_t max_compressed_size = ZSTD_compressBound(input_size); + std::vector output(max_compressed_size); + // Match Java's default compression level, which is 3. + const size_t compressed_size = ZSTD_compress(output.data(), output.size(), input.data(), + input.size(), ZSTD_CLEVEL_DEFAULT); + if (ZSTD_isError(compressed_size)) { + return CompressError("Failed to compress data: {}", + ZSTD_getErrorName(compressed_size)); + } + output.resize(compressed_size); + return output; +} + +Result> ZstdDecompress(std::span input) { + if (input.size() < sizeof(uint32_t) || + ReadLittleEndian(input.data()) != ZSTD_MAGICNUMBER) { + return DecompressError("Compressed data is not a Zstandard frame"); + } + const size_t compressed_frame_size = + ZSTD_findFrameCompressedSize(input.data(), input.size()); + if (ZSTD_isError(compressed_frame_size)) { + return DecompressError("Invalid Zstandard frame: {}", + ZSTD_getErrorName(compressed_frame_size)); + } + if (compressed_frame_size != input.size()) { + return DecompressError("Found {} bytes after the Zstandard frame", + input.size() - compressed_frame_size); + } + + const uint64_t frame_size = ZSTD_getFrameContentSize(input.data(), input.size()); + if (frame_size == ZSTD_CONTENTSIZE_ERROR) { + return DecompressError("Content size of the compressed data is invalid"); + } + if (frame_size == ZSTD_CONTENTSIZE_UNKNOWN) { + return DecompressError("Content size of the compressed data is unknown"); + } + if (frame_size > std::numeric_limits::max()) { + // Matches Java, which rejects content sizes beyond the int range. + return DecompressError("Content size of the compressed data is too large"); + } + + std::vector output(frame_size); + const size_t decompressed_size = + ZSTD_decompress(output.data(), output.size(), input.data(), input.size()); + if (ZSTD_isError(decompressed_size)) { + return DecompressError("Failed to decompress data: {}", + ZSTD_getErrorName(decompressed_size)); + } + if (decompressed_size != frame_size) { + return DecompressError("Decompressed size {} does not match the expected size {}", + decompressed_size, frame_size); + } + return output; +} + +} // namespace iceberg diff --git a/src/iceberg/util/zstd_internal.h b/src/iceberg/util/zstd_internal.h new file mode 100644 index 0000000000..db24d18860 --- /dev/null +++ b/src/iceberg/util/zstd_internal.h @@ -0,0 +1,39 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +#include "iceberg/result.h" + +namespace iceberg { + +/// \brief Compresses data into a single Zstandard frame that records the content size. +Result> ZstdCompress(std::span input); + +/// \brief Decompresses a single Zstandard frame that records the content size. +/// +/// Rejects skippable frames, data after the frame, and content sizes beyond the int32 +/// range. +Result> ZstdDecompress(std::span input); + +} // namespace iceberg From c97b8bb72b3dd1f6394d01a2f4e96b8d6bd2a35d Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Wed, 2 Dec 2026 20:15:31 +0900 Subject: [PATCH 6/9] doc: missing licence --- .../test/resources/puffin/v1/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/iceberg/test/resources/puffin/v1/README.md b/src/iceberg/test/resources/puffin/v1/README.md index 91553ac611..d4557a4838 100644 --- a/src/iceberg/test/resources/puffin/v1/README.md +++ b/src/iceberg/test/resources/puffin/v1/README.md @@ -1,3 +1,22 @@ + + # Puffin fixtures from Apache Iceberg Java These files are canonical Puffin files written by the Apache Iceberg Java From 19961756862d0e02beda86a349e71cfa8c317fe1 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Sat, 5 Dec 2026 00:31:50 +0900 Subject: [PATCH 7/9] fix: cmake --- .../IcebergThirdpartyToolchain.cmake | 49 ++++++++++++++++--- src/iceberg/CMakeLists.txt | 10 ++-- src/iceberg/iceberg-config.cmake.in | 8 +++ 3 files changed, 56 insertions(+), 11 deletions(-) diff --git a/cmake_modules/IcebergThirdpartyToolchain.cmake b/cmake_modules/IcebergThirdpartyToolchain.cmake index dfc906f67c..87178a2ba3 100644 --- a/cmake_modules/IcebergThirdpartyToolchain.cmake +++ b/cmake_modules/IcebergThirdpartyToolchain.cmake @@ -219,6 +219,13 @@ function(resolve_arrow_dependency) set(AWSSDK_SOURCE "SYSTEM") endif() set(ZLIB_SOURCE "SYSTEM") + # Link Arrow to the zstd that core uses instead of building another copy. + set(zstd_SOURCE "SYSTEM") + if(ICEBERG_ZSTD_TARGET STREQUAL "zstd::libzstd_shared") + set(ARROW_ZSTD_USE_SHARED ON) + else() + set(ARROW_ZSTD_USE_SHARED OFF) + endif() set(ARROW_VERBOSE_THIRDPARTY_BUILD OFF) set(CMAKE_CXX_STANDARD 20) @@ -908,6 +915,14 @@ function(resolve_zstd_dependency) set(ZSTD_BUILD_SHARED OFF) set(ZSTD_BUILD_STATIC ON) set(ZSTD_MULTITHREAD_SUPPORT OFF) + # zstd creates an "uninstall" target unless one exists, and the Thrift that vendored + # Arrow builds later creates one unconditionally. Define a placeholder that only + # zstd's directories can see, so that zstd skips its own. + set(ICEBERG_ZSTD_PROJECT_INCLUDE + "${CMAKE_CURRENT_BINARY_DIR}/iceberg_zstd_project.cmake") + file(WRITE "${ICEBERG_ZSTD_PROJECT_INCLUDE}" + "if(NOT TARGET uninstall)\n add_library(uninstall INTERFACE IMPORTED)\nendif()\n") + set(CMAKE_PROJECT_zstd_INCLUDE "${ICEBERG_ZSTD_PROJECT_INCLUDE}") set(ICEBERG_ZSTD_BUILD_VERSION "1.5.7") set(ICEBERG_ZSTD_BUILD_SHA256_CHECKSUM @@ -950,17 +965,37 @@ function(resolve_zstd_dependency) install(FILES "${zstd_SOURCE_DIR}/LICENSE" DESTINATION "${ICEBERG_INSTALL_DOCDIR}" RENAME "LICENSE.zstd") - set(ICEBERG_ZSTD_TARGET libzstd_static) + # Arrow and Avro link zstd::libzstd_static. Unlike an ALIAS, an imported target + # is exported by name, so Arrow's exports do not depend on libzstd_static, which + # zstd also adds to its own export set. + if(NOT TARGET zstd::libzstd_static) + add_library(zstd::libzstd_static INTERFACE IMPORTED) + target_link_libraries(zstd::libzstd_static INTERFACE libzstd_static) + endif() + # Let find_package(zstd) in Arrow and Avro find this build. FetchContent does not + # write this redirect with FETCHCONTENT_TRY_FIND_PACKAGE_MODE=NEVER. + if(NOT EXISTS "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/zstd-config.cmake" + AND NOT EXISTS "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/zstdConfig.cmake") + file(WRITE "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/zstd-config.cmake" "") + endif() + include(CMakePackageConfigHelpers) + write_basic_package_version_file( + "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/zstd-config-version.cmake" + VERSION ${ICEBERG_ZSTD_BUILD_VERSION} + COMPATIBILITY AnyNewerVersion) + set(ICEBERG_ZSTD_TARGET zstd::libzstd_static) else() set(ZSTD_VENDORED FALSE) list(APPEND ICEBERG_SYSTEM_DEPENDENCIES zstd) message(STATUS "Found zstd, version: ${zstd_VERSION}") - if(TARGET zstd::libzstd) - set(ICEBERG_ZSTD_TARGET zstd::libzstd) - elseif(TARGET zstd::libzstd_shared) + # Prefer the shared library so that all of them link + # the same one. zstd::libzstd is only defined by zstd 1.5.6 and later. + if(TARGET zstd::libzstd_shared) set(ICEBERG_ZSTD_TARGET zstd::libzstd_shared) - else() + elseif(TARGET zstd::libzstd_static) set(ICEBERG_ZSTD_TARGET zstd::libzstd_static) + else() + set(ICEBERG_ZSTD_TARGET zstd::libzstd) endif() endif() @@ -1031,6 +1066,8 @@ resolve_nanoarrow_dependency() resolve_croaring_dependency() resolve_utf8proc_dependency() resolve_nlohmann_json_dependency() +# Resolve zstd before Arrow and Avro, which reuse it. +resolve_zstd_dependency() # Scan scheduling needs threading primitives even when spdlog is disabled. find_package(Threads REQUIRED) @@ -1060,8 +1097,6 @@ if(ICEBERG_BUILD_BUNDLE) resolve_avro_dependency() endif() -resolve_zstd_dependency() - if(ICEBERG_BUILD_REST) resolve_cpr_dependency() endif() diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index 19dbfad0ff..f1be7b3a4b 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -180,9 +180,9 @@ set(ICEBERG_SOURCES util/type_util.cc util/url_encoder.cc util/uuid.cc + util/zstd_internal.cc view/view_metadata.cc - view/view_version.cc - util/zstd_internal.cc) + view/view_version.cc) set(ICEBERG_STATIC_BUILD_INTERFACE_LIBS) set(ICEBERG_SHARED_BUILD_INTERFACE_LIBS) @@ -211,14 +211,16 @@ list(APPEND "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,${ICEBERG_ZSTD_TARGET}>") + "$,iceberg::libzstd_static,$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>" +) list(APPEND ICEBERG_SHARED_INSTALL_INTERFACE_LIBS "$,iceberg::nanoarrow_static,$,nanoarrow::nanoarrow_shared,nanoarrow::nanoarrow_static>>" "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,${ICEBERG_ZSTD_TARGET}>") + "$,iceberg::libzstd_static,$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>" +) if(ICEBERG_SPDLOG) set(ICEBERG_HAS_SPDLOG ON) diff --git a/src/iceberg/iceberg-config.cmake.in b/src/iceberg/iceberg-config.cmake.in index c93cfc0cfe..944dd5acd6 100644 --- a/src/iceberg/iceberg-config.cmake.in +++ b/src/iceberg/iceberg-config.cmake.in @@ -80,6 +80,14 @@ iceberg_find_dependencies("${ICEBERG_SYSTEM_DEPENDENCIES}") include("${CMAKE_CURRENT_LIST_DIR}/iceberg-targets.cmake") +# Vendored Arrow and Avro link zstd by the target name that zstd's package config +# defines. +if(TARGET iceberg::libzstd_static + AND NOT TARGET zstd::libzstd_static + AND (TARGET iceberg::arrow_static OR TARGET iceberg::avrocpp_s)) + add_library(zstd::libzstd_static ALIAS iceberg::libzstd_static) +endif() + if(TARGET iceberg::arrow_static) add_library(Arrow::arrow_static ALIAS iceberg::arrow_static) From 42e2397ce15dd74ebba7d622fee426016ef657a9 Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Sat, 5 Dec 2026 01:09:18 +0900 Subject: [PATCH 8/9] fix: use same install zstd target --- src/iceberg/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/iceberg/CMakeLists.txt b/src/iceberg/CMakeLists.txt index f1be7b3a4b..a87358cbb2 100644 --- a/src/iceberg/CMakeLists.txt +++ b/src/iceberg/CMakeLists.txt @@ -211,7 +211,7 @@ list(APPEND "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>" + "$,iceberg::libzstd_static,$,${ICEBERG_ZSTD_TARGET},$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>>" ) list(APPEND ICEBERG_SHARED_INSTALL_INTERFACE_LIBS @@ -219,7 +219,7 @@ list(APPEND "$,iceberg::nlohmann_json,$,nlohmann_json::nlohmann_json,nlohmann_json::nlohmann_json>>" "$,iceberg::utf8proc,utf8proc::utf8proc>" "$,iceberg::roaring,roaring::roaring>" - "$,iceberg::libzstd_static,$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>" + "$,iceberg::libzstd_static,$,${ICEBERG_ZSTD_TARGET},$,zstd::libzstd_shared,$,zstd::libzstd_static,zstd::libzstd>>>>" ) if(ICEBERG_SPDLOG) From 5d88e5e80aef4acf526b244ce92703e2b3235a7a Mon Sep 17 00:00:00 2001 From: lani_karrot Date: Sat, 5 Dec 2026 02:06:00 +0900 Subject: [PATCH 9/9] fix: remove alias --- src/iceberg/iceberg-config.cmake.in | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/iceberg/iceberg-config.cmake.in b/src/iceberg/iceberg-config.cmake.in index 944dd5acd6..f90a3f4eb0 100644 --- a/src/iceberg/iceberg-config.cmake.in +++ b/src/iceberg/iceberg-config.cmake.in @@ -80,12 +80,21 @@ iceberg_find_dependencies("${ICEBERG_SYSTEM_DEPENDENCIES}") include("${CMAKE_CURRENT_LIST_DIR}/iceberg-targets.cmake") -# Vendored Arrow and Avro link zstd by the target name that zstd's package config -# defines. -if(TARGET iceberg::libzstd_static - AND NOT TARGET zstd::libzstd_static - AND (TARGET iceberg::arrow_static OR TARGET iceberg::avrocpp_s)) - add_library(zstd::libzstd_static ALIAS iceberg::libzstd_static) +# Vendored Arrow and Avro link zstd by the target names that zstd's package config +# defines. Point them at the vendored zstd, so that a zstd package that the +# consumer finds is not linked as well. +if(TARGET iceberg::libzstd_static) + foreach(_iceberg_target iceberg::arrow_static iceberg::avrocpp_s) + if(TARGET ${_iceberg_target}) + get_target_property(_iceberg_libs ${_iceberg_target} INTERFACE_LINK_LIBRARIES) + string(REGEX REPLACE "zstd::libzstd(_shared|_static)?" "iceberg::libzstd_static" + _iceberg_libs "${_iceberg_libs}") + set_target_properties(${_iceberg_target} PROPERTIES INTERFACE_LINK_LIBRARIES + "${_iceberg_libs}") + endif() + endforeach() + unset(_iceberg_libs) + unset(_iceberg_target) endif() if(TARGET iceberg::arrow_static)