Skip to content

Skip local Parquet files whose statistics kept with the cached footer exclude the filter - #125528

Merged
Manerone merged 15 commits into
ClickHouse:masterfrom
groeneai:parquet-skip-files-by-cached-statistics
Oct 23, 2026
Merged

Manerone merged 15 commits into
ClickHouse:masterfrom
groeneai:parquet-skip-files-by-cached-statistics

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A filtered read of a glob of local Parquet files (File engine, file() table function) no longer opens the files whose row groups the min/max statistics already excluded: an earlier read keeps those statistics with the cached file metadata, so later queries skip such files even with other constants.

Description

Related: #125423

On a warm server the footers of local Parquet files are cached, but a filtered read of a glob still opens every file and converts the statistics of every row group, only to find that none can match. The query condition cache helps neither for other constants nor for file().

After a read of a settled file version (the query condition cache's gate) whose metadata was already cached, the converted min/max ranges of the key condition columns are kept in the file's cache cell, keyed by column, type and the format settings that affect the conversion, and counted in its weight at once. A read that inserts the cell keeps nothing, so one-off scans do not move cold files in the cache. A later read of that version evaluates the same key condition on them before opening the file and skips it if no row group can match. Skipped files count in ParquetPrunedRowGroups and in the new ParquetFilesSkippedByCachedStatistics. use_parquet_metadata_cache = 0 disables it. A file that is not skipped costs one more metadata cache lookup.

On 100 files with the ClickBench hits schema (release, medians of 7 alternating rounds): Q37-Q43 matching 3 files take 8-10 ms instead of 11-13 ms (3 files opened instead of 100); Q1, Q2, Q3, Q8, Q20, Q24, Q30 and the cold first query are unchanged; the metadata cache grows by 2.2%.

A differential oracle of 1000 random filters over 13 column types matched master; a mutant skipping on any excluded row group failed it.

Object storage is not changed: there the skip touches the read-ahead that #124950 changes. #124959 and #124364 touch the same getOrSetMetadataCell and CacheBase code; #115877 is complementary; #122127 brings the query condition cache to file(), for the same condition only.

Based on the analysis and patch by @ snelheidai.


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

Version info

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

groeneai and others added 2 commits October 12, 2026 21:24
… exclude the filter

On a warm server the footers of local Parquet files are in the Parquet metadata cache,
but a filtered read of a glob still opened every file, built a reader and converted the
min/max statistics of every row group, only to find that no row group can match. The
decision depends only on the file version, the column, its type and a few format
settings, so it is now kept: after a read of a settled file version (the query condition
cache's write gate), the format keeps the converted statistics ranges of the key
condition columns with the file's cache cell, per column key. Later reads of the same
version, also with other constants, look the ranges up before opening the file and skip
it when no row group can satisfy the key condition, which is exactly a file the reader
would have pruned completely by the same statistics.

- `ParquetKeptStatistics`: one shared sub-object of the cache cell (mutex, ranges per
  column key, byte count), counted in the cell weight and capped at a quarter of the
  footer size (at least 4 KiB). The re-weight is atomic (`CacheBase::replaceIfMatches`),
  so a dropped or evicted cell is never re-inserted.
- `ParquetCachedStatisticsFilter`: built once per source; refuses filter push-down off,
  a column mapper, an undecidable key condition and headers the format factory would
  change. The token is re-checked right before a skip.
- A skipped file counts `ParquetPrunedRowGroups` and `ParquetMetadataCacheHits` like the
  reader would, plus the new `ParquetFilesSkippedByCachedStatistics`.
- `use_parquet_metadata_cache = 0` disables both the recording and the skip.

Object storage is not changed here.

Based on the analysis and patch by @ snelheidai in ClickHouse#125423.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten API docs to one-line invariants and drop comments that narrate the new code.

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 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck), plus my own cold review (4 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 A file that is not skipped pays one more metadata cache lookup AGREE Controls Q1, Q2, Q3, Q8, Q20, Q24, Q30 unchanged in the release A/B; stated in the description
2 💡 A skipped file is not opened, so open-time errors for it (a selected column missing from that file, a failed conversion of a non-filter column) are not raised AGREE, noted Same behavior as the existing query condition cache whole-file skip; the returned rows do not change
3 💡 StorageFile names the Parquet format at the skip site DISAGREE StorageFile already branches on Parquet in four places; the helper is in the format so object storage can reuse it

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

Session id: cron:clickhouse-review-slot-8:20261012-221300

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9b0d293]

Summary: ✅


AI Review

Summary

PR #125528 retains converted Parquet filter-column statistics with cached file metadata so later reads can skip excluded local files before opening them. Reviewed head 9b0d29346db4b737b92e88df3221a430ab3b70e1: no outstanding findings. The previous cache-weight, memory-ownership, and unbounded range-collection findings are addressed; the remaining bot-authored thread was resolved. The committed regression and performance tests, together with the reported differential checks and before/after measurements, support the change. Tests were not rerun locally because this checkout has no built ClickHouse binary.

Final Verdict

Status: ✅ Approve. No new inline findings.

`updateWeight` re-set the file's cell right after the read that kept the
statistics. With the default SLRU policy, both the `get` and the `set` of
`replaceIfMatches` move a probationary cell to the protected segment, so one
filtered query promoted every file it read for the first time, which master
leaves probationary until a second access. A one-off filtered query over many
files then demoted and evicted the entries that are actually reused.

Now the kept bytes are counted at the next hit of the cell (`getOrSetMetadataCell`
or the skip check), which moves the cell anyway; until then they are not counted.

Measured with a 4-entry SLRU cache: two hot files read twice, then two one-off
filtered queries over four cold files, then the hot files read again. Master
and this commit: both hot files hit. Before this commit: both miss.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 677f8ef0-61d2-4801-b1f2-21cadaa964b4
  • MIRAI run: 443abdeb-835e-4e48-b64c-64abafcab4b5
  • PR check IDs:
    • clickbench_1167027_1791856780
    • clickbench_1167033_1791856780
    • clickbench_1167039_1791856780
    • tpch_adapted_1_official_1167050_1791856780
    • tpch_adapted_1_official_1167062_1791856780
    • tpch_adapted_1_official_1167099_1791856780

groeneai and others added 2 commits October 13, 2026 02:27
The previous commit counted kept statistics in the cache weight only at the
next hit of the cell, so a file read once by a filtered query held them
uncounted for as long as it stayed in the cache.

Now a read keeps statistics only in a cell it found in the cache, and counts
them at once with `updateWeight`. Re-setting the cell moves it like the hit
already did, so a cell that a read inserts is not moved after the insertion,
and one-off filtered scans still leave cold files probationary under SLRU.
The skip starts from the third read of a file version instead of the second.

The reader collects the ranges only when it can keep them: for a cached cell
it hit, and only if the caller asked with
`FormatFilterInfo::keep_filter_column_statistics`, which only `StorageFile`
sets. Object storage, archive, file descriptor and metadata-cache-off reads no
longer copy them. `AggregateFunctionStatesFromValuesInputFormat` now forwards
`cacheFilterColumnStatistics`, so reads through it keep the ranges they collect.

Measured (debug build, `clickhouse local`): the cache weight includes the kept
statistics right after the read that keeps them (2848 bytes after the first
read, 3263 after the second, which keeps 415 bytes). With a 4-entry SLRU cache,
two hot files read twice, then one-off filtered reads of four cold files: both
hot files still hit, as on master. The test checks the weight with
`clickhouse-local`; it fails without the `updateWeight` call and on both
previous versions of this change, and without the forwarding in the wrapper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test started three client processes per checked query (the query,
SYSTEM FLUSH LOGS and the query_log lookup), about 90 in total, plus two
clickhouse-local runs. Under ASan that took 60 s for a single run, and the
flaky check of `amd_asan_ubsan` stopped it at the 180 s limit.

Queries now run in one client call per state of the files, tagged with a
log_comment, and their profile events are read with one flush at the end;
the two clickhouse-local runs are merged. The assertions are unchanged; only
the row-group line of the reference changes its format.

Measured with 16 parallel runs: ASan 60.7 s -> 10.2 s, debug 12.1 s -> 2.5 s.
50 parallel random-settings runs and 8 DatabaseReplicated runs pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: compile time of recompiled translation units.

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

62 object files changed (+178.77 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp.o 511.26 KiB 570.00 KiB +58.74 KiB (+11.49%)
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/ParquetMetadataCache.cpp.o 203.30 KiB 251.89 KiB +48.59 KiB (+23.90%)
src/CMakeFiles/dbms.dir/Storages/StorageFile.cpp.o 1.20 MiB 1.23 MiB +38.51 KiB (+3.15%)

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 ⚠️

812 translation units recompiled, 7045 s compile time in total, 723 of them have a recent master baseline.

Translation unit Master PR Δ vs median
src/Storages/StorageFile.cpp 13.8 s 19.5 s +5.4 s (+38%)

Translation units without a recent master baseline:

  • src/Formats/FormatFactory.cpp: 47.9 s
  • src/Server/GRPCServer.cpp: 10.2 s
  • src/Interpreters/AsynchronousInsertQueue.cpp: 9.8 s
  • src/Processors/Formats/Impl/ArrowIPC/ArrowIPCBlockInputFormat.cpp: 9.8 s
  • programs/keeper-bench/LogRunner.cpp: 9.4 s
  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.8 s
  • src/Storages/StorageXDBC.cpp: 7.6 s
  • src/Storages/ObjectStorage/Web/Configuration.cpp: 7.6 s
  • src/Processors/Formats/Impl/DWARFBlockInputFormat.cpp: 7.3 s
  • src/Storages/YTsaurus/StorageYTsaurus.cpp: 7.2 s
  • src/Databases/DatabaseURL.cpp: 7.1 s
  • src/Databases/DataLake/HiveCatalog.cpp: 7.0 s
  • src/TableFunctions/TableFunctionFile.cpp: 7.0 s
  • src/Storages/prepareReadingFromFormat.cpp: 6.9 s
  • src/TableFunctions/ITableFunctionXDBC.cpp: 6.8 s
  • src/Dictionaries/YTsaurusDictionarySource.cpp: 6.5 s
  • src/Processors/Formats/Impl/FreeformRowInputFormat.cpp: 6.5 s
  • programs/obfuscator/Obfuscator.cpp: 6.5 s
  • src/Functions/UserDefined/UserDefinedWebAssembly.cpp: 6.4 s
  • src/Processors/Formats/Impl/PuffinBlockInputFormat.cpp: 6.3 s
  • ... and 24 more

Job report

`kept_statistics->add` changed a resident cell before `updateWeight` took the
cache lock to recompute its weight, so an insertion or eviction in between saw
the cell with its old weight. `CacheBase::updateIfMatches` runs the change and
the weight recomputation under one lock acquisition; it replaces the
`replaceIfMatches` added earlier in this PR.

The ranges are copied and their bytes counted by `ParquetKeptStatistics::prepare`
before the cache lock is taken, so the lock only covers the map insertion.
`prepare` also returns nothing for a column already kept or over the cap, and
then the cache lock is not taken at all.

05390 now also checks that a read of a file whose version token has not
settled keeps nothing, even though its metadata is cached: the two unsettled
reads in the client part were followed by a new token, so they could not tell.
Without the settled check before `cacheFilterColumnStatistics` the new line
fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9ce9ca0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, targeted) not from this PR: the job errored before running any test. Its test-selection step could not reach the CI database (play.clickhouse.com refused connections, [Errno 111] Connection refused, from about 09:09 UTC), so Failed to get previously failed tests required for test selection a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) same CI database outage in the test-selection step, no test ran a fix task is moved to pending (same task as above)
Integration tests (amd_asan_ubsan, db disk, targeted) same CI database outage in the test-selection step, no test ran a fix task is moved to pending (same task as above)

