Skip to content

Parse only the Parquet column chunk metadata that a query reads - #124364

Merged
grantholly-clickhouse merged 9 commits into
ClickHouse:masterfrom
groeneai:parquet-lazy-column-chunks
Oct 20, 2026
Merged

grantholly-clickhouse merged 9 commits into
ClickHouse:masterfrom
groeneai:parquet-lazy-column-chunks

Conversation

@groeneai

@groeneai groeneai commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124212
Related: #115877
Related: #104431

Changelog category (leave one):

  • Performance Improvement

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's hits.parquet, SELECT count() in clickhouse-local is about 2.4 times faster.

Description

Opening a Parquet file deserialized every ColumnChunk of every row group before the reader knew its columns: 23,730 for ClickBench's hits.parquet (105 columns, 226 row groups). With the metadata cache (file(), clickhouse-local, object storage), every query also deep-copied the cached FileMetaData (about 16 MiB).

Now the footer is parsed by the generated FileMetaData::read through a protocol that skips RowGroup::columns directly on the footer bytes, accepting what thrift's skip accepts, and records where each chunk starts. A reader parses only its columns' chunks with the generated ColumnChunk::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 new CacheBase::replaceIfMatches, so an entry dropped by SYSTEM DROP PARQUET METADATA CACHE or evicted stays gone. A bloom filter without bloom_filter_length needs 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.
  • Server, cache hit: metadata CPU of SELECT * -52%, of one column -77%. A file's first hit re-parses the columns it reads, +6.4 ms once.
  • Cache charge per file: 20.3 MB -> 2.6 MB, 23.9 MB once all columns were read.

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 computeParquetFooterDigest should then hash FileFooter::serialized, as the cached FileMetaData has no column chunks.


Workflow [PR]
Sync PR [sync-upstream/pr/124364]

Version info

  • Merged into: 26.11.1.279-master (included in 26.11 and later)

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-issue PR origin: picked up an external GitHub issue labels Oct 7, 2026
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ The cache weight of a column chunk missed the element storage of path_in_schema / key_value_metadata and all of crypto_metadata (ThriftUtil.cpp, columnChunkNestedMemory) AGREE, fixed all nested allocations counted; test fixture uses non-SSO values
2 ⚠️ A reader still copies the cached FileMetaData skeleton (Reader::setFileFooter) AGREE only the skeleton (schema, row group headers) is copied, about 42 KB for hits.parquet; the description says so
3 ⚠️ A bloom filter without bloom_filter_length makes the reader parse all column chunks again, also the ones it already has, on every query (Reader::initializePrefetches); raised twice AGREE, fixed the fallback parses only the missing chunks, once; a cache hit keeps them. 105-column file without bloom_filter_length: warm user CPU -24% vs master (was +16%), first hit +8% once
4 ⚠️ The cell weight skips the CRS strings of geometry/geography logical types and the AAD strings of encryption_algorithm (ParquetMetadataCache.cpp) AGREE, fixed counted
5 ⚠️ The plain count() of parquet_wide_footer.xml is answered by the row-count cache after prewarm AGREE, fixed use_cache_for_count_from_files = 0, as in count_from_formats.xml
6 ⚠️ MetadataCacheConcurrentAdds asserts that clears and adds happened after a fixed number of iterations of an unsynchronized race AGREE, fixed readers continue until both are observed, bounded by a deadline
7 ⚠️ The cell weight charges schema, row_groups and column_orders per element, while a repeated list field leaves a larger allocation behind AGREE, fixed charged by capacity; every container of the cell is now charged by capacity
8 💡 A crafted footer with many empty row groups lacking column chunks makes a wide read allocate one default chunk per column per row group noted, not blocking spec-violating input; bounded by the memory limit
9 ⚠️ No committed test drives the fallback of row 3 end to end, so a return to re-parsing would stay green DISAGREE (as a blocking gap) reverting the fallback turns the cache-charge check red (3/3), results identical; a fixture needs a file without bloom_filter_length, which ClickHouse's writer never produces. I can add a gtest harness if wanted

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261007-045300

