Repository navigation
Parse only the Parquet column chunk metadata that a query reads - #124364
grantholly-clickhouse merged 9 commits into
Conversation
The native Parquet reader deserialized the whole footer (every ColumnChunk of every row group) before knowing which columns a query reads, and the metadata cache returned a deep copy of the parsed FileMetaData on every hit and miss. Now the footer is parsed by the generated FileMetaData::read through a protocol that skips RowGroup::columns and records where each serialized ColumnChunk starts (`deserializeFileMetaDataWithoutColumnChunks`). Each Reader parses only the column chunks of its primitive columns with the generated ColumnChunk::read, at the recursion depth of a full parse and with an exact end check (`deserializeColumnChunks`); count(), schema inference and bucket splitting parse none. A bloom filter without a length needs the offsets of all chunks: that fallback adds the missing ones to the reader's columns, so a cache hit keeps them like any other. The metadata cache stores an immutable `Parquet::FileFooter` (that skeleton, the serialized bytes and the offsets) and the column chunks parsed so far, one immutable `FileColumnChunks` per column, shared without copying. A reader takes the cached columns it reads, parses only the missing ones, and after a cache hit adds them to the entry (`ParquetMetadataCache::addColumnChunks`). Adding replaces the cell with `CacheBase::replaceIfMatches`, which does nothing if the cell is no longer resident: an add never re-inserts an entry that `SYSTEM DROP PARQUET METADATA CACHE` or an eviction removed, and never overwrites a newer cell. Adding only after a hit keeps the SLRU queue of the entry where it was: a set right after the inserting miss would move every file read once to the protected queue. The weight of a cell counts its column chunks: element storage once by capacity, plus their nested allocations. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 5 rounds, 9 findings) plus my own review.
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261007-045300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261007-021000 |
|
Workflow [PR], commit [d4cb214] Summary: ✅
AI ReviewSummaryThe PR parses Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings or thread updates are needed. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes how the Parquet reader reads file metadata: it skips the per-column entries in the footer and parses only the columns a query needs, plus some small CacheBase and GeoFilter changes. That is a one-time cost per file, so it cannot plausibly explain a -42.0% CPU-backed speedup on the ClickBench Q20 LIKE scan, or +18.7% to +25.0% slowdowns on the GROUP BY queries Q30-Q32. A footer-wide change would also move all queries the same way, not in opposite directions. Q30 and Q31 sit inside master's recent range and Q32 lands just above it, so all four flags are downgraded to not_sure, and nothing in this diff links it to these deltas. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes18 object files changed (+199.89 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units712 translation units recompiled, 6688 s compile time in total, 711 of them have a recent master baseline. Translation units without a recent master baseline:
|
std::mt19937::result_type is uint_fast32_t, which is 32-bit on macOS, so seeding it from a size_t fails there with -Wshorten-64-to-32. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
When the footer isn't cached,
16 Method4-core Graviton3, release builds of master 85c3e1d, of this PR (b8c2933) on it, and of this PR with the diff below. All three also had an unrelated local change (lazy Diff on top of b8c2933diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp
index 7523c98..39ac916 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.cpp
+++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp
@@ -228,6 +228,34 @@ void Reader::init(const ReadOptions & options_, const Block & sample_block_, For
format_filter_info = format_filter_info_;
}
+size_t Reader::readFileNumRows(Prefetcher & prefetcher, size_t footer_read_size)
+{
+ size_t file_size = prefetcher.getFileSize();
+ if (file_size <= 8)
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Parquet file too short: {} bytes", file_size);
+ if (footer_read_size == 0)
+ footer_read_size = std::clamp<size_t>(file_size / 100, 128ul << 10, 2ul << 20);
+ size_t initial_read_size = std::min(file_size, std::max<size_t>(footer_read_size, 8));
+ PODArray<char> buf(initial_read_size);
+ prefetcher.readSync(buf.data(), initial_read_size, file_size - initial_read_size);
+ if (memcmp(buf.data() + initial_read_size - 4, "PAR1", 4) != 0)
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Not a Parquet file (wrong magic bytes at the end of file)");
+ int32_t metadata_size_i32 = 0;
+ memcpy(&metadata_size_i32, buf.data() + initial_read_size - 8, 4);
+ if (metadata_size_i32 <= 0 || size_t(metadata_size_i32) + 8 > file_size)
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Bad metadata size in parquet file: {} bytes", metadata_size_i32);
+ size_t metadata_size = size_t(metadata_size_i32);
+ if (metadata_size + 8 > initial_read_size)
+ {
+ size_t remaining_bytes_to_read = metadata_size + 8 - initial_read_size;
+ PODArray<char> full(metadata_size);
+ memcpy(full.data() + remaining_bytes_to_read, buf.data(), initial_read_size - 8);
+ prefetcher.readSync(full.data(), remaining_bytes_to_read, file_size - metadata_size - 8);
+ return size_t(deserializeFileMetaDataNumRows(full.data(), metadata_size));
+ }
+ return size_t(deserializeFileMetaDataNumRows(buf.data() + initial_read_size - 8 - metadata_size, metadata_size));
+}
+
std::shared_ptr<const FileFooter> Reader::readFileFooter(Prefetcher & prefetcher, size_t footer_read_size)
{
/// Parquet file ends with:
diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h
index 4d61830..3953880 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.h
+++ b/src/Processors/Formats/Impl/Parquet/Reader.h
@@ -590,6 +590,8 @@ struct Reader
/// `footer_read_size` overrides the initial footer read size; 0 sizes it adaptively to the file.
static std::shared_ptr<const FileFooter> readFileFooter(Prefetcher & prefetcher, size_t footer_read_size);
+ /// Reads the same footer bytes, but parses only the number of rows (for count()).
+ static size_t readFileNumRows(Prefetcher & prefetcher, size_t footer_read_size);
/// Works around writer bugs in column chunk metadata.
static void fixUpColumnChunk(parq::ColumnChunk & column, bool written_by_old_duckdb);
/// `cached_column_chunks`, by Parquet column index (nullptr = absent), were parsed from `footer`.
diff --git a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
index 72579e2..d17ec7c 100644
--- a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
@@ -9,6 +9,7 @@
#include <thrift/transport/TBufferTransports.h>
#include <array>
+#include <optional>
#include <sstream>
namespace DB::ErrorCodes
@@ -287,6 +288,57 @@ void deserializeColumnChunks(
column.memory_bytes += column.chunks.capacity() * sizeof(parq::ColumnChunk);
}
+int64_t deserializeFileMetaDataNumRows(const char * buf, size_t limit)
+{
+ std::optional<int64_t> num_rows;
+ try
+ {
+ limit = std::min(limit, size_t(UINT32_MAX));
+ uint8_t * cast_buf = const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(buf));
+ const auto size_limit = int32_t(std::min(limit, size_t(std::numeric_limits<int32_t>::max())));
+ auto configuration = std::make_shared<apache::thrift::TConfiguration>(/*maxMessageSize=*/ size_limit);
+ auto trans = std::make_shared<apache::thrift::transport::TMemoryBuffer>(cast_buf, uint32_t(limit), apache::thrift::transport::TMemoryBuffer::OBSERVE, configuration);
+ apache::thrift::protocol::TCompactProtocolT<apache::thrift::transport::TMemoryBuffer> proto(
+ trans, /*string_limit=*/ size_limit, /*container_limit=*/ size_limit);
+
+ std::string field_name;
+ apache::thrift::protocol::TType field_type = apache::thrift::protocol::T_STOP;
+ int16_t field_id = 0;
+ proto.readStructBegin(field_name);
+ while (true)
+ {
+ proto.readFieldBegin(field_name, field_type, field_id);
+ if (field_type == apache::thrift::protocol::T_STOP)
+ break;
+ /// `num_rows` is field 3. Writers emit fields in id order, so only `version` and `schema`
+ /// are skipped before it, and the row groups after it are never read.
+ if (field_id == 3 && field_type == apache::thrift::protocol::T_I64)
+ {
+ int64_t value = 0;
+ proto.readI64(value);
+ num_rows = value;
+ break;
+ }
+ proto.skip(field_type);
+ proto.readFieldEnd();
+ }
+ }
+ catch (const apache::thrift::TException & e)
+ {
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Failed to parse Parquet Thrift metadata from {} bytes: {}", limit, e.what());
+ }
+ catch (const std::exception & e)
+ {
+ throw Exception(Exception::CreateFromSTDTag(), e);
+ }
+
+ if (!num_rows.has_value())
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Parquet file metadata has no num_rows");
+ if (*num_rows < 0)
+ throw Exception(ErrorCodes::INCORRECT_DATA, "Negative num_rows in Parquet file metadata: {}", *num_rows);
+ return *num_rows;
+}
+
template <typename T>
std::string thriftToString(const T & obj)
{
diff --git a/src/Processors/Formats/Impl/Parquet/ThriftUtil.h b/src/Processors/Formats/Impl/Parquet/ThriftUtil.h
index c1abec5..cafa685 100644
--- a/src/Processors/Formats/Impl/Parquet/ThriftUtil.h
+++ b/src/Processors/Formats/Impl/Parquet/ThriftUtil.h
@@ -62,6 +62,10 @@ size_t serializeThriftStruct(const T & obj, WriteBuffer & out);
template <typename T>
size_t deserializeThriftStruct(T & out, const char * buf, size_t limit);
+/// Reads only `num_rows` of a serialized FileMetaData: skips the fields before it (version and
+/// schema) and stops right after it, without deserializing the row groups and their column chunks.
+int64_t deserializeFileMetaDataNumRows(const char * buf, size_t limit);
+
template <typename T>
std::string thriftToString(const T &obj);
diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
index 9fdb566..fc49c76 100644
--- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
+++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
@@ -17,6 +17,11 @@
#include <Interpreters/Context.h>
#include <Processors/Formats/Impl/Parquet/SchemaConverter.h>
+namespace ProfileEvents
+{
+ extern const Event ParquetMetadataCacheHits;
+}
+
namespace DB
{
@@ -46,7 +51,8 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat(
FormatFilterInfoPtr format_filter_info_,
size_t min_bytes_for_seek,
ParquetMetadataCachePtr metadata_cache_,
- const std::optional<RelativePathWithMetadata> & object_with_metadata_)
+ const std::optional<RelativePathWithMetadata> & object_with_metadata_,
+ bool is_remote_fs_)
: IInputFormat(header_, &buf)
, format_settings(format_settings_)
, read_options(convertReadOptions(format_settings))
@@ -54,6 +60,7 @@ ParquetV3BlockInputFormat::ParquetV3BlockInputFormat(
, format_filter_info(format_filter_info_)
, metadata_cache(metadata_cache_)
, object_with_metadata(object_with_metadata_)
+ , read_from_remote_fs(is_remote_fs_)
{
read_options.min_bytes_for_seek = min_bytes_for_seek;
read_options.bytes_per_read_task = min_bytes_for_seek * 4;
@@ -138,6 +145,23 @@ std::shared_ptr<const Parquet::FileFooter> ParquetV3BlockInputFormat::getFileFoo
return readFileFooter(prefetcher);
}
+size_t ParquetV3BlockInputFormat::getFileNumRows(Parquet::Prefetcher & prefetcher) const
+{
+ if (auto cache_key = getMetadataCacheKey())
+ {
+ /// A remote footer is cached, so that a query reading the data next doesn't fetch it again.
+ if (read_from_remote_fs)
+ return size_t(getFileFooter(prefetcher)->metadata.num_rows);
+ if (auto cell = metadata_cache->get(*cache_key))
+ {
+ ProfileEvents::increment(ProfileEvents::ParquetMetadataCacheHits);
+ return size_t(cell->footer->metadata.num_rows);
+ }
+ }
+ /// Reading a local footer again is cheap, parsing it is not: parse only the number of rows.
+ return Parquet::Reader::readFileNumRows(prefetcher, read_options.format.parquet.footer_read_size);
+}
+
Chunk ParquetV3BlockInputFormat::read()
{
if (need_only_count)
@@ -148,10 +172,7 @@ Chunk ParquetV3BlockInputFormat::read()
/// Don't init Reader and ReadManager if we only need file metadata.
Parquet::Prefetcher temp_prefetcher;
temp_prefetcher.init(in, read_options, parser_shared_resources);
- auto footer = getFileFooter(temp_prefetcher);
-
-
- auto chunk = getChunkForCount(size_t(footer->metadata.num_rows));
+ auto chunk = getChunkForCount(getFileNumRows(temp_prefetcher));
chunk.getChunkInfos().add(std::make_shared<ChunkInfoRowNumbers>(0));
reported_count = true;
@@ -393,7 +414,8 @@ void registerInputFormatParquet(FormatFactory & factory)
std::move(format_filter_info),
min_bytes_for_seek,
metadata_cache,
- object_with_metadata
+ object_with_metadata,
+ is_remote_fs
);
});
factory.registerRandomAccessInputFormat(
diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
index 051fba9..dba5a3e 100644
--- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
+++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
@@ -46,7 +46,8 @@ public:
FormatFilterInfoPtr format_filter_info_,
size_t min_bytes_for_seek,
ParquetMetadataCachePtr metadata_cache_ = nullptr,
- const std::optional<RelativePathWithMetadata> & object_with_metadata_ = std::nullopt);
+ const std::optional<RelativePathWithMetadata> & object_with_metadata_ = std::nullopt,
+ bool is_remote_fs_ = false);
void resetParser() override;
@@ -76,6 +77,7 @@ private:
FormatFilterInfoPtr format_filter_info;
ParquetMetadataCachePtr metadata_cache;
const std::optional<RelativePathWithMetadata> object_with_metadata;
+ const bool read_from_remote_fs;
/// (This mutex is not important. It protects `reader.emplace` in a weird case where onCancel()
/// may be called in parallel with first read(). ReadManager itself is thread safe for that,
@@ -96,6 +98,7 @@ private:
std::shared_ptr<const Parquet::FileFooter> readFileFooter(Parquet::Prefetcher & prefetcher) const;
/// For count(), which needs no column chunks.
std::shared_ptr<const Parquet::FileFooter> getFileFooter(Parquet::Prefetcher & prefetcher) const;
+ size_t getFileNumRows(Parquet::Prefetcher & prefetcher) const;
};
class NativeParquetSchemaReader final : public ISchemaReader |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-chunks Resolve the conflict in `Reader.h` (keep `readFileFooter` with the new comment about the 64 KiB local footer read, and add `readMinMaxFromStatistics` / `min_max_chunk` from master), and adapt the code from master that read column chunks from `RowGroup::columns` (`readMinMaxFromStatistics`, `getHyperrectangleForRowGroup`) to `numColumnChunks` / `getColumnChunk`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
In a fresh
A Checks:
Method4-core Graviton3, Release builds without LTO. Both builds are master f20e47b with this PR and eight other open PRs (#124552, #124829, #124859, #124863, #124864, #124899, #124951, #124959). Their Diff on top of d70d6b5diff --git a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
index 72579e24fb4..5b6751f1e70 100644
--- a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
@@ -125,9 +125,188 @@ size_t columnChunkNestedMemory(const parq::ColumnChunk & column_chunk)
return total_size;
}
+/// Skips compact protocol values in place. Accepts and rejects the same input as
+/// `apache::thrift::protocol::skip` on `CompactProtocol` with the same size and recursion limits,
+/// but does not read through the transport value by value or copy strings.
+class CompactValueSkipper
+{
+public:
+ CompactValueSkipper(const uint8_t * end_, int32_t size_limit_, uint32_t recursion_limit_)
+ : end(end_), size_limit(size_limit_), recursion_limit(recursion_limit_)
+ {
+ }
+
+ /// `depth` is the recursion depth of the struct itself, as counted by TInputRecursionTracker.
+ const uint8_t * skipStruct(const uint8_t * pos, uint32_t depth) const
+ {
+ checkDepth(depth);
+ while (true)
+ {
+ need(pos, 1);
+ const uint8_t header = *pos++;
+ const uint8_t type = header & 0x0f;
+ if (type == STOP)
+ return pos;
+ /// A zero delta means that the field id follows as a varint.
+ if ((header >> 4) == 0)
+ pos = skipVarint(pos);
+ pos = skipValue(pos, type, depth + 1, /*in_container=*/ false);
+ }
+ }
+
+private:
+ enum : uint8_t
+ {
+ STOP = 0x00, BOOLEAN_TRUE = 0x01, BOOLEAN_FALSE = 0x02, BYTE = 0x03, I16 = 0x04, I32 = 0x05, I64 = 0x06,
+ DOUBLE = 0x07, BINARY = 0x08, LIST = 0x09, SET = 0x0A, MAP = 0x0B, STRUCT = 0x0C, UUID = 0x0D,
+ };
+
+ const uint8_t * const end;
+ const int32_t size_limit;
+ const uint32_t recursion_limit;
+
+ void checkDepth(uint32_t depth) const
+ {
+ if (depth > recursion_limit)
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::DEPTH_LIMIT);
+ }
+
+ void need(const uint8_t * pos, size_t bytes) const
+ {
+ if (static_cast<size_t>(end - pos) < bytes)
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "Unexpected end of Thrift data");
+ }
+
+ static void checkType(uint8_t type)
+ {
+ if (type > UUID)
+ throw apache::thrift::TException(std::string("don't know what type: ") + static_cast<char>(type));
+ }
+
+ const uint8_t * skipVarint(const uint8_t * pos) const
+ {
+ for (size_t i = 0; i < 10; ++i)
+ {
+ need(pos, 1);
+ if (!(*pos++ & 0x80))
+ return pos;
+ }
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes.");
+ }
+
+ /// Like TCompactProtocol::readVarint32: a varint of up to 10 bytes truncated to 32 bits.
+ const uint8_t * readSize(const uint8_t * pos, int32_t & size) const
+ {
+ uint64_t value = 0;
+ for (size_t i = 0; i < 10; ++i)
+ {
+ need(pos, 1);
+ const uint8_t byte = *pos++;
+ value |= static_cast<uint64_t>(byte & 0x7f) << (7 * i);
+ if (!(byte & 0x80))
+ {
+ size = static_cast<int32_t>(static_cast<uint32_t>(value));
+ if (size < 0)
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::NEGATIVE_SIZE);
+ if (size_limit > 0 && size > size_limit)
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::SIZE_LIMIT);
+ return pos;
+ }
+ }
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes.");
+ }
+
+ const uint8_t * skipValue(const uint8_t * pos, uint8_t type, uint32_t depth, bool in_container) const
+ {
+ checkDepth(depth);
+ switch (type)
+ {
+ case BOOLEAN_TRUE:
+ case BOOLEAN_FALSE:
+ /// The value of a bool field is in the field header, a bool element takes one byte.
+ if (!in_container)
+ return pos;
+ need(pos, 1);
+ return pos + 1;
+ case BYTE:
+ need(pos, 1);
+ return pos + 1;
+ case I16:
+ case I32:
+ case I64:
+ return skipVarint(pos);
+ case DOUBLE:
+ need(pos, 8);
+ return pos + 8;
+ case UUID:
+ need(pos, 16);
+ return pos + 16;
+ case BINARY:
+ {
+ int32_t size = 0;
+ pos = readSize(pos, size);
+ need(pos, size_t(size));
+ return pos + size;
+ }
+ case STRUCT:
+ return skipStruct(pos, depth);
+ case LIST:
+ case SET:
+ {
+ need(pos, 1);
+ const uint8_t header = *pos++;
+ int32_t size = (header >> 4) & 0x0f;
+ if (size == 15)
+ pos = readSize(pos, size);
+ else if (size_limit > 0 && size > size_limit)
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::SIZE_LIMIT);
+ const uint8_t element_type = header & 0x0f;
+ checkType(element_type);
+ for (int32_t i = 0; i < size; ++i)
+ {
+ if (element_type == STOP)
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "invalid TType");
+ pos = skipValue(pos, element_type, depth + 1, /*in_container=*/ true);
+ }
+ return pos;
+ }
+ case MAP:
+ {
+ int32_t size = 0;
+ pos = readSize(pos, size);
+ if (size == 0)
+ return pos;
+ need(pos, 1);
+ const uint8_t types = *pos++;
+ const uint8_t key_type = types >> 4;
+ const uint8_t value_type = types & 0x0f;
+ checkType(key_type);
+ checkType(value_type);
+ for (int32_t i = 0; i < size; ++i)
+ {
+ if (key_type == STOP || value_type == STOP)
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "invalid TType");
+ pos = skipValue(pos, key_type, depth + 1, /*in_container=*/ true);
+ pos = skipValue(pos, value_type, depth + 1, /*in_container=*/ true);
+ }
+ return pos;
+ }
+ default:
+ checkType(type);
+ throw apache::thrift::protocol::TProtocolException(
+ apache::thrift::protocol::TProtocolException::INVALID_DATA, "invalid TType");
+ }
+ }
+};
+
/// Hides the methods that the generated `FileMetaData::read` calls, to skip the elements of
-/// `RowGroup::columns` instead of reading them. `skip` is `TVirtualProtocol<CompactProtocol>::skip`,
-/// so skipped values never come back here.
+/// `RowGroup::columns` instead of reading them. The elements are skipped on the transport's bytes
+/// by CompactValueSkipper, so skipped values never come back here.
class ColumnChunkSkippingProtocol : public CompactProtocol
{
public:
@@ -173,17 +352,24 @@ public:
auto & row_group_offsets = offsets.back();
row_group_offsets.clear();
row_group_offsets.reserve(size + 1);
- /// `skip` counts every value against the recursion limit, the generated reader only structs.
- /// One level less accepts every column chunk that the generated reader accepts.
- decrementInputRecursionDepth();
+ uint32_t available = 0;
+ const uint8_t * begin = trans_->borrow(nullptr, &available);
+ const UInt32 begin_position = position();
+ const CompactValueSkipper skipper(begin + available, sizeLimit(limit), getRecursionLimit());
+ const uint8_t * pos = begin;
for (uint32_t i = 0; i < size; ++i)
{
- row_group_offsets.push_back(position());
+ row_group_offsets.push_back(begin_position + UInt32(pos - begin));
/// Read as a struct whatever the declared element type, like the generated reader.
- bytes += skip(apache::thrift::protocol::T_STRUCT);
+ /// The generated reader would read the column chunk at depth 3 (FileMetaData, RowGroup,
+ /// ColumnChunk), but `skip` also counts every value against the recursion limit, so one
+ /// level less accepts every column chunk that the generated reader accepts.
+ pos = skipper.skipStruct(pos, /*depth=*/ 2);
}
+ const auto skipped = UInt32(pos - begin);
+ trans_->consume(skipped);
+ bytes += skipped;
row_group_offsets.push_back(position());
- incrementInputRecursionDepth();
size = 0;
}
return bytes;Feel free to take it into this PR. |
|
A faster replacement for the diff in my previous comment. There, Measured as before, against this PR:
None of the 19 measured queries is slower (highest ratio: Q24, 1.004, not significant). In 15 interleaved runs of this PR, the first diff and the new one, the Checks:
Diff on top of d70d6b5 (replaces the previous one)diff --git a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
index 72579e24fb4..e1a891fc528 100644
--- a/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ThriftUtil.cpp
@@ -1,6 +1,7 @@
#include <Processors/Formats/Impl/Parquet/ThriftUtil.h>
#include <Common/Exception.h>
+#include <base/defines.h>
#include <IO/WriteBuffer.h>
#include <fmt/format.h>
@@ -125,9 +126,247 @@ size_t columnChunkNestedMemory(const parq::ColumnChunk & column_chunk)
return total_size;
}
+/// Skips compact protocol values in place. Accepts and rejects the same input as
+/// `apache::thrift::protocol::skip` on `CompactProtocol` with the same size and recursion limits,
+/// but does not read through the transport value by value or copy strings.
+class CompactValueSkipper
+{
+public:
+ CompactValueSkipper(const uint8_t * end_, int32_t size_limit_, uint32_t recursion_limit_)
+ : end(end_), size_limit(size_limit_), recursion_limit(recursion_limit_)
+ {
+ }
+
+ /// `depth` is the recursion depth of the struct itself, as counted by TInputRecursionTracker,
+ /// which also counts every field value one level deeper.
+ const uint8_t * skipStruct(const uint8_t * pos, uint32_t depth) const
+ {
+ if (depth > recursion_limit) [[unlikely]]
+ throwDepthLimit();
+ while (true)
+ {
+ need(pos, 1);
+ const uint8_t header = *pos++;
+ const uint8_t type = header & 0x0f;
+ if (type == STOP)
+ return pos;
+ if (depth >= recursion_limit) [[unlikely]]
+ throwDepthLimit();
+ /// A zero delta means that the field id follows as a varint.
+ if ((header >> 4) == 0)
+ pos = skipVarint(pos);
+ switch (type)
+ {
+ case BOOLEAN_TRUE:
+ case BOOLEAN_FALSE:
+ /// The value of a bool field is in the field header.
+ break;
+ case I16:
+ case I32:
+ case I64:
+ pos = skipVarint(pos);
+ break;
+ case BINARY:
+ pos = skipBinary(pos);
+ break;
+ default:
+ pos = skipValue(pos, type, depth + 1);
+ break;
+ }
+ }
+ }
+
+private:
+ enum : uint8_t
+ {
+ STOP = 0x00, BOOLEAN_TRUE = 0x01, BOOLEAN_FALSE = 0x02, BYTE = 0x03, I16 = 0x04, I32 = 0x05, I64 = 0x06,
+ DOUBLE = 0x07, BINARY = 0x08, LIST = 0x09, SET = 0x0A, MAP = 0x0B, STRUCT = 0x0C, UUID = 0x0D,
+ };
+
+ const uint8_t * const end;
+ const int32_t size_limit;
+ const uint32_t recursion_limit;
+
+ [[noreturn]] static NO_INLINE void throwInvalidData(const char * message)
+ {
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::INVALID_DATA, message);
+ }
+
+ [[noreturn]] static NO_INLINE void throwDepthLimit()
+ {
+ throw apache::thrift::protocol::TProtocolException(apache::thrift::protocol::TProtocolException::DEPTH_LIMIT);
+ }
+
+ [[noreturn]] static NO_INLINE void throwBadSize(bool negative)
+ {
+ throw apache::thrift::protocol::TProtocolException(
+ negative ? apache::thrift::protocol::TProtocolException::NEGATIVE_SIZE : apache::thrift::protocol::TProtocolException::SIZE_LIMIT);
+ }
+
+ [[noreturn]] static NO_INLINE void throwUnknownType(uint8_t type)
+ {
+ throw apache::thrift::TException(std::string("don't know what type: ") + static_cast<char>(type));
+ }
+
+ ALWAYS_INLINE void need(const uint8_t * pos, size_t bytes) const
+ {
+ if (static_cast<size_t>(end - pos) < bytes) [[unlikely]]
+ throwInvalidData("Unexpected end of Thrift data");
+ }
+
+ static ALWAYS_INLINE void checkType(uint8_t type)
+ {
+ if (type > UUID) [[unlikely]]
+ throwUnknownType(type);
+ }
+
+ ALWAYS_INLINE const uint8_t * skipVarint(const uint8_t * pos) const
+ {
+ /// Like TCompactProtocol::readVarint64: at most 10 bytes.
+ for (size_t i = 0; i < 10; ++i)
+ {
+ need(pos, 1);
+ if (!(*pos++ & 0x80))
+ return pos;
+ }
+ throwInvalidData("Variable-length int over 10 bytes.");
+ }
+
+ /// Like TCompactProtocol::readVarint32 and its callers: a varint of up to 10 bytes truncated to 32 bits.
+ ALWAYS_INLINE const uint8_t * readSize(const uint8_t * pos, int32_t & size) const
+ {
+ uint64_t value = 0;
+ for (size_t i = 0; i < 10; ++i)
+ {
+ need(pos, 1);
+ const uint8_t byte = *pos++;
+ value |= static_cast<uint64_t>(byte & 0x7f) << (7 * i);
+ if (!(byte & 0x80))
+ {
+ size = static_cast<int32_t>(static_cast<uint32_t>(value));
+ if (size < 0 || (size_limit > 0 && size > size_limit)) [[unlikely]]
+ throwBadSize(size < 0);
+ return pos;
+ }
+ }
+ throwInvalidData("Variable-length int over 10 bytes.");
+ }
+
+ ALWAYS_INLINE const uint8_t * skipBinary(const uint8_t * pos) const
+ {
+ int32_t size = 0;
+ pos = readSize(pos, size);
+ need(pos, size_t(size));
+ return pos + size;
+ }
+
+ /// Skips `count` elements of a list, set or map of the given element type; elements are at `depth`.
+ const uint8_t * skipElements(const uint8_t * pos, uint8_t type, int32_t count, uint32_t depth) const
+ {
+ if (count == 0)
+ return pos;
+ if (type == STOP) [[unlikely]]
+ throwInvalidData("invalid TType");
+ if (depth > recursion_limit) [[unlikely]]
+ throwDepthLimit();
+ switch (type)
+ {
+ case BOOLEAN_TRUE:
+ case BOOLEAN_FALSE:
+ case BYTE:
+ need(pos, size_t(count));
+ return pos + count;
+ case I16:
+ case I32:
+ case I64:
+ for (int32_t i = 0; i < count; ++i)
+ pos = skipVarint(pos);
+ return pos;
+ case BINARY:
+ for (int32_t i = 0; i < count; ++i)
+ pos = skipBinary(pos);
+ return pos;
+ default:
+ for (int32_t i = 0; i < count; ++i)
+ pos = skipValue(pos, type, depth);
+ return pos;
+ }
+ }
+
+ /// Skips a value of any type except STOP; the value is at `depth`.
+ const uint8_t * skipValue(const uint8_t * pos, uint8_t type, uint32_t depth) const
+ {
+ if (depth > recursion_limit) [[unlikely]]
+ throwDepthLimit();
+ switch (type)
+ {
+ case BOOLEAN_TRUE:
+ case BOOLEAN_FALSE:
+ case BYTE:
+ /// Only reached for elements of containers: a bool element takes one byte.
+ need(pos, 1);
+ return pos + 1;
+ case I16:
+ case I32:
+ case I64:
+ return skipVarint(pos);
+ case DOUBLE:
+ need(pos, 8);
+ return pos + 8;
+ case UUID:
+ need(pos, 16);
+ return pos + 16;
+ case BINARY:
+ return skipBinary(pos);
+ case STRUCT:
+ return skipStruct(pos, depth);
+ case LIST:
+ case SET:
+ {
+ need(pos, 1);
+ const uint8_t header = *pos++;
+ int32_t count = (header >> 4) & 0x0f;
+ if (count == 15)
+ pos = readSize(pos, count);
+ else if (size_limit > 0 && count > size_limit) [[unlikely]]
+ throwBadSize(false);
+ const uint8_t element_type = header & 0x0f;
+ checkType(element_type);
+ return skipElements(pos, element_type, count, depth + 1);
+ }
+ case MAP:
+ {
+ int32_t count = 0;
+ pos = readSize(pos, count);
+ if (count == 0)
+ return pos;
+ need(pos, 1);
+ const uint8_t types = *pos++;
+ const uint8_t key_type = types >> 4;
+ const uint8_t value_type = types & 0x0f;
+ checkType(key_type);
+ checkType(value_type);
+ if (key_type == STOP || value_type == STOP) [[unlikely]]
+ throwInvalidData("invalid TType");
+ if (depth >= recursion_limit) [[unlikely]]
+ throwDepthLimit();
+ for (int32_t i = 0; i < count; ++i)
+ {
+ pos = skipValue(pos, key_type, depth + 1);
+ pos = skipValue(pos, value_type, depth + 1);
+ }
+ return pos;
+ }
+ default:
+ checkType(type);
+ throwInvalidData("invalid TType");
+ }
+ }
+};
+
/// Hides the methods that the generated `FileMetaData::read` calls, to skip the elements of
-/// `RowGroup::columns` instead of reading them. `skip` is `TVirtualProtocol<CompactProtocol>::skip`,
-/// so skipped values never come back here.
+/// `RowGroup::columns` instead of reading them. The elements are skipped on the transport's bytes
+/// by CompactValueSkipper, so skipped values never come back here.
class ColumnChunkSkippingProtocol : public CompactProtocol
{
public:
@@ -173,17 +412,24 @@ public:
auto & row_group_offsets = offsets.back();
row_group_offsets.clear();
row_group_offsets.reserve(size + 1);
- /// `skip` counts every value against the recursion limit, the generated reader only structs.
- /// One level less accepts every column chunk that the generated reader accepts.
- decrementInputRecursionDepth();
+ uint32_t available = 0;
+ const uint8_t * begin = trans_->borrow(nullptr, &available);
+ const UInt32 begin_position = position();
+ const CompactValueSkipper skipper(begin + available, sizeLimit(limit), getRecursionLimit());
+ const uint8_t * pos = begin;
for (uint32_t i = 0; i < size; ++i)
{
- row_group_offsets.push_back(position());
+ row_group_offsets.push_back(begin_position + UInt32(pos - begin));
/// Read as a struct whatever the declared element type, like the generated reader.
- bytes += skip(apache::thrift::protocol::T_STRUCT);
+ /// The generated reader would read the column chunk at depth 3 (FileMetaData, RowGroup,
+ /// ColumnChunk), but `skip` also counts every value against the recursion limit, so one
+ /// level less accepts every column chunk that the generated reader accepts.
+ pos = skipper.skipStruct(pos, /*depth=*/ 2);
}
+ const auto skipped = UInt32(pos - begin);
+ trans_->consume(skipped);
+ bytes += skipped;
row_group_offsets.push_back(position());
- incrementInputRecursionDepth();
size = 0;
}
return bytes; |
Skipping `RowGroup::columns` went through `apache::thrift::protocol::skip`, which reads every value through the transport and copies every skipped string. `CompactValueSkipper` walks the compact protocol directly on the footer bytes with the same size and recursion limits, so it accepts, rejects and consumes the same input as `skip`. Errors are thrown from cold helpers so that the per-value fast paths stay inlined. ClickBench's 100-file layout, server, metadata cache dropped before each query (n=30, paired, 95% CI): user CPU of `count()` -35% [-40, -30], of `min(EventDate), max(EventDate)` -41% [-46, -36], of a fully pruned `count()` -38% [-43, -32]; query time -16%, -16% and -12%. Cache hits do not parse the footer and are unchanged. A differential run against the previous `skip`-based protocol (266 real footers, 310k mutated or random footers, 720 nesting shapes up to and past the recursion limit) found no difference in result, offsets or error code, also under ASan and UBSan. A new gtest compares both on column chunks with unknown fields of every thrift type. Proposed by snelheidai: ClickHouse#124364 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I took the second version in a334558: with a cold metadata cache it cuts the user CPU of |
|
The description notes that a reader still copies the rest of the footer (schema, row group headers). This copy, in The footer is immutable and lives as long as the reader, and every use of The CPU reduction was consistent across two runs. Wall time was 2–7% lower, but significant only for Q7 and Q43 in run 1:
Setup: one 4-core Graviton3 host, warm page cache, a fresh Both builds were master f20e47b with this PR's footer path (d70d6b5 plus the skipper now in a334558) and 8 other open Parquet PRs. The copy itself is unchanged in a334558, but the ratios on this PR alone will differ somewhat. Diff on a334558diff --git a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
index d8c168d9..13cb980a 100644
--- a/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
+++ b/src/Processors/Formats/Impl/Parquet/ReadManager.cpp
@@ -69,7 +69,7 @@ void ReadManager::init(FormatParserSharedResourcesPtr parser_shared_resources_,
reader.preparePrewhere();
ProfileEvents::increment(ProfileEvents::ParquetReadRowGroups, reader.row_groups.size());
- ProfileEvents::increment(ProfileEvents::ParquetPrunedRowGroups, reader.file_metadata.row_groups.size() - reader.row_groups.size());
+ ProfileEvents::increment(ProfileEvents::ParquetPrunedRowGroups, reader.file_metadata().row_groups.size() - reader.row_groups.size());
size_t num_row_groups = reader.row_groups.size();
for (size_t i = size_t(ReadStage::NotStarted) + 1; i < size_t(ReadStage::Deliver); ++i)
diff --git a/src/Processors/Formats/Impl/Parquet/Reader.cpp b/src/Processors/Formats/Impl/Parquet/Reader.cpp
index 73185935..993c327a 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.cpp
+++ b/src/Processors/Formats/Impl/Parquet/Reader.cpp
@@ -233,6 +233,8 @@ void Reader::init(const ReadOptions & options_, const Block & sample_block_, For
format_filter_info = format_filter_info_;
}
+const parq::FileMetaData Reader::empty_file_metadata{};
+
std::shared_ptr<const FileFooter> Reader::readFileFooter(Prefetcher & prefetcher, size_t footer_read_size)
{
/// Parquet file ends with:
@@ -310,7 +312,6 @@ void Reader::fixUpColumnChunk(parq::ColumnChunk & column, bool written_by_old_du
void Reader::setFileFooter(std::shared_ptr<const FileFooter> footer, std::vector<FileColumnChunksPtr> cached_column_chunks_)
{
file_footer = std::move(footer);
- file_metadata = file_footer->metadata;
cached_column_chunks = std::move(cached_column_chunks_);
}
@@ -359,7 +360,7 @@ void Reader::ensureColumnChunks(const std::vector<size_t> & column_indices)
std::vector<FileColumnChunks> parsed;
deserializeColumnChunks(
file_footer->serialized.data(), file_footer->serialized.size(), file_footer->column_chunk_offsets, indices_to_parse, parsed);
- const bool written_by_old_duckdb = file_metadata.created_by == "DuckDB";
+ const bool written_by_old_duckdb = file_metadata().created_by == "DuckDB";
for (size_t k = 0; k < indices_to_parse.size(); ++k)
{
for (auto & column : parsed[k].chunks)
@@ -395,7 +396,7 @@ void Reader::getHyperrectangleForRowGroup(size_t row_group_idx, Hyperrectangle &
/// Without arrays a valid chunk has num_values == num_rows.
bool always_null = column_meta.statistics.__isset.null_count &&
column_meta.statistics.null_count == column_meta.num_values &&
- (column_info.levels.back().rep > 0 || column_meta.num_values == file_metadata.row_groups.at(row_group_idx).num_rows);
+ (column_info.levels.back().rep > 0 || column_meta.num_values == file_metadata().row_groups.at(row_group_idx).num_rows);
bool can_be_null = !column_meta.statistics.__isset.null_count ||
column_meta.statistics.null_count != 0;
bool null_as_default = options.format.null_as_default && !column_info.output_nullable;
@@ -585,8 +586,8 @@ std::optional<Chunk> Reader::readMinMaxFromStatistics(const std::optional<std::u
if (!column_info.decoder.allow_stats || column_info.levels.back().rep > 0)
return std::nullopt;
/// Without the `TYPE_ORDER` column order, `min_value` / `max_value` have no defined meaning (parquet.thrift).
- if (!file_metadata.__isset.column_orders || column_info.column_idx >= file_metadata.column_orders.size()
- || !file_metadata.column_orders[column_info.column_idx].__isset.TYPE_ORDER)
+ if (!file_metadata().__isset.column_orders || column_info.column_idx >= file_metadata().column_orders.size()
+ || !file_metadata().column_orders[column_info.column_idx].__isset.TYPE_ORDER)
return std::nullopt;
/// Statistics of these types are the exact extremes in `min` / `max` order; strings may be truncated, floats
@@ -604,9 +605,9 @@ std::optional<Chunk> Reader::readMinMaxFromStatistics(const std::optional<std::u
std::vector<Field> mins(num_columns);
std::vector<Field> maxs(num_columns);
bool has_rows = false;
- for (size_t row_group_idx = 0; row_group_idx < file_metadata.row_groups.size(); ++row_group_idx)
+ for (size_t row_group_idx = 0; row_group_idx < file_metadata().row_groups.size(); ++row_group_idx)
{
- const auto & meta = file_metadata.row_groups[row_group_idx];
+ const auto & meta = file_metadata().row_groups[row_group_idx];
if (meta.num_rows < 0 || numColumnChunks(row_group_idx) != total_primitive_columns_in_file)
return std::nullopt;
if (meta.num_rows == 0 || (row_groups_to_read.has_value() && !row_groups_to_read->contains(row_group_idx)))
@@ -756,7 +757,7 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
|| options.format.parquet.spatial_filter_push_down)
{
geo_meta.emplace(); // Mark as "parsed" upfront; filled in on success, left empty on failure.
- for (const auto & kv : file_metadata.key_value_metadata)
+ for (const auto & kv : file_metadata().key_value_metadata)
{
if (kv.key != "geo")
continue;
@@ -849,7 +850,7 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
/// input_format_parquet_allow_missing_columns = 0, turning a readable file into an exception.
std::unordered_set<String> schema_leaf_paths;
{
- const auto & schema = file_metadata.schema;
+ const auto & schema = file_metadata().schema;
if (schema.size() >= 2 && schema.at(0).num_children > 0)
{
size_t schema_idx = 1;
@@ -946,7 +947,7 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
/// Pass std::nullopt when allow_geoparquet_parser is disabled so SchemaConverter skips
/// geo type resolution entirely (it will not re-parse).
SchemaConverter schemer(
- file_metadata,
+ file_metadata(),
options,
&extended_sample_block,
options.format.parquet.allow_geoparquet_parser ? geo_meta : std::nullopt);
@@ -1127,9 +1128,9 @@ void Reader::prefilterAndInitRowGroups(const std::optional<std::unordered_set<UI
std::vector<RowGroupCandidate> candidates;
bool some_top_k_range_to_read = false;
size_t total_rows = 0;
- for (size_t row_group_idx = 0; row_group_idx < file_metadata.row_groups.size(); ++row_group_idx)
+ for (size_t row_group_idx = 0; row_group_idx < file_metadata().row_groups.size(); ++row_group_idx)
{
- const auto * meta = &file_metadata.row_groups[row_group_idx];
+ const auto * meta = &file_metadata().row_groups[row_group_idx];
if (meta->num_rows < 0)
throw Exception(ErrorCodes::INCORRECT_DATA, "Row group {} has negative row count: {}", row_group_idx, meta->num_rows);
if (meta->num_rows == 0)
@@ -1381,7 +1382,7 @@ void Reader::prepareBloomFilterCondition()
if (!any_row_group_eligible)
continue;
- parquet::ColumnDescriptor desc = makeColumnDescriptor(file_metadata, column_info);
+ parquet::ColumnDescriptor desc = makeColumnDescriptor(file_metadata(), column_info);
bf_eligible_columns[column_info.idx_in_output_block].emplace(primitive_idx, std::move(desc));
dict_filter_eligible_columns[column_info.idx_in_output_block] = any_row_group_dict_eligible;
any_column_eligible_for_bf = true;
@@ -1585,7 +1586,7 @@ void Reader::initializePrefetches()
/// But leave `data_pages_bytes` unchanged because it's used to check whether there are any
/// more pages to read, and we don't want to start reading a page inside these 100 bytes.
size_t data_pages_extra_bytes = 0;
- if (file_metadata.created_by == "parquet-mr" && !column.meta->meta_data.__isset.dictionary_page_offset && !column.meta->__isset.offset_index_offset)
+ if (file_metadata().created_by == "parquet-mr" && !column.meta->meta_data.__isset.dictionary_page_offset && !column.meta->__isset.offset_index_offset)
data_pages_extra_bytes = std::min(100ul, prefetcher.getFileSize() - size_t(column.meta->meta_data.data_page_offset) - column.data_pages_bytes);
column.data_pages_prefetch = prefetcher.registerRange(
@@ -1604,14 +1605,14 @@ void Reader::initializePrefetches()
/// "something else" offsets and do binary search for each bloom filter to find where it ends.
/// Needs all column chunks, not only the ones we read.
size_t max_column_chunks = 0;
- for (size_t row_group_idx = 0; row_group_idx < file_metadata.row_groups.size(); ++row_group_idx)
+ for (size_t row_group_idx = 0; row_group_idx < file_metadata().row_groups.size(); ++row_group_idx)
max_column_chunks = std::max(max_column_chunks, numColumnChunks(row_group_idx));
std::vector<size_t> all_column_indices(max_column_chunks);
std::iota(all_column_indices.begin(), all_column_indices.end(), 0);
ensureColumnChunks(all_column_indices);
std::vector<size_t> all_offsets;
- all_offsets.reserve(file_metadata.row_groups.size() * file_metadata.schema.size() * 6);
+ all_offsets.reserve(file_metadata().row_groups.size() * file_metadata().schema.size() * 6);
for (size_t column_idx = 0; column_idx < max_column_chunks; ++column_idx)
{
const auto & chunks = column_chunks[column_idx]->chunks;
@@ -2485,7 +2486,7 @@ bool Reader::DictionaryLookup::findAnyHash(const std::vector<uint64_t> & hashes)
{
if (!computed)
{
- value_hashes = hashDictionaryValues(reader.file_metadata, reader.options, column, column_info, reservation, reserved_bytes);
+ value_hashes = hashDictionaryValues(reader.file_metadata(), reader.options, column, column_info, reservation, reserved_bytes);
computed = true;
}
/// If the dictionary values couldn't be hashed (e.g. the value set didn't fit the pruning budget),
diff --git a/src/Processors/Formats/Impl/Parquet/Reader.h b/src/Processors/Formats/Impl/Parquet/Reader.h
index 89e1fba4..17901329 100644
--- a/src/Processors/Formats/Impl/Parquet/Reader.h
+++ b/src/Processors/Formats/Impl/Parquet/Reader.h
@@ -524,8 +524,10 @@ struct Reader
Prefetcher prefetcher;
std::shared_ptr<const FileFooter> file_footer;
- /// `file_footer->metadata`, without column chunks; see getColumnChunk.
- parq::FileMetaData file_metadata;
+ /// `file_footer->metadata`, without column chunks; see getColumnChunk. The footer is immutable and
+ /// may be shared with the metadata cache, so it is not copied for every file.
+ const parq::FileMetaData & file_metadata() const { return file_footer ? file_footer->metadata : empty_file_metadata; }
+ static const parq::FileMetaData empty_file_metadata;
std::deque<RowGroup> row_groups;
/// Don't get confused in different column numberings (sorry there are so many):
diff --git a/src/Processors/Formats/Impl/Parquet/tests/gtest_parquet_lazy_column_chunks.cpp b/src/Processors/Formats/Impl/Parquet/tests/gtest_parquet_lazy_column_chunks.cpp
index 95d83d13..336caec6 100644
--- a/src/Processors/Formats/Impl/Parquet/tests/gtest_parquet_lazy_column_chunks.cpp
+++ b/src/Processors/Formats/Impl/Parquet/tests/gtest_parquet_lazy_column_chunks.cpp
@@ -675,7 +675,7 @@ TEST(ParquetLazyColumnChunks, ReaderParsesOnlyItsColumns)
for (size_t i = 0; i < 3; ++i)
{
EXPECT_EQ(reader.numColumnChunks(i), 5);
- EXPECT_TRUE(reader.file_metadata.row_groups[i].columns.empty());
+ EXPECT_TRUE(reader.file_metadata().row_groups[i].columns.empty());
EXPECT_EQ(reader.getColumnChunk(i, 1), expected.row_groups[i].columns[1]);
EXPECT_EQ(reader.getColumnChunk(i, 3), expected.row_groups[i].columns[3]);
}
diff --git a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
index a519bb59..36fa7e7e 100644
--- a/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
+++ b/src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
@@ -202,7 +202,7 @@ std::optional<std::pair<std::vector<size_t>, size_t>> ParquetV3BlockInputFormat:
if (produced_rows)
matched.push_back(row_group.row_group_idx);
}
- return std::make_pair(std::move(matched), reader->reader.file_metadata.row_groups.size());
+ return std::make_pair(std::move(matched), reader->reader.file_metadata().row_groups.size());
}
std::vector<std::pair<size_t, Field>> ParquetV3BlockInputFormat::getTopKBestValuesOfBuckets() const |
`Reader::setFileFooter` copied `file_footer->metadata` (schema and row group headers, without column chunks) into `Reader::file_metadata` for every file. The footer is immutable, the reader holds it for its whole lifetime, and every use of `file_metadata` only reads it, so `file_metadata()` now returns a reference to it. ClickBench's 100-file layout, server, max_threads=4, two servers with the binaries swapped between four phases (n=100 pairs, 95% CI), CPU time with/without: metadata cache hit: `min(EventDate), max(EventDate)` 0.935 [0.911, 0.959], ClickBench Q43 0.944 [0.928, 0.959], `count()` 0.912 [0.889, 0.935]; cache dropped before each query: Q43 0.964 [0.944, 0.986], fully pruned `count()` 0.971 [0.949, 0.993]. Full scans are unchanged, results identical. Proposed by snelheidai: ClickHouse#124364 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I took this in 9c39575: on this PR alone it cuts the CPU of footer-bound queries over the 100 ClickBench files by 6-9% on a metadata cache hit and by 3-4% on a miss, with full scans unchanged. |
…-chunks Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-chunks Master reverted ClickHouse#124131, removing `getDictionaryValues` next to the PR's `column_chunks` and `cached_column_chunks` members in `Reader.h`; kept only the PR's members. Co-Authored-By: Claude Opus 5.5 <[email protected]>
grantholly-clickhouse
left a comment
There was a problem hiding this comment.
LGTM. It looks like a neat optimization where we update the cache entries as we need columns. We are also using shared pointers in places where we used to pass around copied values.
|
|
||
| ParquetMetadataCacheCell::ParquetMetadataCacheCell(parquet::format::FileMetaData metadata_) | ||
| : metadata(std::move(metadata_)) | ||
| ParquetMetadataCacheCell::ParquetMetadataCacheCell( |
There was a problem hiding this comment.
So now given a cache key C1, we start with an empty column chunk list, and as new columns get read, we update the cache entry for C1 each time.
cache miss: C1 key gets created, columns are empty
cache hit: we read columns a and b so we update the entry for C1 with column chunks a and b so we have metadata for columns a and b
cachec hit: we read columns b and c. Now we update the C1 entry adding the column c and its metadata so C1 looks like (a, b, c) with metadata for those columns
| namespace parq = parquet::format; | ||
|
|
||
| /// Parquet file footer whose column chunks are parsed on demand, see deserializeColumnChunks. | ||
| struct FileFooter |
There was a problem hiding this comment.
I see, so now we can wrap around the metadata, and have a list of offsets so we know how to jump into the metadata for any given column
| /// Get or load Parquet metadata with caching. Returns the cell and whether it was a cache hit. | ||
| template <typename LoadFunc> | ||
| parquet::format::FileMetaData getOrSetMetadata(const ParquetMetadataCacheKey & key, LoadFunc && load_fn) | ||
| std::pair<MappedPtr, bool> getOrSetMetadata(const ParquetMetadataCacheKey & key, LoadFunc && load_fn) |
There was a problem hiding this comment.
Now we are returning a shared pointer instead of a value copy.
Conflicts with the TopN query condition cache key (ClickHouse#122109 and the `StorageFile` TopK key), the `Parquet` columns cache and the lazy column chunk metadata (ClickHouse#124364): - `StorageFile`: row blocks are read only from the plain predicate key, in the same consultation as its row groups (one Hits/Misses event), so `readFile` gained `increment_profile_events`. - `StorageFile`: master moved the `!top_k_filter` check out of the write-side condition to write TopN entries under the TopK key. The row-block write keeps it, otherwise a TopN read would store threshold-dependent row blocks under the plain key. - `StorageObjectStorageSource` merged cleanly: the row-block write is inside the per-file `!isTopKFilterApplied()` block of ClickHouse#122109. - `Reader::file_metadata` is an accessor now. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `GeospatialStatistics` After #124364 the Parquet footer is parsed without `RowGroup::columns`, so `getGeoTypeFromGeospatialStatistics` saw no column chunks and inferred `Geometry` for every column with the `GEOMETRY` or `GEOGRAPHY` logical type. `SchemaConverter` now takes the `FileFooter` and parses the chunks of only that column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… cell Since ClickHouse#124364, a read that finds a file's footer in `ParquetMetadataCache` replaces the cell with one that also holds the column chunks it parsed (`addColumnChunks`). The new cell had fresh, empty kept statistics, and `keepStatistics` kept ranges only in the exact cell the read found. So after the master merge the read that replaced the cell kept nothing, a file was skipped one read later than before, and every later replacement (a read of other columns) dropped the ranges kept so far. 05390 fails on the merge commit alone. The replacing cell now shares the kept statistics of the cell it replaces (their byte cap stays a quarter of the footer of the first cell), and `keepStatistics` keeps ranges in the resident cell whenever it shares them, under the same cache lock that recomputes its weight. With column chunks added on a hit, the first hit also changes a cell's weight by the chunks it parses, so the clickhouse-local weight checks of 05390 first read x and s twice without a filter; the filtered read that follows changes the weight only by the ranges it keeps. Checked: dropping the kept bytes from the weight fails "weight counts the kept ranges", and dropping both settle gates (StorageFile and `isEtagUsableAsCacheKey`) fails the unsettled line.
Closes: #124212
Related: #115877
Related: #104431
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reading a Parquet file parses the metadata of only the columns that a query reads, and
count()and schema inference parse none. The Parquet metadata cache shares the parsed column chunk metadata between queries instead of copying the whole file metadata for every query. On ClickBench'shits.parquet,SELECT count()inclickhouse-localis about 2.4 times faster.Description
Opening a Parquet file deserialized every
ColumnChunkof every row group before the reader knew its columns: 23,730 for ClickBench'shits.parquet(105 columns, 226 row groups). With the metadata cache (file(),clickhouse-local, object storage), every query also deep-copied the cachedFileMetaData(about 16 MiB).Now the footer is parsed by the generated
FileMetaData::readthrough a protocol that skipsRowGroup::columnsdirectly on the footer bytes, accepting what thrift'sskipaccepts, and records where each chunk starts. A reader parses only its columns' chunks with the generatedColumnChunk::read, at their nesting depth and with an exact end check. The cache keeps this footer and, after a cache hit, the columns parsed so far, in immutable shared cells, which readers use without copying. Adding columns replaces the cell with the newCacheBase::replaceIfMatches, so an entry dropped bySYSTEM DROP PARQUET METADATA CACHEor evicted stays gone. A bloom filter withoutbloom_filter_lengthneeds every chunk's offsets: the reader parses the missing chunks once, and a cache hit keeps them.Release builds,
hits.parquet,max_threads = 4, paired runs:clickhouse-local(cache miss):count()33 -> 14 ms, a one-column read 34 -> 15 ms; all-column reads and full scans unchanged or faster.SELECT *-52%, of one column -77%. A file's first hit re-parses the columns it reads, +6.4 ms once.Tests: a gtest (equivalence with the full parse, also on corrupted footers) and
tests/performance/parquet_wide_footer.xml.Conflicts with #115877 (shares the fully parsed cached metadata) and #104431, whose
computeParquetFooterDigestshould then hashFileFooter::serialized, as the cachedFileMetaDatahas no column chunks.Workflow [PR]
Sync PR [sync-upstream/pr/124364]
Version info
26.11.1.279-master(included in26.11and later)