Mergeable Check and PR are the praktika rollups of the rows above. The report has no other failed check on this head; all five flaky check jobs passed.

Session id: cron:our-pr-ci-monitor:20261013-113003

@Manerone Manerone self-assigned this Oct 15, 2026
@Manerone

Copy link
Copy Markdown
Contributor

how do we make sure the statistics we read are not stale?

@groeneai

Copy link
Copy Markdown
Collaborator Author

The kept ranges are part of the file's entry in the Parquet metadata cache, and that entry is keyed by the path and the file's version token (computeFileCacheVersionToken in StorageFile.cpp: mtime with nanoseconds, inode and size). A rewrite changes the token, so the next query misses the entry and opens the file. The ranges come from the cached footer itself (the same min/max the reader uses to prune row groups), so they can't be staler than the footer that master already reuses for that token.

On top of that, ranges are kept and used only after the token has settled (mtime at least 3 s in the past, the same gate the query condition cache uses for files), because only then does every later write have to change the mtime. The read that keeps them re-checks the token after reading, and the skip re-checks it right before skipping, so a rewrite during either one is caught. 05390 covers a rewrite and an unsettled (future) mtime.

The one case it can't detect is a rewrite that keeps the inode, the size and the mtime, but master's footer cache and the query condition cache trust the same token there too.