@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: paired A/B release runs on hits.parquet (cache misses and hits), stable across batches; the unit tests are deterministic, the race test runs until its races happened (deadline-bounded).
b Root cause explained? The footer was deserialized in full, every ColumnChunk of every row group, before the reader knew its columns, and the metadata cache returned a deep copy of it for every query.
c Fix matches root cause? Yes: chunks are parsed per column where the footer is read, and the cache shares immutable parsed metadata instead of copying it. No setting, no guard.
d Test intent preserved / new tests added? New gtest (9 tests, incl. 20,000 corrupted footers and the cache races) and a perf test; the existing Parquet stateless tests pass unchanged.
e Both directions demonstrated? Base vs fix measurements; 21 mutations of the change (no parse, no depth/end/reset checks, plain set, identity ignored, weight wrong or missing a term, cached chunks ignored, add after a miss) each turn a test or the cache-charge check red.
f Fix is general across code paths? Every column chunk read goes through one accessor; cache hit, miss and uncached readers share one parse path; count(), schema inference and bucket splitting parse none; the bloom filter length fallback parses the missing chunks once, and a cache hit keeps them.
g Fix generalizes across inputs (params/datatypes/wrappers)? Duplicated fields, ignored list element types, nesting limits, chunk end mismatches, corrupted footers, writer workarounds (old DuckDB, zero dictionary offset), a file without bloom filter lengths.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change; the cache is in memory only.
i Invariants and contracts preserved? Cache cells and their parsed columns are immutable and were parsed from the cell's own footer; a change is a new cell plus an atomic compare-and-replace that never re-inserts a removed entry or overwrites a newer one; one cache entry per file; weights computed once per cell.

Session id: cron:clickhouse-impl-slot-5:20261007-021000

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d4cb214]

Summary: ✅


AI Review

Summary

The PR parses Parquet column chunk metadata on demand and shares immutable footer and column metadata between readers. No actionable findings remain at commit d4cb2146941c46df3118c2bf8441985ba3ca9214.

Missing context / blind spots
  • ⚠️ No local build artifacts are available, so tests were not rerun locally. Runtime validation relies on the PR's reported differential tests and benchmarks and the available CI reports.
Final Verdict

Status: ✅ Approve. No new inline findings or thread updates are needed.

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 20 not_sure 220 128 -42.0% <0.0001 cpu: The PR only changes how the Parquet footer is parsed, which is a one-time metadata cost per file. That cannot halve the CPU of a URL LIKE scan, so this -42.0% is unlikely to come from the diff.
⚠️ 30 not_sure 219 260 +18.7% <0.0001 aggregation: This +18.7% sits inside master's recent range (193-294 ms). The query is bound by a high-cardinality GROUP BY, and lazy column-chunk parsing in the footer does not touch the aggregation path.
⚠️ 31 not_sure 257 311 +21.0% <0.0001 aggregation: This +21.0% sits inside master's recent range (229-337.5 ms). The cost is in the GROUP BY on WatchID/ClientIP, which the footer-parsing change does not touch.
⚠️ 32 not_sure 742 928 +25.0% <0.0001 aggregation: This +25.0% lands just above master's recent range (683-922 ms), and the measurements were very noisy. A one-time metadata parse cannot add 185 ms to a GROUP BY-heavy query.

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
  • StressHouse run: 042bd1db-c280-4779-b3c3-50b38407f80a
  • MIRAI run: df33e876-1799-4e04-9107-2f8c84c6a893
  • PR check IDs:
    • clickbench_88401_1791939574
    • clickbench_88511_1791939602
    • clickbench_88629_1791939608
    • tpch_adapted_1_official_88835_1791939618
    • tpch_adapted_1_official_89242_1791939741
    • tpch_adapted_1_official_89351_1791939746

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d4cb21469 with master cb1f1594b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

