Skip to content

Support Query Condition Cache for local Parquet files - #109247

Merged
alexey-milovidov merged 9 commits into
masterfrom
query-condition-cache-local-files
Jul 16, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
query-condition-cache-local-files

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Extends the Query Condition Cache to local Parquet files read via the File table engine.

Until now the Query Condition Cache only applied to Parquet files read through object storage (StorageObjectStorageSource, added in #102115). Local files read via StorageFile already computed the predicate condition_hash and KeyCondition — so in-query row-group/page pruning worked — but they never consulted or populated the cache, so the pruning result was recomputed on every query.

This wires the cache into StorageFileSource::generate, mirroring the object-storage read/write paths:

  • on read, look up the surviving row groups for the file and predicate and restrict the reader with setBucketsToRead (or skip the whole file);
  • when a file is exhausted, record the row groups that produced no matching rows via getMatchedBuckets.

The file version token (current_file_cache_version: sub-second mtime, inode and size — already computed for the Parquet footer metadata cache) is folded into the cache key, so an in-place file rewrite yields a cache miss rather than stale results. Only Parquet reports matched buckets, so other formats naturally miss. Controlled by the existing use_query_condition_cache setting.

Like the object-storage path, the cache is keyed by the table UUID, so it engages for UUID-bearing File-engine tables (the common case in an Atomic database). The file table function shares the same read path but constructs a StorageID without a persistent UUID, so the Query Condition Cache disables itself there (issues #92863 / #92864) — the same limitation the s3() table function has. Extending the cache to UUID-less storages (which would also cover file() and s3()) is left as a possible follow-up.

Related: #102115

Changelog category (leave one):

  • Improvement

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

Support the Query Condition Cache for local Parquet files read via the File table engine (previously supported only for object storage and data lakes).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.1042 (included in 26.7 and later)

The Query Condition Cache previously only applied to Parquet files read
through object storage (`StorageObjectStorageSource`). Local files read via
the `file()` table function or the `File` table engine (`StorageFile`)
computed the predicate `condition_hash` and `KeyCondition` (so in-query
row-group / page pruning already worked) but never consulted or populated
the cache, so the pruning result was recomputed on every query.

This wires the cache into `StorageFileSource::generate`, mirroring the
object-storage read/write paths: on read, look up the surviving row groups
for the file and predicate and restrict the reader with `setBucketsToRead`
(or skip the whole file); when a file is exhausted, record the row groups
that produced no matching rows via `getMatchedBuckets`.

The file version token (`current_file_cache_version`: sub-second mtime,
inode and size - already computed for the Parquet footer metadata cache) is
folded into the cache key, so an in-place file rewrite yields a cache miss
rather than stale results. Only Parquet reports matched buckets, so other
formats naturally miss.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b39426]

Summary: ✅


AI Review

Summary

This PR wires QueryConditionCache into local File-engine Parquet reads and adds focused regression coverage around cache hits, bypass on unsettled mtimes, and rewrite invalidation. The main stale-read race is still open, though: the code starts trusting a cached skip decision before the file generation is pinned for the full scan, so a concurrent rewrite of the same path can still silently drop matching row groups.

Findings

❌ Blockers

  • [src/Storages/StorageFile.cpp:1801] StorageFileSource::generate still consults QueryConditionCache after only the post-open stat, but another File table on the same path can INSERT ... SETTINGS engine_file_truncate_on_insert = 1 after that check and before or during the scan. The later fileCacheVersionTokenStillHolds guard at src/Storages/StorageFile.cpp:1961 only suppresses cache population; it does not undo the already-applied setBucketsToRead or whole-file skip. That means the reader can still reuse a stale V1 skip decision against V2 bytes and return wrong results.
    Suggested fix: only apply cached row-group pruning once the file generation is pinned for the full read, or fail close and bypass local-file QueryConditionCache whenever concurrent rewrites of the same path are still possible.
Final Verdict

Needs revision before merge: the previously reported stale-read race in StorageFile is still reachable in the current code.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
The `Style check` was the only red job (it drops all downstream builds/tests),
failing on three issues in the new test:
- a test-numbering gap (`05020` was far ahead of the highest existing number),
- a global `SYSTEM FLUSH LOGS` (must name the log: `SYSTEM FLUSH LOGS query_log`),
- `SYSTEM DROP QUERY CONDITION CACHE` without a `no-parallel` tag.

While verifying the test end-to-end (CI never built it, since it stopped at the
style stage) two functional problems surfaced:

- The original test asserted on `read_rows`, but that cannot observe the cache:
  Parquet bloom-filter pruning already skips the absent (odd) value on the very
  first query, so the cached and uncached reads are identical. The reliable
  signal is the `QueryConditionCacheMisses` / `QueryConditionCacheHits` profile
  events, as used by the existing object-storage test
  (`test_storage_iceberg_with_spark/test_query_condition_cache.py`).

- The `file()` table function has a Nil table UUID, and `QueryConditionCache`
  disables itself for storages without a UUID (issues #92863 / #92864), so the
  cache is inert for it - the same limitation the `s3()` table function has. The
  cache is populated and reused for file-backed tables that do have a UUID, i.e.
  the `File` table engine.

Rewrite the test to use a `File` engine table and assert on the cache
miss/hit profile events (first query = miss, second = hit), plus a correctness
check that a matching predicate is not over-skipped. The table gets a unique
UUID per test run, so the cache keys are isolated and no global cache reset is
needed, keeping the test parallel-safe.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

While fixing the Style check failures I built and ran the test end-to-end (CI had never built this PR — every downstream job was dropped after the red style stage). Two things surfaced:

  1. The read_rows assertions could not observe the cache. Parquet bloom-filter pruning (on by default) already skips the absent odd value b = 3 on the first query, so the cached and uncached queries read the same number of rows. The reliable signal is the QueryConditionCacheMisses / QueryConditionCacheHits profile events, as used by test_storage_iceberg_with_spark/test_query_condition_cache.py.

  2. The file() table function does not populate the cache. Its StorageID has a Nil UUID, and QueryConditionCache::read/write intentionally disable themselves for storages without a UUID (issues Regression with query condition cache on Memory engine in 25.10 #92863 / Parquet: allow reading Tuple/Map columns as JSON #92864) — the same limitation the s3() table function has. The cache is populated and reused for file-backed tables that have a UUID, i.e. the File table engine (verified locally: first query = miss, second = hit; a matching predicate is not over-skipped).

I renumbered the test to 04498 (the 05020 number left a >100 numbering gap), scoped SYSTEM FLUSH LOGS to query_log, and rewrote it to use a File engine table and assert on the miss→hit profile events. Each run gets a table with a unique UUID, so the cache keys are isolated and no global cache reset (SYSTEM DROP ...) is needed, keeping the test parallel-safe.

Open question: the description highlights the file table function, but with the current Nil-UUID policy the cache only engages for UUID-bearing tables (File engine), consistent with object storage. Do you want to (a) extend caching to table functions — a shared-cache change that would also cover s3() — or (b) adjust the description/changelog to reflect File-engine support?

Comment thread src/Storages/StorageFile.cpp Resolved
…ables

Add a shared helper `QueryConditionCache::makeFilePartName(path, version_token)`
that composes the `part_name` component of a cache key from a file's full path and
a content-version token, separated by a NUL byte (which cannot occur in either, so
the encoding is unambiguous). Using the full path (rather than the base name) keeps
files that share a name in different directories from colliding, and folding in a
version token makes an in-place rewrite of a file yield a different key instead of a
stale hit.

Use it for the local-file path in `StorageFile` (version token = modification time,
inode and size), replacing the ad-hoc `path + "::" + version` concatenation. The
same helper is reused for the object-storage path (ETag as the version token) in a
follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Resolving my open question above in the (b) direction, since the AI review flags the same file() / Nil-UUID contract mismatch as a blocking Major.

I've updated the PR description and Changelog entry so they describe what this PR actually ships — the Query Condition Cache now engages for UUID-bearing File-engine tables — and added a paragraph documenting that the file table function shares the read path but has no persistent UUID, so the cache disables itself there (issues #92863 / #92864), exactly like s3(). The C++ and the 04498 test are unchanged: the code comments were already accurate and the test already exercises the File-engine (miss→hit) path, so only the user-facing text needed narrowing.

I deliberately did not take the AI's option (a) (extend the shared cache keying to Nil-UUID storages): that reverses the deliberate "no UUID → no cache" policy from #92863 / #92864 and would also change s3() behavior, so it is a cross-cutting design decision for you rather than something to slip in here. The new wording leaves that door open as a follow-up (your makeFilePartName helper already points that way). If you'd prefer to keep the broad file() headline and land option (a) first instead, this is a one-line revert of the description.

Address review feedback on the `04498_query_condition_cache_local_files`
test: the previous version only proved miss->hit reuse on an unchanged
file, leaving the main stale-read failure mode untested.

The whole point of the file version token folded into the cache key via
`QueryConditionCache::makeFilePartName` (sub-second mtime + inode + size)
is that rewriting the same `File` table must not reuse the old skip
decision. Add a focused rewrite step: populate the cache on even-only
data (so `WHERE b = 3` records "no matching row group"), overwrite the
table in place so `3` now exists, then assert the next query returns the
matching row and records a cache miss rather than a hit.

If a future refactor dropped the version token from the key, this step
would return `0` (a stale cache hit reusing the "nothing matches"
decision) and fail, instead of silently skipping a row group that now
contains the searched value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
The query condition cache keyed local `File` reads by an
`(mtime, inode, size)` version token, but filesystem timestamps are
coarser than the wall clock (one ~1-10 ms clock tick on most Linux
filesystems, a full second on ext3, two seconds on FAT), so an in-place
rewrite that keeps the inode and the byte size and lands in the same
timestamp tick as the previous write produces an identical token, and a
query could reuse a stale skip decision, wrongly skipping row groups
that now contain matches.

Trust the token only once the file has settled: the last modification
must be at least 3 seconds in the past (a future mtime, e.g. due to
clock skew on a network mount, also fails the check). Otherwise the
query condition cache is bypassed for that read - neither consulted nor
populated. The format metadata cache is not touched: its token and
consumers predate this change.

The `04498` test now pins mtimes explicitly instead of relying on
wall-clock timing: a settled (past) mtime engages the cache (miss, then
hit), an unsettled (future) mtime deterministically exercises the
fail-close bypass, and a rewrite followed by a distinct settled mtime
proves invalidation plus re-population. The row group size moved to a
table-level setting on the CREATE TABLE: the `File` sink writes with
the format settings captured on the table, so the query-level SETTINGS
clause on the INSERT never reached the Parquet writer and the file had
a single row group; a single-row-group file with a matching row leaves
no unmatched row groups to cache, which would make the repeated-query
hit assertion impossible.

Addresses the review finding on `StorageFile.cpp` about coarse mtime
granularity reusing stale query-condition-cache entries.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Storages/StorageFile.cpp Resolved
`current_file_cache_version` was sampled once before `createReadBuffer`
opened the file and trusted for the rest of the read, but a second
`File` table pointing at the same path is guarded by its own
independent `rwlock`, not ours, and can truncate and rewrite the file
strictly between that `stat` and the open, or while the row groups are
being scanned. In that window the cache would consult or populate a
stale entry keyed by a token that no longer describes the bytes being
read, silently skipping a rewritten file.

Re-stat the path immediately after opening (closing the window before
the read starts) and again immediately before writing to the Query
Condition Cache (closing the window spanning the read itself); on any
mismatch treat the version token as unsettled and fail close for both
the read and the write. `04498_query_condition_cache_local_files` and
`04207_parquet_metadata_cache_local_file` verified passing (3/3 and
1/1 runs) against a server built from this branch.

#109247 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 28.60% 85.90% +57.30%
Functions 39.40% 92.70% +53.30%
Branches 20.60% 78.00% +57.40%

Changed lines: Changed C/C++ lines covered: 96/100 (96.00%) · Uncovered code

Full report · Diff report

@scanhex12 scanhex12 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ok looks good

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 16, 2026
Merged via the queue into master with commit 9075098 Jul 16, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-condition-cache-local-files branch July 16, 2026 15:49
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`current_file_cache_version` was sampled once before `createReadBuffer`
opened the file and trusted for the rest of the read, but a second
`File` table pointing at the same path is guarded by its own
independent `rwlock`, not ours, and can truncate and rewrite the file
strictly between that `stat` and the open, or while the row groups are
being scanned. In that window the cache would consult or populate a
stale entry keyed by a token that no longer describes the bytes being
read, silently skipping a rewritten file.

Re-stat the path immediately after opening (closing the window before
the read starts) and again immediately before writing to the Query
Condition Cache (closing the window spanning the read itself); on any
mismatch treat the version token as unsettled and fail close for both
the read and the write. `04498_query_condition_cache_local_files` and
`04207_parquet_metadata_cache_local_file` verified passing (3/3 and
1/1 runs) against a server built from this branch.

ClickHouse#109247 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cache-local-files

Support Query Condition Cache for local Parquet files
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 20, 2026
47 of 72 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product 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