@Manerone

Copy link
Copy Markdown
Contributor

performance review doesn't show any improvements. Possible reason is:

fill_query writes the files right before measurement starts, and StorageFileSource only keeps or uses statistics once mtime + 3 <= now. All runs probably finish inside that window, so nothing is ever kept or skipped. Suggested fix: add a second <fill_query> that waits past the gate, e.g. SELECT sleepEachRow(1) FROM numbers(4) FORMAT Null, or set an old mtime some other way. Then re-run CI and confirm #0 and #1 get faster.

I don't like the idea of adding a sleep() call, is there another way we can test this?

The fill query wrote the files right before the measured runs, but a
file is skipped only once its version has settled (mtime at least 3 s
in the past), so the CI runs measured the unskipped path. The
lineitem files of the `tpch_ice_sf10` dataset are unpacked before the
tests and keep the archive's mtime, so they need no fill and no sleep.
They are split by `l_shipdate` month, so a date filter skips all files
but the matching one. `max_threads = 1` keeps the cost of the skipped
files from hiding behind the read of the matching file. The
`l_orderkey` query skips nothing and is the control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Right, that was the cause: the fill finishes a few seconds before the measured runs, and a file is skipped only once its mtime is 3 s old, so CI measured the unskipped path. Running perf.py here with the CI release builds of this PR and of master, the query that happened to run first skipped files only in its last 8 of 31 runs.

