Skip to content

Query Condition Cache: key object-storage entries by ETag - #109310

Merged
alexey-milovidov merged 5 commits into
masterfrom
query-condition-cache-object-storage-etag
Jul 13, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
query-condition-cache-object-storage-etag

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The Query Condition Cache keyed object-storage files by their path only (ObjectInfo::getIdentifier). For a general (non-data-lake) remote object that is not a stable identity: an object can be overwritten in place under the same path, after which the cache would serve stale row-group information and a query could return wrong results.

This folds a content-version token into the key for non-data-lake objects — the ETag, which changes when the object is overwritten. A query after an overwrite then misses the cache and re-reads instead of reusing stale entries. S3, AzureBlobStorage, and local object storage populate the ETag, so the cache keeps working for them. HDFS object metadata does not currently carry an ETag (HDFSObjectStorage leaves it empty), and web object storage does not support object metadata at all (WebObjectStorage::getObjectMetadata throws NOT_IMPLEMENTED), so non-data-lake objects on those backends are deliberately not cached (fail-close) — the same safe behaviour as any object without an ETag. The HDFS case can be revisited if a stable HDFS version token becomes available. If no ETag is available the object is not cached (fail-close) rather than risking a stale hit.

Data-lake data files (Iceberg, DeltaLake, Hudi) are immutable, so their path is a stable identity on its own; they keep using the path-only key. This also avoids disabling the cache for data lakes whose object metadata does not carry an ETag.

The key is composed by a shared helper QueryConditionCache::makeFilePartName(path, version_token) (path and token separated by a NUL byte, which cannot occur in either). The same helper is used by the local-file path in StorageFile.

Notes:

  • The ObjectIteratorSplitByBuckets (cluster split) read path keeps the path-only key. That is safe: path-only entries are now written only for immutable data-lake files, so a path-only read can only hit a correct data-lake entry; non-data-lake reads there simply miss.
  • The version token used for the key is the ETag captured from the listing/HEAD, matching how the filesystem cache and page cache already key object-storage reads. Closing the narrow window where an object is overwritten in place between LIST and GET within a single query requires read-time ETag validation (as s3_validate_etag_on_read already provides for S3), which is orthogonal to this change.
  • The data-lake path is behaviorally unchanged and is covered by the existing test_query_condition_cache.py (Iceberg over s3/azure/local). The new non-data-lake ETag behaviour (overwrite invalidation) is covered by test_query_condition_cache_overwrite_invalidation in tests/integration/test_storage_s3/test.py, which overwrites the same MinIO object in place and asserts the next query misses the stale entry and returns the new rows.

Related: #102115
Related: #109247

Changelog category (leave one):

  • Improvement

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

Key the Query Condition Cache for remote (object storage) Parquet files by ETag in addition to the path, so that overwriting an object in place no longer serves stale cached results.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

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

The Query Condition Cache keyed object-storage files by their path only. For a
general (non-data-lake) remote object that is not a stable identity: an object can
be overwritten in place under the same path, after which the cache would serve
stale row-group information and a query could return wrong results.

Fold a content-version token into the key for non-data-lake objects: the ETag,
which changes when the object is overwritten. A query after an overwrite then
misses the cache and re-reads rather than reusing stale entries. S3, Azure, HDFS,
local and web object storage all populate the ETag, so the cache keeps working for
them. If no ETag is available the object is not cached (fail-close) rather than
risking a stale hit.

Data-lake data files (Iceberg, DeltaLake, Hudi) are immutable, so their path is a
stable identity on its own; they keep using the path-only key, which also avoids
disabling the cache for data lakes whose object metadata does not carry an ETag.

The shared helper `QueryConditionCache::makeFilePartName(path, version_token)`
composes the key (path and token separated by a NUL byte, which cannot occur in
either). The same helper is used by the local-file path in `StorageFile`.

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 [42c0c5d]

Summary: ✅


AI Review

Summary