18 object files changed (+199.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/ThriftUtil.cpp.o 511.68 KiB 652.95 KiB +141.27 KiB (+27.61%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp.o 485.57 KiB 511.26 KiB +25.69 KiB (+5.29%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/Parquet/Reader.cpp.o 860.31 KiB 878.18 KiB +17.87 KiB (+2.08%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

712 translation units recompiled, 6688 s compile time in total, 711 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 8.1 s

Job report

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]>
@snelheidai

Copy link
Copy Markdown

When the footer isn't cached, count() on a local file could parse only FileMetaData.num_rows (field 3) instead of the footer skeleton with every row group. On top of this PR, the diff below takes count() on hits.parquet from 20 to 6 ms in clickhouse-local (master: 47 ms):

clickhouse-local, median of 10 paired runs this PR + num_rows only ratio [95% CI]
count() on hits.parquet (one file) 20.0 ms 6.0 ms 0.297 [0.293, 0.301]
ClickBench Q1 (count()), 100-file layout 27.0 ms 20.5 ms 0.774 [0.748, 0.802]
count() from file('hits_*.parquet') 31.5 ms 25.0 ms 0.780 [0.744, 0.817]
count() from hits_7.parquet (one of the 100 files) 6.0 ms 6.0 ms 0.985 [0.951, 1.020]
Q2, 100 files (control: reads a column) 62.5 ms 63.5 ms 1.018 [1.000, 1.036]
Q43, 100 files (control) 48.0 ms 47.0 ms 0.984 [0.965, 1.004]
  • On a cache hit, num_rows comes from the cached cell.
  • For a local file without a cached footer, the footer bytes are read as before, but parsing stops at num_rows and nothing is inserted into the cache: reading a local footer again is cheap, parsing it is not.
  • Remote reads (is_remote_fs) keep getFileFooter, so a later query on the same object still hits the cache.
  • 04207_parquet_metadata_cache_local_file checks local cache use with count(). A local count() miss now neither hits nor misses, so those checks need a data query such as sum(id).
  • count() on a local file no longer checks the footer after num_rows, so some footers damaged there return a row count instead of an error.
  • In a server, repeated count() on an unchanged file is already answered by the row-count cache (use_cache_for_count_from_files). So the gain applies to clickhouse-local and to the first count() of each file.

16 count() and error checks (several row groups, empty, truncated and garbage files, globs, _file filters) gave identical results and error codes with and without the diff.

Method

4-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 PollingQueue creation), and the two PR builds replaced CacheBase::replaceIfMatches with a non-atomic stand-in to avoid a full rebuild; count() doesn't call it, and the diff touches neither. Each run is a new clickhouse-local process, so the metadata and row-count caches start empty. Times are the query times printed by --time, with the files in the page cache and the arms rotated. Ratios are geometric means of the paired ratios with 95% t-intervals.

Diff on top of b8c2933
diff --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

…-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]>
@snelheidai

Copy link
Copy Markdown

In a fresh clickhouse-local, 85% of FileMetaData::read with this PR is thrift's generic skip, which ColumnChunkSkippingProtocol uses to step over the column chunks (profile of a query that only parses the 100 footers of ClickBench's partitioned layout). skip copies every skipped string into a std::string and goes through the transport for each value. The diff below (ThriftUtil.cpp only) skips the column chunks directly on the footer bytes. It keeps skip's size and recursion limits, accepts and rejects the same footers, and records the same offsets.

ClickBench, 100 files, fresh clickhouse local --time this PR + diff ratio [95% CI]
Q7 min(EventDate), max(EventDate) 27 ms 20 ms 0.750 [0.689, 0.816]
Q1 count() 19 ms 17 ms 0.854 [0.747, 0.977]
Q2 66 ms 61 ms 0.933 [0.873, 0.997]
Q8 69 ms 66 ms 0.955 [0.922, 0.989]
Q42 53 ms 51 ms 0.955 [0.914, 0.997]

A count() whose row groups are all pruned, so that it only parses the footers, goes from 26 to 20 ms (medians of 15 runs). User CPU drops by 8–16 ms per query, about 0.1 ms per footer. Long scans and cold-cache runs are unchanged (for example Q3 1.008, Q26 1.000). A metadata-cache hit doesn't parse the footer skeleton, so in a server the gain is limited to cache misses.

Checks:

  • The 14 deterministic queries among the 19 measured return identical results. Q25 and Q39–Q42 have ties under ORDER BY ... LIMIT and vary between runs of either build.
  • Of 246 Parquet stateless tests, 191 pass and 8 are skipped; 36 fail identically without the diff, and 11 time out because the S3/URL test endpoint wasn't running.
  • 400 randomly mutated footers × 4 queries: all 1600 runs give the same result or the same error code. The message text of some parse errors can differ.
  • I haven't run this PR's gtests with the diff.
Method

4-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 ThriftUtil.cpp is the same as at d70d6b5, so the diff applies here unchanged. Each query runs in a new clickhouse local --time process, as in ClickBench, with hits_0..99.parquet in the page cache. Ratios are geometric means of paired ratios over 5 alternating rounds, with 95% t-intervals. The profile is perf on the pruned count() (WHERE CounterID = 999999999).

Diff on top of d70d6b5
diff --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.

@snelheidai

Copy link
Copy Markdown