Instead of a sleep, the test now reads the tpch_ice_sf10 lineitem files that the perf job already unpacks into user_files (84 Parquet files, one per l_shipdate month, with the archive's mtime), so it needs no fill at all: d8b6fd4. Locally, 3 perf.py runs from a cold cache:

Query Files skipped master PR
l_shipdate = '1996-07-04' 83 of 84 11.0 ms 7.6 ms (-31%)
l_receiptdate = '1996-07-04' 82 of 84 12.8 ms 10.2 ms (-20%)
l_shipdate >= '1999-01-01' 84 of 84 6.4 ms 3.3 ms (-49%)
l_orderkey = 1234567 (control) 0 47.6 ms no significant change

The test sets max_threads = 1: with more threads the other files are opened in parallel with the read of the matching one, and the saving does not show in the query time.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d8b6fd4

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 3/4) / Build ClickHouse master build break since af19343b2516, not from this PR (it does not touch the file): unit_tests_dbms does not compile, gtest_functions_stress.cpp:2367: error: value of type 'const ResolvedAddress' is not contextually convertible to 'bool'; no diagnostic in the files of this PR #126269 (external, open)
Sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the first row #126269 (the owner of the first row)

The build failure dropped 110 dependent jobs, so no functional or performance test has run on this head yet, including the changed parquet_skip_files_by_cached_statistics performance test.

Session id: cron:our-pr-ci-monitor:20261016-133003

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the targeted-job test-selection Connection refused errors in the CI ledger above: #125613. A refused connection to the CI database is now retried for up to 3 minutes, then the targeted job skips instead of erroring.

@Manerone

Copy link
Copy Markdown
Contributor

some nits:

  • use_parquet_metadata_cache (src/Core/Settings.cpp): the description still says only "parquet format may utilize the parquet metadata cache". It now also controls keeping filter-column statistics and skipping files with them, and it is the only way to turn this off. Please add a sentence.
  • ParquetMetadataCache.cpp:139: the per-cell cap max(memory_bytes / 4, 4096) uses two hardcoded constants. They are bounded by the cache limit, so this is minor, but a short comment on the choice would help. Also, whichever columns are kept first fill the budget for the lifetime of the cell; nothing replaces them.
  • A skipped file is not opened, so errors that would only show up when opening it (e.g. a selected column missing from that file) now depend on whether the cache is warm. You noted this already; one line in the setting description would make it visible to users.
  • Reader::prefilterAndInitRowGroups: the kept vectors hold one range per non-empty row group, and canSkipFile assumes that position i is the same row group in every column's vector, including vectors kept by different queries. That holds only because no per-query continue comes before the push into key_condition_column_ranges (rows_to_read is one, which is why recording is disabled with it). A future per-query continue above the push would silently misalign vectors kept by different queries. Please add a comment at the push site stating this invariant, or a test with empty row groups and two columns kept by different queries.

Also, please fix the merge conflicts and merge the latest master

groeneai and others added 2 commits October 19, 2026 13:28
…by-cached-statistics