This PR fixes the obvious cross-query stale-hit case by folding object-storage etag values into the Query Condition Cache key, adds a focused S3 overwrite regression, and correctly fail-closes HDFS. I am not approving it yet because the current code still allows cached row-group marks from one object generation to be applied to bytes from another on backends whose later read is not pinned to the same generation token.

PR Metadata
  • Changelog category should be Bug Fix, not Improvement: the PR description and test both describe a wrong-results fix for stable object-storage engines, so this is user-visible misbehavior rather than a pure optimization change.
  • Changelog entry is required for Bug Fix, and the current entry is specific enough. The only metadata change needed is to replace - Improvement with - Bug Fix.
Findings

❌ Blockers

  • [src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:136] [dismissed by author -- https://github.com/Query Condition Cache: key object-storage entries by ETag #109310#discussion_r3521070324] makeQueryConditionCacheKey still keys the cache from the etag seen at listing / metadata-probe time, but Azure, Local, and Web reads are not pinned to that same generation before createReadBuffer consumes the object. If the object is overwritten after the cache lookup and before the read, the query can still reuse row-group marks from generation N while reading bytes from generation N+1, which can skip matching groups and return wrong results. This is still live in the current code: WebObjectStorage::tryGetObjectMetadata can populate metadata.etag, so URL / web engines are cacheable here without any read-time validation. Suggested fix: either fail-close anywhere the later read is not validated against the same version token used at lookup time, or add equivalent read-time generation validation for Azure, Local, and Web before keeping those backends cacheable.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Close the remaining generation-mismatch gap for non-S3 backends (Azure, Local, Web) or make those paths fail-close until they have read-time validation.
  • Change the PR template category from Improvement to Bug Fix.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 3, 2026
Add `test_query_condition_cache_overwrite_invalidation` to `test_storage_s3`
that overwrites the same object in place between two `SELECT`s (via
`s3_truncate_on_insert = 1`) and asserts the second query misses the old
cache entry (`ProfileEvents['QueryConditionCacheMisses']`) and returns the
new rows. This exercises the core correctness contract of keying
object-storage entries by ETag: an in-place rewrite yields a new ETag and
therefore a new cache key, so stale row-group information is not reused.

Requested in review of #109310

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

Copy link
Copy Markdown
Member Author

Addressed the two AI-review findings:

  1. Overwrite regression test — added test_query_condition_cache_overwrite_invalidation to tests/integration/test_storage_s3/test.py. It overwrites the same MinIO object in place (s3_truncate_on_insert = 1, new content → new ETag, same path) between two SELECTs and asserts the second query both misses the old entry (ProfileEvents['QueryConditionCacheMisses'] > 0, no QueryConditionCacheHits) and returns the new rows. It mirrors the existing test_query_condition_cache harness and observes the cache via ProfileEvents (not read_rows, which the Parquet bloom filter can mask).

  2. HDFS and empty ETag — confirmed: HDFSObjectStorage never populates ObjectMetadata::etag (tryGetObjectMetadata sets only size_bytes/last_modified; listObjects hard-codes .etag = {}), so non-data-lake HDFS objects now fall into the fail-close path and are not cached. This is correctness-safe (no stale hits) but does drop the optimization for HDFS. I corrected the PR description to document this scope explicitly rather than claiming HDFS keeps the cache.

    I deliberately did not add an HDFS version-token fallback from last_modified + size_bytes: mLastMod is second-granularity, so two in-place rewrites within the same second (same size) would collide and produce a stale hit — which defeats the fail-close guarantee this PR establishes. Whether to accept that pragmatic tradeoff (perf for HDFS at the cost of a narrow same-second correctness window) vs. keeping HDFS uncached is a design call for you to make.

String identifier = object_info.getIdentifier(/*include_file_bucket_info=*/false);
if (is_data_lake)
return identifier;
const auto & metadata = object_info.getObjectMetadata();

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.

makeQueryConditionCacheKey is using whatever ObjectMetadata is already attached to the iterator entry, which on the normal listObjects path is the etag from the listing rather than a freshly validated generation token. That still leaves a wrong-result window on every backend whose later read is not pinned to the same etag: if the object is overwritten after LIST but before createReader, we hit the old path + etag cache entry here and then read the new bytes. S3 only avoids that while s3_validate_etag_on_read = 1; Azure, Local, Web (and S3 with validation disabled via compatibility) can still reuse stale row-group marks. To actually close the stale-hit bug, the cache lookup needs a fresh version token at this point or equivalent read-time generation validation for all supported backends.

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'd keep this in the PR. The smallest safe scope is to make the Query Condition Cache fail-close anywhere the later read is not pinned to the same generation token used at lookup time; otherwise Azure, Local, and Web still retain the wrong-result window, and Web is in scope here because WebObjectStorage::getObjectMetadata can populate etag from the response headers. That closes the correctness gap without taking on the broader filesystem/page-cache follow-up in the same patch.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

On the AI-review blocker for makeQueryConditionCacheKey (StorageObjectStorageSource.cpp:136) — the LIST-vs-GET window:

The observation is correct: the cache key uses the ETag captured by listObjects, not a token re-validated at read time, so an in-place overwrite that lands between this query's own LIST and its GET in createReader is not caught on backends without read-time ETag pinning. I consider this a deliberate scope boundary rather than a blocker for this PR, for three reasons:

  1. Strict improvement, not a regression. On master the object-storage key is path-only (ObjectInfo::getIdentifier), so any in-place overwrite — even one fully completed between two separate queries — reuses stale row-group marks and returns wrong results. This PR makes the common cross-query overwrite case correct (the ETag changes, so it is a cache miss). The only residual window is the narrow intra-query one where the overwrite interleaves between this query's LIST and GET.

  2. Consistent with the existing object-storage caches. The filesystem cache (key = hash(path, metadata->etag)) and the page cache ("etag:" + metadata->etag) in the same createReadBuffer path already key on path + ETag from the same listObjects metadata, with exactly the same LIST-vs-GET window. The Query Condition Cache now follows the same established model; if this window were a correctness blocker, it would already be one for those two shipping caches.

  3. Read-time revalidation is currently S3-only. For S3, s3_validate_etag_on_read = 1 pins the GET to the listed ETag and turns an interleaved overwrite into S3_OBJECT_CHANGED_DURING_READ rather than a torn/stale read, which also protects the cache lookup. Azure populates a real ETag but has no read-time pin; Web and HDFS carry no ETag and already fall into the fail-close (uncached) path; Local uses an mtime-derived token.

Closing the residual window for every backend means either extending read-time ETag validation (as s3_validate_etag_on_read does for S3) to Azure/Local, or making the cache fail-close whenever read-time validation is unavailable. Both are cross-cutting changes to the read path that also affect the filesystem/page caches, so they seem better as a dedicated follow-up than folded in here. I'm happy to implement either direction if you'd rather pull it into this PR.

The LIST-before-GET regression test the review asks for needs a fault-injection hook to overwrite the object between the listing and the read — a plain two-query test can't deterministically hit that window — so I'd add it together with whichever revalidation approach you choose.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only failing check here — Integration tests (amd_asan_ubsan, flaky) — is unrelated to this change (Query Condition Cache keyed by object-storage ETag).

Root cause: the integration flaky check runs the entire test_storage_s3 module (79 tests) on every worker (--dist=each), and that module contains test_s3_glob_scheherazade, which is both very slow (~10 min per run) and flaky. In this run it failed 3/3 with a listing/row-count race — the night_*/tale.csv glob over 1001 concurrently-written objects returned count() of 509 / 779 / 783 instead of 1001 — and the job then hit the wall-clock backstop (WARNING: Timeout exceeded [3249], sending SIGTERM). Neither test_s3_glob_scheherazade nor S3 globbing/listing is touched by this PR (it only changes how the Query Condition Cache is keyed, folding the ETag into the key), so the failure cannot be caused by these changes. Before the recent master merge this job passed; the merge pulled in the --dist=each flaky-check that now amplifies the slow module across workers.

@groeneai, could you investigate the test_s3_glob_scheherazade slowness/flakiness (the concurrent-write listing count race) and/or the flaky-check time budget for the large test_storage_s3 module, and provide a fix in a separate PR? I could not find an existing tracking issue for either. CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/109310/eb337f73256ad7e756e357bc27044041afb0d265/integration_tests_amd_asan_ubsan_flaky/logs.tar.gz

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, taking it in a separate PR (plus a tracking issue). One correction to the root cause: this is a write-side race plus the sequential-write slowness, not an S3 listing/pagination bug.

From the failing flaky-check logs (gw0): only 514 of the 1001 night_*/tale.csv inserts were even issued before the SELECT count() ran, and 491 finished. The test fans out 30 threading.Thread workers, each doing sequential single-row INSERT ... VALUES round-trips (~1001 total, ~10 min). Under the ASan server's load the writer connections hit Code: 210 ... Broken pipe ... (NETWORK_ERROR), and the Python threads die silently (threading.Thread swallows the exception, job.join() returns clean), so the glob then reads a partial object set and returns 509/779/783 (514 issued here) instead of 1001. So the short count is missing writes, not a short LIST.

Fix direction for the separate PR: replace the 30-thread sequential writer with a single server-side partitioned write (INSERT INTO TABLE FUNCTION s3('.../night_{_partition_id}/tale.csv', ...) PARTITION BY ... SELECT ... FROM numbers(1001)). That writes all 1001 objects in one atomic query (no silent thread deaths, no ~1000 round-trips), and still exercises the >1000-object glob. I will open the PR and the tracking issue and link both here.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR: #110167. Tracking issue: #110165. Rewrites the writer as batched server-side partitioned inserts (all 1001 objects, no client threads, no ~1000 round-trips); passes locally in ~33s (was ~10 min and failing 3/3), and the assertion is strengthened to verify every distinct file exists (sum(column1)=500500).

alexey-milovidov and others added 2 commits July 13, 2026 00:33
…id flaky-check OOM/timeout

The overwrite-invalidation test wrote a `numbers(1000)` Parquet object twice
(once for `v1`, once for the `v2` in-place overwrite) with
`output_format_parquet_row_group_size = 1`, i.e. 1000 row groups per write.
That made it by far the slowest test in `test_storage_s3` (~283s). The
integration flaky check runs the whole `test_storage_s3` module 3x concurrently
(`pytest -n 3 --dist=each`) under ASan, and this test runs last, so under peak
accumulated memory pressure its post-write `SELECT` hung and the `clickhouse`
client was SIGKILLed (`Return code: -9`), turning into a job-level timeout.

Reduce both inserts to `numbers(200)`. With `id < 100` this still produces 100
prunable row groups out of 200 (so `QueryConditionCacheMisses` and
`QueryConditionCacheHits` remain non-zero and the ETag-invalidation assertions
are unchanged), while making the test strictly lighter than the single-write
`test_query_condition_cache` that passes reliably in the same job.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/109310/aae9b291098f14ada806c8f84360d94c2287a99a/integration_tests_amd_asan_ubsan_flaky/

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

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 78.00% +0.10%

Changed lines: Changed C/C++ lines covered: 38/38 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is good for me.

@alexey-milovidov alexey-milovidov self-assigned this Jul 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 13, 2026
Merged via the queue into master with commit 81f54fb Jul 13, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-condition-cache-object-storage-etag branch July 13, 2026 21:45
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 13, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Add `test_query_condition_cache_overwrite_invalidation` to `test_storage_s3`
that overwrites the same object in place between two `SELECT`s (via
`s3_truncate_on_insert = 1`) and asserts the second query misses the old
cache entry (`ProfileEvents['QueryConditionCacheMisses']`) and returns the
new rows. This exercises the core correctness contract of keying
object-storage entries by ETag: an in-place rewrite yields a new ETag and
therefore a new cache key, so stale row-group information is not reused.

Requested in review of ClickHouse#109310

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…cache-object-storage-etag

Query Condition Cache: key object-storage entries by ETag
@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