A faster replacement for the diff in my previous comment. There, need(), skipVarint() and skipValue() weren't inlined, and need() alone took a third of the remaining FileMetaData::read time. This version moves every throw into a cold NO_INLINE helper and inlines the fast paths for scalar struct fields and container elements. The limits, the accepted and rejected footers and the recorded offsets don't change.

Measured as before, against this PR:

ClickBench, 100 files, fresh clickhouse local --time this PR + new diff ratio [95% CI]
Q1 count() 19 ms 14 ms 0.776 [0.701, 0.859]
Q43 44 ms 38 ms 0.882 [0.806, 0.965]
Q20 72 ms 63 ms 0.884 [0.833, 0.937]
Q39 64 ms 57 ms 0.902 [0.845, 0.962]
Q42 53 ms 49 ms 0.939 [0.905, 0.974]

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 count() that only parses the footers takes 27, 24 and 21 ms, with 42, 35 and 27 ms of user CPU; Q7 takes 25, 20 and 17 ms.

Checks:

  • The deterministic queries return identical results.
  • 300 randomly mutated footers × 4 queries: all 1200 runs give the same result or the same error code as this PR.
  • Of the 190 Parquet stateless tests that pass with the first diff, 187 pass with this one. A server restart interrupted my run before 02242, 02245 and 02481 finished, and I haven't rerun those three.
  • This PR's gtests haven't been run with either diff.
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

I took the second version in a334558: with a cold metadata cache it cuts the user CPU of count() over the 100 ClickBench files by 35% here, and a differential run against the skip-based protocol found no difference in results, offsets or error codes.

@snelheidai

Copy link
Copy Markdown

The description notes that a reader still copies the rest of the footer (schema, row group headers). This copy, in Reader::setFileFooter, costs about 30 µs of CPU per file on Graviton3: about 6% of the CPU of footer-bound queries over ClickBench's 100 partitioned files (hits_0..99.parquet).

The footer is immutable and lives as long as the reader, and every use of Reader::file_metadata only reads it, so file_metadata() can return file_footer->metadata instead of a copy. The diff below applies to a334558, and the changed files compile with clang 21.

The CPU reduction was consistent across two runs. Wall time was 2–7% lower, but significant only for Q7 and Q43 in run 1: --time has 1 ms resolution, and these queries take 17–43 ms. Ratio with/without the diff [95% CI]:

Query CPU, run 1 (n=14) CPU, run 2 (n=20) Wall, run 1 (n=14) Wall, run 2 (n=20)
Q7 MIN/MAX(EventDate) 0.952 [0.926, 0.978] 0.937 [0.925, 0.949] 0.950 [0.912, 0.991] 0.934 [0.870, 1.003]
Q43 not recorded 0.938 [0.910, 0.966] 0.941 [0.895, 0.990] 0.984 [0.961, 1.009]
count() WHERE CounterID = -1 (all row groups pruned) 0.940 [0.919, 0.962] 0.937 [0.923, 0.951] 0.967, not significant 0.973 [0.937, 1.011]

Setup: one 4-core Graviton3 host, warm page cache, a fresh clickhouse-local --time per query with the official ClickBench create.sql, alternating runs of the two builds. CPU is the query's UserTimeMicroseconds + SystemTimeMicroseconds. Run 1 also covered Q1, Q2, Q8, Q20 and Q37–Q42: Q39 and Q42 were about 4% faster in wall time, Q40 was 2.4% slower but not in run 2 (0.977 [0.949, 1.005]), and the others showed no significant change. The full-scan controls Q4 and Q21 were unchanged. Results were identical, except that Q39–Q42 pick different tied rows at the LIMIT boundary from run to run in both builds.

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 a334558
diff --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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

alexey-milovidov and others added 3 commits October 17, 2026 03:29
…-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 grantholly-clickhouse left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now we are returning a shared pointer instead of a value copy.

@grantholly-clickhouse
grantholly-clickhouse added this pull request to the merge queue Oct 20, 2026
Merged via the queue into ClickHouse:master with commit c8a410b Oct 20, 2026
178 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 20, 2026
@grantholly-clickhouse grantholly-clickhouse self-assigned this Oct 20, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
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]>
alexey-milovidov added a commit that referenced this pull request Oct 20, 2026
… `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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 20, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parquet-reader-v3 Issues related to the native Parquet reader. groeneai-origin-issue PR origin: picked up an external GitHub issue pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

5 participants