# Conflicts:
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
…tatistics invariants

The setting description now says that it also controls keeping filter column
statistics and skipping files with them, and that open-time errors of a skipped
file depend on the cache contents. Comments state the per-cell budget of kept
statistics and why the push into `key_condition_column_ranges` must come before
any query-dependent `continue`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The kept ranges live in the shared metadata cache, so allocate them outside the
memory tracker of the query and user, like the uncompressed cache and the
columns cache. Measured on 300 files whose filter column has 500-byte min/max:
the read that keeps them peaked at 2279487 bytes before and 1463183 after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. I merged master (the only conflicts were the new columns cache include and declaration next to ours in ParquetV3BlockInputFormat) and addressed the nits in 965f5cb:

  • use_parquet_metadata_cache: the description now says that for File and file() it also keeps the filter column statistics and skips files with them, that open-time errors of a skipped file then depend on the cache, and that disabling it turns both off. I checked the example: with input_format_parquet_allow_missing_columns = 0, SELECT sum(y) ... WHERE x > 5000 over a file without y fails with Column y was not found in parquet schema when the cache is off, and returns 0 when the file is skipped.
  • Per-cell cap: a comment says the kept statistics may add a quarter of the footer's size, and at least 4 KiB for a small footer, so the cache limits still bound the cell, and that the columns kept first use up this budget for the lifetime of the cell.
  • prefilterAndInitRowGroups: a comment at the push states that canSkipFile matches ranges kept by different queries by position, so no continue that depends on the query may come before it.

Also in 6db3834: the kept ranges belong to the shared cache, so they are now allocated outside the memory tracker of the query, like the columns cache entries. On 300 files with 500-byte min/max values, the read that keeps them peaked at 2.28 MB before and 1.46 MB after. 05390 passes 50/50 with random settings on the merged tree.

groeneai and others added 2 commits October 19, 2026 16:53
…ry too

The kept ranges were allocated outside the memory tracker of the query, but released
by whichever query evicts the cell or drops the last reference to them, and that free
lowered the usage of a query that holds live allocations. Allocate and release the
kept statistics with `ServerOwnedCacheEntryAllocator` and a deleter that blocks the
tracker, like the uncompressed cache.

Measured with a 300-entry LRU cache: a query reading 300 new files evicts 300 cells
whose 500-byte min/max ranges were kept. Its memory_usage was 15823303 bytes against
16613047 when the evicted cells kept nothing, and is now 16572791 against 16575927.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ot settled

`StorageFile` keeps the ranges only for a settled version, so a hit read of a file
written in the last 3 seconds copied them for nothing. Take the cell for keeping only
when the version identifies the content, as the columns cache does. Measured on 150
files with an mtime in the future: the hit read peaked at 1258031 bytes instead of
1260847; settled files keep and skip as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manerone

Copy link
Copy Markdown
Contributor

fix merge conflicts

…by-cached-statistics

# Conflicts:
#	src/Common/CacheBase.h
#	src/Processors/Formats/Impl/Parquet/Reader.cpp
#	src/Processors/Formats/Impl/Parquet/Reader.h
#	src/Processors/Formats/Impl/ParquetMetadataCache.cpp
#	src/Processors/Formats/Impl/ParquetMetadataCache.h
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.cpp
#	src/Processors/Formats/Impl/ParquetV3BlockInputFormat.h
… 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done: merged master in d8f99d0. The conflicts were with #124364, which replaces the metadata cache cell when it adds column chunks. 0f56d1f makes the new cell keep the statistics already kept with the old one; with the merge alone, 05390 fails because the third read of a file no longer skips it. It also makes the weight checks in 05390 read the column chunks first, so they still measure only the kept ranges.

A read whose metadata cache cell keeps statistics copied the ranges of every
key condition column for every row group, and only then found that a column
was already kept or did not fit the cell's budget. For a file with long string
bounds every warm read held all of them at once and discarded them: 1000 row
groups with 3000-byte bounds of `s`, `WHERE s = 'zzzz'`, took 7.25 MiB instead
of 1.23 MiB for the same read of an unsettled copy, and nothing was kept.

Now the format asks the reader to collect only the columns the cell does not
keep yet, with the bytes the cell can still take. The reader counts the bytes
while collecting and, while all columns together take more, drops the column
that takes the most. Only complete columns are left. The same read takes
2.86 MiB, the rest being the budget itself (a quarter of the footer); with two
such columns 4.28 MiB instead of 13.30 MiB. A budget per column would not do:
with four columns it collects as much as before.
`ParquetKeptStatistics::prepare` takes the byte count from the reader instead
of recounting the ranges under its lock.

05390 checks the extra memory of such a read of four columns against an
unsettled copy: +1.6 MB, while the previous commit and a per-column budget
both take +6.3 MB (threshold 3 MB).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). and removed comp-parquet-reader-v3 Issues related to the native Parquet reader. labels Oct 20, 2026
@Manerone
Manerone added this pull request to the merge queue Oct 23, 2026
Merged via the queue into ClickHouse:master with commit 479496c Oct 23, 2026
179 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 23, 2026
alexey-milovidov added a commit that referenced this pull request Oct 24, 2026
…-parallel-read

Conflicts with the query condition cache for tables without a UUID (#122127) and with skipping
Parquet files by the cached statistics (#125528): the split file now uses
`query_condition_cache_table_id` (computed before splitting), the sources of a split file don't
keep the statistics (each reads only some row groups) and count a skipped file once, and the
reader of a bucket skips other buckets' row groups only after recording their ranges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
…p-k-file-order

Resolves the conflicts with the Parquet footer cache changes on master
(ClickHouse#125528 and the lazy column chunks):
- `getOrSetMetadata` now returns the cache cell, so the footer probe uses it
  and `getOrSetMetadataCell` is dropped;
- the probe reads the footer with `readFileFooter` and `setFileFooter`;
- `keep_filter_column_statistics` is set before the file order pass;
- the includes master now has in `StorageFile.cpp` are not repeated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 1, 2026
…file order pass

Since ClickHouse#125528 a reader skips a local Parquet file without opening it when the
statistics kept with its cached footer exclude the filter. The file order pass
ran before that check and still analysed the footer of every such file, so a
repeated query whose filter excludes most files paid for footers it never
reads. The pass now uses the same `ParquetCachedStatisticsFilter` check and
leaves such files without a bound, as it already does for the files the query
condition cache excludes.

Measured (debug build, 100 files x 100 row groups x 17 columns, the cached
statistics exclude 99 files, warm, pass on vs off by
`input_format_parquet_preserve_order`, 40 interleaved pairs, median wall):
1 thread 12.96 -> 9.34 ms (off: 7.6 ms), 4 threads 9.27 -> 8.47 ms (off: 7.5-8.0 ms).
05341 checks that the second read analyses only the footer of the file the
statistics do not exclude.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 20, 2026
…adata cache

A warm read of a Parquet file from object storage or a data lake, whose footer is
already in `ParquetMetadataCache`, still read the offset index of every column chunk
it read before requesting the column data. ClickHouse writes the page index after the
bloom filters, more than `remote_read_min_bytes_for_seek` from the data, so that was a
separate, sequential request per file; since ClickHouse#128471 an Iceberg data file is one row
group, so a warm `IcebergS3` scan paid one request latency per data file and stream.

The offset indexes a read decodes and validates are now kept with the cached footer,
like ClickHouse#125528 keeps statistics: a container shared by the cache cells of a file version,
counted in the cell weight and limited to the footer size (at least 4 KiB). Only a read
that found the footer in the cache adds to it, when it reaches the end of the file, so a
file read once is not moved to SLRU's protected segment; the per-read collection stops
at the bytes the container can still keep (master frees each offset index with its row
group, so an unbounded collection would hold them all until the end of the file). The
offset indexes come from beyond the footer bytes, so they are used and kept only when
the cache key identifies the content (a strong ETag or an immutable content id), the
gate of the columns cache and the page cache. A later read copies the kept offset index
instead of registering its byte range, and the column-index stage decodes only an offset
index it read. New counter `ParquetMetadataCacheOffsetIndexHits`.

Measured (Release, 8 paired rounds, S3 behind a 20 ms first-byte delay): a warm
`IcebergS3` scan of 100M rows in 110 files -32.6% (203 -> 110 GETs), the `s3()` glob of
the same files -31.3%, 10M rows in 16 files -25.7%; `WHERE b = 5`, 1000 tiny files and
20 random-`UInt64` files unchanged (the last makes 40 requests instead of 20, with 21%
fewer bytes). The metadata cache grows by about 640 B per 3-column file.

Based on the analysis and patch by snelheidai in ClickHouse#129400.

Closes ClickHouse#129400

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). 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

Development

Successfully merging this pull request may close these issues.

3 participants