Skip to content

Detect when tables behind a query have changed - #108721

Open
alexey-milovidov wants to merge 313 commits into
masterfrom
detect-table-modification
Open

alexey-milovidov wants to merge 313 commits into
masterfrom
detect-table-modification

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

Closes: #108713

Adds a way to detect when the data behind a query has changed, and uses it to make the query cache consistent and to skip unnecessary refreshes of materialized views.

A new virtual method getModificationHash on IStorage returns an optional UInt128 that changes whenever the data behind the table changes (similar to an HTTP ETag). It is not a hash of the data and the way it is computed is engine-specific. It returns NULL when the engine cannot give a usable value, so callers fail closed.

Implemented for engines that can expose a loop-free (no-ABA) value - one that never returns to an earlier value across a change-and-change-back (an A -> B -> A transition):

  • MergeTree family: the block-number ranges of the active data parts, their content checksums, the table structure/key metadata, a per-lifetime counter that advances on every active-part-set change (so a drop that restores an identical part set does not reproduce an earlier hash), and a per-lifetime metadata version that advances on every metadata change (so a metadata ALTER and back does not either). Changes on insert, merge, mutation, ALTER.
  • Memory: identity of the current set of blocks plus the row count and a monotonic version.
  • Log, TinyLog, StripeLog: total rows and bytes plus structure and a monotonic version.
  • Merge and Distributed: combine the hashes of the underlying tables (Distributed asks each shard through system.tables), folding each table's identity (database, name, UUID) so two different tables with the same hash are distinguished; they fail closed if any underlying table does.
  • View and MaterializedView are looked through: a view hashes the tables behind its stored SELECT (plus its own UUID, columns, and security metadata), a materialized view hashes its target table. They fail closed for parameterized views and in databases without table UUIDs (Ordinary), where incarnations of a re-created view cannot be told apart.

URL and object storage (S3, ...) trust the resource's strong (non-weak) ETag when one is exposed, and fail closed (report NULL) otherwise - for glob/failover patterns, a weak or absent ETag, or an unreachable source. The ETag is loop-free for content (the same ETag denotes the same content), but unlike the engines above there is no monotonic version to fold, so an A -> B -> A rewrite back to byte-identical content within a single query's read window can in principle repeat it. That residual is narrow and both consumers below are opt-in, so we keep these engines in the feature rather than drop them. File fails closed: its only change signals are size and modification time, both weak.

It is exposed as a lazily-computed modification_hash column in system.tables, and used for two features:

  • New setting query_cache_use_only_when_data_was_not_changed: when enabled, the combined modification hash of the tables referenced by a query is folded into the query cache key, so a cached result is reused only while none of those tables changed. If consistency cannot be guaranteed (e.g. a query calling a non-deterministic function, whose result can change while every referenced table is unchanged; a table function; a File table; a URL/object-storage table without a strong ETag; an object-storage read pruned by a _path/_file/Hive-partition filter, where the consumed subset cannot be compared with the full listing; a query inside a transaction, which reads the transaction's snapshot while the hash samples the live table state; a referenced table with an active row policy for the current user, which changes what the user reads while every referenced table is unchanged - row policies existing only on remote shard servers of a Distributed table cannot be seen and remain part of the best-effort window; a subquery whose own SETTINGS clause changes a setting, since its tables are probed under the query's settings rather than the ones the subquery reads with; or a cached subquery containing a scalar subquery, which the analyzer has already executed and replaced with a constant), the query cache is bypassed for that query.
  • REFRESH ... IF CHANGED for refreshable materialized views: a scheduled refresh is skipped when none of the tables the view reads from changed since the last refresh that rebuilt the view (e.g. REFRESH EVERY 1 MINUTE IF CHANGED). It always rebuilds when a source table cannot prove it is unchanged.

The clickhouse binary was built and all new tests pass locally, including a functional check that Distributed.modification_hash changes when a remote table changes and that IF CHANGED skips refreshes while the source is unchanged.

Changelog category (leave one):

  • New Feature

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

Added a modification_hash column to system.tables that changes whenever the data behind a table changes. Based on it, added a setting query_cache_use_only_when_data_was_not_changed to make the query cache consistent (a cached result is reused only while the referenced tables are unchanged) and a REFRESH ... IF CHANGED option for refreshable materialized views to skip refreshes when the source data did not change.


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

@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6435c01]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds table modification hashes, optional query-cache consistency, and REFRESH ... IF CHANGED. Reviewed head 6435c01a48ca13b9c8ca055e4ed943bcb4cf8609, including all prior inline discussion. One new cache-writer defect and three remaining correctness/access concerns prevent approval. Previously accepted external-validator and table-set limitations are not raised again.

Findings

❌ Blockers

  • Cloned writers discard consistency validation. QueryResultCache.h:349: the copy constructor omits consistency_validator. A successful speculative IN set build executes and finalizes a cloned writer, bypassing both post-read source checks and resolved non-determinism flags. An IN source using arrayJoin(groupArraySample(1)(x)) over Memory can consequently cache its unseeded sample despite the consistency setting. Copy the validator and test the cloned path. New inline finding.

  • Matching usernames do not establish matching reader roles. MergeTreeData.cpp:16149 and StorageDistributed.cpp:2238: ordinary TCP enables default roles even if the initiating session used SET ROLE NONE. A restrictive policy on a default role can change a parallel reader's result while the caller's hash remains unchanged. The same exception in Distributed introspection lets a default role's full-source grant reveal changes to a source column the caller cannot read. Validate the effective roles or fail closed. Replied once and reopened the existing parallel-reader thread and introspection thread, whose claimed fixes remain incomplete.

  • The subquery's first probe can follow its data snapshot. Planner.cpp:615 [dismissed by author -- https://github.com/Detect when tables behind a query have changed #108721#discussion_r4272499788]. Still present: IdentifierResolver captures a Memory snapshot at H0; one concurrent insert before the Planner probe makes both live probes see H1, while execution reads the captured H0 blocks. The writer can store old rows under the current key. Establish the first probe before snapshot acquisition, validate the captured snapshots, or disable this path. The author silently resolved this point; it is retained here without another inline comment or reopening.

  • Effective view-security context changes can escape both probes. StorageView.cpp:918 [dismissed by author -- https://github.com/Detect when tables behind a query have changed #108721#discussion_r4238180930]. Still present: the pre-probe, actual read, and post-probe construct independent effective contexts. A definer-profile or source-policy change from A to B and back during a read can certify rows read under B with A's hash, also through a materialized view. Pin/validate an effective-context generation for the whole read, or fail closed. The author deferred a design decision; the existing thread remains open and receives no repeated comment.

💡 Nits

  • query-cache.mdx:177 still renders the setting's introduction as 26.9, whereas its current DECLARE history in src/Core/Settings.cpp:7436 says 26.12. Regenerate the setting documentation from the current source. This is the drift previously tracked in the version-history thread; no repeated inline comment was posted.
Tests
  • ⚠️ Add a cloned IN-source regression proving that an unseeded aggregate is not cached, with a seeded control.
  • ⚠️ Cover an insert between Memory snapshot acquisition and the first subquery consistency probe.
  • ⚠️ Cover same-user TCP reads after SET ROLE NONE: a default-role policy change for parallel reads, and a full-source default-role grant through a narrower Distributed wrapper.
  • ⚠️ Verify that a transient effective-security-context change cannot publish a cache entry or refresh watermark for different read semantics.

The Praktika report reports 15,465 passed, 4,590 skipped, and no failed tests. The findings above are source traces; no local builds or tests were run in this CI job.

Final Verdict

Status: ❌ Block

Preserve cloned-writer validation, validate TCP reader roles, tie subquery hashes to their read snapshots, and close or explicitly settle the effective-security-context gap before approval.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 28, 2026
Comment thread src/Storages/StorageLog.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI status

All PR-relevant checks are green: the full build matrix (amd/arm × debug/asan/tsan/msan/ubsan/binary/coverage), Fast test, Style check, Code Review, and the stateless test stages across sanitizers.

The two red stages are pre-existing known flaky crashes, unrelated to this PR — the new code is absent from both stack traces, and none of this PR's commits touch the affected files (src/Disks/*, KeyCondition, indexes, query planning):

The src/Disks/* changes visible in the diff come from merging master (to pick up 26.7 and fix 02995_new_settings_history), not from this PR.

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageLog.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the Block verdict in 9dbe8e6.

You're right, and I was wrong to dismiss it in r3488497869: a sorting-key change is query-visible. ALTER TABLE ... MODIFY ORDER BY can reduce the sorting key (e.g. PRIMARY KEY k ORDER BY (k, v) → MODIFY ORDER BY k) without changing the column list, and for the ReplacingMergeTree family the sorting key is the deduplication key, so FINAL results change while parts/checksums/columns/UUID stay the same. Reproduced locally: two parts (1,10) and (1,20), SELECT count() FROM t FINAL = 2, then ALTER TABLE t MODIFY ORDER BY k → 1, with the active part set unchanged.

Fix: MergeTreeData::getModificationHash now folds the table's key-metadata ASTs (partition, sorting, primary, sampling) into the structure portion of the hash. Secondary indices, projections and table settings remain excluded (performance only, not query results over the same parts).

Regressions added:

  • 04402: the hash changes (and the FINAL result changes) after ALTER ... MODIFY ORDER BY.
  • 04403: with query_cache_use_only_when_data_was_not_changed = 1, a cached SELECT count() FROM t FINAL returns the fresh result (1) after the ALTER instead of the stale cached 2.

Both verified locally against a build with the fix.

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageMerge.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Jun 29, 2026
…ication hash

AI-Review (PR #108721) raised the last remaining `A -> B -> A` hole in the
`query_cache_use_only_when_data_was_not_changed` and `REFRESH ... IF CHANGED`
consistency checks. Round 9 made the `MergeTree` modification hash loop-free,
but `URL` and object storage still folded a content-derived fingerprint (the
`ETag`, size and modification time). All of those return to an earlier value
across a change-and-change-back - rewriting a resource back to byte-identical
content within the same second restores the strong `ETag`, the size and the
second-granular modification time - so the pre/post equality check the
consumers rely on could pass while the read actually saw the transient state
`B`, storing or remembering a result built from `B` under state `A`'s key.

Unlike the block numbers of `MergeTree` or the `data_version` of `Memory`/`Log`,
an arbitrary HTTP resource or object store exposes no monotonic, no-ABA version
(S3 object versioning is not generally enabled, HDFS has no `ETag`). There is
nothing to fold that would make the value not repeat, so
`IStorageURLBase::getModificationHash` and `StorageObjectStorage::getModificationHash`
now fail closed and return nullopt, exactly as `StorageFile` already does.
`system.tables.modification_hash` is then NULL for these engines, and because
`computeQueryReferencedTablesModificationHash` bails out as soon as any
referenced table returns nullopt, the query cache is bypassed and
`REFRESH ... IF CHANGED` always rebuilds for them - the safe direction (a missed
cache reuse or an extra refresh, never a stale result). This also makes the
contract uniform: `getModificationHash` now returns a value only when it is
loop-free, so the value `Distributed` reads from a remote shard's
`system.tables` is loop-free-or-NULL with no separate path.

Document the loop-free (no-ABA) requirement on the `IStorage::getModificationHash`
contract and in the user docs (query cache, `REFRESH ... IF CHANGED`,
`system.tables`). Remove the now-unused `etag` field this PR had added to
`HTTPFileInfo`.

Add `04489_external_engine_modification_hash_fail_closed`: `File`/`URL` report a
NULL modification hash, and a query over a fail-closed table with the
consistency setting reflects an append immediately (the cache is bypassed rather
than serving a stale result). The real `A -> B -> A` race needs a controllable
external server and is not deterministically reproducible in a functional test;
the test locks in the invariant that forecloses it.

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

Copy link
Copy Markdown
Member Author

Decision on the remaining AI-Review Block (URL / object storage A -> B -> A)

The AI-Review's last open point asks every engine participating in query_cache_use_only_when_data_was_not_changed / REFRESH ... IF CHANGED to expose a no-ABA modification value, or to fail closed for URL and object storage. We are deliberately not failing closed for those engines (round 10, which did, is reverted in 46606a7), so this Block stands by design.

Rationale:

  • The strong ETag is loop-free: a given ETag denotes a single content state. It never yields a false "unchanged" for the common case — an object that changes and stays changed gets a different ETag, so the pre/post equality check drops the cache entry / re-runs the refresh.
  • The residual hole requires an external object to change to B and back to byte-identical A (restoring the same strong ETag, size and second-granular modification time) within the exact window of a single query's read, serving matching strong ETags throughout. That is extraordinarily narrow.
  • Both consumers are opt-in: query_cache_use_only_when_data_was_not_changed defaults to false, and REFRESH ... IF CHANGED is an explicit request.
  • Unlike MergeTree (block numbers + a per-lifetime active-part-set counter), Memory/Log/StripeLog (data_version), an arbitrary HTTP resource or object store exposes no monotonic, no-ABA version to fold. The only "no-ABA" option is to drop these engines from the feature entirely, which we choose not to do.

So: engines where a no-ABA value is achievable provide one and are fully consistent; for external-ETag engines we accept the narrow residual in exchange for keeping them in the feature. URL/object storage still fail closed for the cases we genuinely cannot validate (glob/failover patterns, weak or absent ETag, unreachable sources).

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI note: the BuzzHouse (amd_debug) red — Logical error: Distributed task iterator is not initialized (STID: 4662-3e65) — is the known pre-existing fuzzer flake tracked in #107898, not a regression from this PR. It is thrown in RemoteQueryExecutor::processReadTaskRequest (the distributed read-task protocol for parallel replicas / cluster table functions); this PR's getModificationHash only issues a plain GET_ONE SELECT with no task iterator, so it cannot reach that path. Master history shows the same error on master (pull_request_number = 0) and ~1-2 random PRs per day for the past month. AI-Review is ✅ Approve; the rest of CI is green.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage / status (automated continue-pr pass)

  • AI Review: ✅ Approve, and there are 0 unresolved review threads. No cursor[bot] or other actionable review summaries are pending.
  • MERGEABLE, no conflicts. Merge-base with master is 0a567fc (2026-06-29 20:18Z, < 1 day old), so no re-merge was done even though the branch is behind — the only red is unrelated and not master-fixable.

Sole CI red — BuzzHouse (amd_debug): Logical error: Distributed task iterator is not initialized (STID: 4662-3e65) — unrelated, pre-existing flaky.

  • Tracked by open issue Logical error: Distributed task iterator is not initialized (STID: 4662-3e65) #107898 (created 2026-06-18 from PR Add read-checksums command to clickhouse-disks #106901's Stress test (arm_tsan)).
  • It fires on master (pr=0) on 3 separate days and across ~18 unrelated PRs over the last 30 days — not specific to this PR.
  • The other three BuzzHouse configs (arm_asan_ubsan, amd_tsan, amd_msan) all passed on this same commit, confirming a build-independent race.
  • The error is raised in RemoteQueryExecutor::processReadTaskRequest (RemoteQueryExecutor.cpp:743), reached only from the async cluster-function / parallel-replicas read path (readAsync → RemoteSource::tryGenerate). This PR does not touch that file. The new StorageDistributed::getModificationHash path issues a plain synchronous SELECT modification_hash, toString(uuid) FROM system.tables via RemoteQueryExecutor with PoolMode::GET_ONE and no Extension/task iterator, using readBlock (not readAsync), so it cannot trigger this error.

The workflow is already re-running, which should clear the flaky red. No code change is needed.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged current master into the branch (commit ce10d390966). The branch had fallen ~635 commits behind and GitHub was reporting a CONFLICTING/DIRTY state, but the three-way merge against the current master tip resolved cleanly with no manual conflict resolution — the stale status has now recomputed to MERGEABLE.

master had touched several of this PR's feature files since the merge base (StorageURL.cpp +106/-39, ReadWriteBufferFromHTTP.{cpp,h}, StorageObjectStorage.cpp, MergeTreeData.cpp). To make sure the textually-clean auto-merge is also semantically sound, I rebuilt those four translation units against the merged headers — all compiled cleanly. The PR's ETag-based getModificationHash logic and SettingsChangesHistory entry are intact.

Review state: 0 unresolved threads, AI Review ✅ Approve. The only red before the merge was BuzzHouse (amd_debug)'s Distributed task iterator is not initialized — the known flaky #107898 (fires via the async RemoteQueryExecutor::readAsync→RemoteSource::tryGenerate path, which this PR's synchronous system.tables read for the Distributed hash never reaches). Fresh CI is now running on the merge commit.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage — Stateless tests (arm_binary, parallel) red is a known flaky test, not a regression from this PR.

The failure is 04093_msan_fiber_distributed_false_positive: Code: 102 UNEXPECTED_PACKET_FROM_SERVER: expected TablesStatusResponse, got ProfileInfo on SELECT count() FROM remote('127.0.0.{1,2}', system.one). This is the "connection left in a broken state" flake class (cf. closed #93018) — a connection-pool protocol desync under parallel test load.

  • Not this PR: over the last 45 days it fires on 8 unrelated PRs and never on master (pull_request_number=0). The query above does not touch the query cache, system.tables.modification_hash, or REFRESH ... IF CHANGED, so this PR's getModificationHash is never invoked on its path.
  • The Distributed modification-hash probe (getModificationHashOfRemoteTableInShard) drains its RemoteQueryExecutor cleanly (reads to end-of-stream, then finish() on both the value and the fail-closed paths), so it does not leave a pooled connection desynced. The functional tests here only use test_shard_localhost / a self-referential Distributed (local/fail-closed paths, no remote-shard query).

Clears on re-run. The rest of CI is green so far; AI-Review is ✅ with 0 unresolved threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage (automated continue-pr pass) — the remaining reds are pre-existing flaky tests, not regressions from this PR. AI-Review is ✅ Approve with 0 unresolved review threads, and the PR is MERGEABLE. Two of the three failures are not yet documented above (the arm_binary / 04093_msan_fiber_distributed_false_positive one was already triaged in the previous comment):

  • Fast test (arm_darwin) / 03988_keeper_client_autocomplete (report). Over the last 45 days it fires on 10+ unrelated PRs and never on master (pull_request_number = 0), with an onset of 2026-06-25 (a recently added test). It exercises clickhouse keeper-client autocomplete on macOS — no code path touched by this PR (getModificationHash, system.tables.modification_hash, the query cache, or REFRESH ... IF CHANGED).

  • Stateless tests (amd_tsan, parallel, 1/2) / 01600_quota_by_prefix_forwarded_ip (report). Fails only on two unrelated PRs (108772, this one) and never on master. It is an HTTP quota test with retry loops (retries=300) under parallel load and randomized quota intervals — a classic parallel-load flake, and unrelated to this PR's feature.

All three clear on re-run; the failed jobs cannot be re-run yet because the parent workflow run (28480508142) is still in_progress.

@groeneai, there is no open tracking issue for 03988_keeper_client_autocomplete or 01600_quota_by_prefix_forwarded_ip. Could you investigate these flakes and provide a fix in a separate PR? If a fix is already in progress, please link it here.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage (consolidated) — all three remaining red checks are pre-existing flaky tests, unrelated to this PR. Everything else is green (143 successful checks, including all sanitizer builds, stress, and fuzzer jobs), AI-Review is ✅, and there are 0 unresolved review threads.

Test Failing job(s) Why it's a flake, not this PR
04093_msan_fiber_distributed_false_positive Stateless (arm_binary), Stateless (amd_tsan, 1/2) Connection-pool desync (expected TablesStatusResponse, got ProfileInfo, cf. closed #93018). Fires on 8 unrelated PRs / 0 on master (45d). Its query SELECT count() FROM remote(...) never invokes getModificationHash; the Distributed probe drains its RemoteQueryExecutor cleanly.
01600_quota_by_prefix_forwarded_ip Stateless (amd_tsan, 1/2) Quota MAX QUERIES = 1 retry-loop timing test. Fires on 2 unrelated PRs / 0 on master. The access check added here issues no queries and is not on this test's path.
03988_keeper_client_autocomplete Fast test (arm_darwin) macOS-specific: fires on 13 unrelated PRs, always on Fast test (arm_darwin), 0 on master. Keeper-client CLI test, unrelated to this PR.

None of these touch modification_hash / the query cache / the access-control change. They clear on a re-run of the three jobs.

alexey-milovidov and others added 9 commits November 10, 2026 02:49
# Conflicts:
#	src/Storages/StorageLog.cpp
…odification hashes

A `DETACH` / `ATTACH` keeps the table UUID and can restart the metadata version, while the
configuration is loaded anew, e.g. after an `ALTER NAMED COLLECTION`. The same resource with the
same strong `ETag` can then be decoded differently (`CSV` -> `TSV`), or a different S3 `versionId`
can be read, without any hashed input moving.

`IStorageURLBase::getModificationHash` now folds the format, compression method, HTTP method,
headers and the format settings (their source settings hash, or the hash of the reading context's
settings when the table captured none). `StorageObjectStorage::getModificationHash` folds the data
source description, format, compression method, format settings and the S3 `versionId`, the same
inputs `ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey` covers for this lifecycle.

Address review feedback on `src/Storages/StorageURL.cpp` (external-table hashes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tive reader

A materialized view pushes its read straight into the target table, without a planner of its own,
so the `additional_result_filter` of the effective reader (the definer under `SQL SECURITY DEFINER`)
is never applied to that read: the planner of the reading query applies, and hashes, the filter of
its own settings. Folding the definer's filter into `getModificationHash` made a profile change that
returns the same rows move the hash, so a `REFRESH ... IF CHANGED APPEND` reading the view appended
the unchanged rows again (and the `system.tables` introspection path reported `NULL`).

`computeAdditionalFiltersModificationHash` no longer parses or walks `additional_result_filter`, and
`updateHashWithRowAffectingSettings` gets `include_additional_result_filter`, which
`StorageMaterializedView::getModificationHash` passes as false.

Address review feedback on `src/Storages/StorageMaterializedView.cpp` (unused result filters).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… cannot follow

The tables of a query are probed under one context, while the analyzer plans a subquery with its own
`SETTINGS` under a separate one. A subquery's `prefer_localhost_replica = 0` makes a `Distributed`
table read its local shard over TCP under the shard user's profile, while the probe takes the
in-process branch, so a change of that profile was invisible to the consistent query cache. The same
scope loss bypassed the guards for nested `skip_unavailable_shards` and parallel-replica reads.

`computeQueryReferencedTablesModificationHash` now fails closed when any `SETTINGS` clause in the AST
sets a value different from the probing context. The settings of the root, already applied to the
context, compare equal; query cache settings and others ignored by the query cache key, and the filter
settings that are hashed with their own dependencies, are not counted.

Address review feedback on `src/Interpreters/Cache/QueryResultCache.cpp` (per-scope contexts).

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

The analyzer executes a scalar subquery while it resolves the tree, before the planner of an
enclosing subquery cached with `query_cache_use_only_when_data_was_not_changed = 1` installs the
object-set capture that keeps unvalidated cache entries from being served. The constant that replaces
the scalar subquery also hides its tables from the AST hashed for the key, so the enclosing subquery
could certify rows older than the hashes it took. Fail closed in that case.

Address review feedback on `src/Planner/Planner.cpp` (scalar subqueries executed during analysis).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`computeFiltersModificationHashes` hashed the dependencies of the filters from
`additional_table_filters` / `additional_result_filter` without the scope check of
`astHasScopeSettingsDifferentFromContext`, so a filter subquery with its own `SETTINGS`
(e.g. `prefer_localhost_replica = 0` reading a `Distributed` table over TCP) was probed
under the caller's context. Run the check on every filter AST as well. The check now
also inspects `ASTSetQuery::default_settings`: a `SETTINGS name = DEFAULT` reset counts
when it changes the value of the probing context.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…other user

A local replica of `cluster_for_parallel_replicas` that is read over TCP (no local plan,
e.g. `parallel_replicas_prefer_local_replica = 0`, or a cluster of several replicas) runs
as the user configured for the cluster, and that user's profile (`additional_table_filters`,
`final`, ...) changes the rows without changing the parts. `MergeTreeData::getModificationHash`
is computed under the caller's context, so it now stays known only when the whole read is
the in-process local plan of a single local replica, or every replica reads as the caller
(the cluster has an inter-server secret, or the configured user is the caller).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… object-storage hashes

Whether a declared column is read from the file or filled from the Hive partition in the
path is captured from `use_hive_partitioning` when the table is loaded. A `DETACH` /
`ATTACH` with another value keeps the UUID and can restart the metadata version, so the
rows read from an unchanged resource changed while the modification hash did not. Fold
the mapping, as `ReadFromObjectStorageStep::makeTopKQueryConditionCacheKey` already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflict in `ReadFromObjectStorageStep::createIterator`: master sets the join runtime
filters for file pruning on the iterator; this branch wraps it in `CapturingObjectIterator`.
Set the runtime filters first, on the unwrapped iterator, and mark the consumed object set
as pruned when such filters are present, since they make the read consume a subset of the
listing, like a `_path` / `_file` filter. Conflict in the includes of `StorageView.cpp`:
kept both sides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 13, 2026 14:10
# Conflicts:
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
#	src/Storages/StorageMaterializedView.h
…ageURLBase::getModificationHash`

Master removed `StorageURLSource::setCredentials` in favour of `setCredentialsFromURL` with the
`http_forbid_headers` filter. The probe now applies the same filter as the reader, inside the
`try`, so forbidden credentials are never sent and the hash fails closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` safe to run concurrently

Users are server-wide, so concurrent runs in the flaky check dropped and re-created each other's
`u_05619` (`UNKNOWN_USER`, `HAVE_DEPENDENT_OBJECTS`). Convert the test to `.sh` (the file rename
landed in the previous commit) and make the user name unique per database.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…able of a materialized view

`StorageMaterializedView::readImpl` requires the effective reader's `SELECT` on the source table of
the view (`select_table_id`) as well as on the target table, but `getModificationHash` checked only the
target. After a revoke of the source grant the hash stayed the same, so the consistent query cache
served a result where an uncached read raises `ACCESS_DENIED`. Now the hash is `NULL` unless the
effective reader can read every view column from the source table.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed d92b774:

  • Merged origin/master (c2ee5c2). There were two conflicts. In StorageMaterializedView.h, I kept both the PR's getModificationHash and master's new incremental-refresh checks. In ReadFromObjectStorageStep.cpp, I kept master's RuntimeFilterPruningPredicate construction and then the PR's consumed-object-set capture. Master removed StorageURLSource::setCredentials, so the URL probe now calls setCredentialsFromURL with the http_forbid_headers filter inside the fail-closed try (896f696).
  • Flaky checks: 05619_materialized_view_modification_hash_definer_result_filter used the fixed server-wide user u_05619, so concurrent runs collided (UNKNOWN_USER / HAVE_DEPENDENT_OBJECTS). It is now a .sh test with a per-database user name (3d1c074).
  • Review blocker: the materialized-view hash now fails closed when the definer cannot read the source table (d92b774), with a new test 05629_materialized_view_modification_hash_source_grant.
  • ninja clickhouse builds. I ran both tests and 10 existing materialized-view modification-hash tests against a local server, and they pass.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=3819a9e47bb4b9fc42ba19e2c9e62f489980cf5f&name_0=PR&name_1=La%20Casa%20Del%20Dolor%20%28amd_tsan%29 (ThreadSanitizer: data race in WriteBuffer::write from ParallelFormattingOutputFormat::collectorThreadFunction, STID 1003-46d8; this PR does not touch output formats) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The getViewContext A -> B -> A thread on StorageView.cpp is still open for a design decision.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the Iceberg write race from #127670: with a row format, startNewFile gets a ParallelFormattingOutputFormat, whose collector thread writes the data file buffer while MultipleFileWriter::consume reads buffer->count() on the inserting thread. The trigger is the fuzzer's last statement, INSERT INTO TABLE FUNCTION icebergLocal(local, ..., compression = 'zstd', format = 'TSVWithNamesAndTypes', ...).

The fix in progress is my #105667. For a new table or a table function it rejects a format the data lake cannot store (for Iceberg, anything but Parquet, ORC, Avro and Vortex) and an explicit compression, so this INSERT fails with BAD_ARGUMENTS. @ PedroTadim closed the direct race fix #129168 in favour of it (#129168 (comment)). #105667 is green at 987b7a60 (only CH Inc sync fails) and waits for @ alesapin to re-review his CHANGES_REQUESTED from 2026-05-28.

After #105667, the race stays reachable only through a row-format table whose definition was stored before the upgrade (ATTACH, RESTORE). If you want the race fixed before #105667 merges, I can send the change from #129168 (Iceberg data files formatted on the inserting thread) as a new PR.

Comment thread src/Storages/IStorage.cpp Resolved
alexey-milovidov and others added 3 commits November 18, 2026 05:14
…cation

Resolved conflicts: kept the PR's `getModificationHash` declaration in `StorageMaterializedView.h` while taking master's revert of the incremental refresh source checks; master's new move overload of `IStorage::setInMemoryMetadata` also advances `metadata_version_for_modification_hash`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… hashing a view

Master added a `view_query` parameter to `getViewContext` that registers the body as a `SQL SECURITY` child row of `system.query_log`. `StorageView::getModificationHash` only builds the context to hash the dependencies and never executes the body, so it passes `nullptr` and nothing is registered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ication hash

`canComputeModificationHash` accepted `SELECT` on any single column outside
`system.tables.modification_hash`. A query result cache hit skips the planner's
column checks, and a partial `REVOKE` changes neither the table hash nor the cache
key, so with `query_cache_use_only_when_data_was_not_changed` a cached
`SELECT secret_col` kept being served after `SELECT(secret_col)` was revoked while
another column stayed readable. Now every column must be readable (fail closed),
and the new test `05828_query_cache_partial_column_revoke` covers it.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 72f2217:

  • Merged origin/master (c3ec2bd) to resolve the conflicts:
    • StorageMaterializedView.h: master reverted the incremental-refresh source checks (94ac854). I took the revert and kept this PR's getModificationHash declaration.
    • IStorage.h: master added a move overload of setInMemoryMetadata. It now also advances metadata_version_for_modification_hash.
  • Fixed the build after the merge (f2d3e1b). Master added a view_query parameter to getViewContext, which registers the body as a query_log child row. StorageView::getModificationHash only hashes the view and never runs the body, so it passes nullptr and nothing is registered.
  • Review blocker on partial column grants (72f2217): canComputeModificationHash now requires SELECT on every column. Covered by the new test 05828_query_cache_partial_column_revoke.
  • ninja clickhouse builds. The new test and the related query_cache_consistency, view_modification_hash, query_log_access_info and system_tables_modification_hash tests pass on a local server. The only failures were tests that need ZooKeeper, S3, transactions or extra clusters, which the local server does not have.
  • One thread is still open: the effective-context A -> B -> A window in StorageView.cpp. It needs a design decision from the author (see my earlier reply on that thread). The previous CI run skipped the full suite because unresolved review threads blocked it.
  • @groeneai, thanks for the analysis of the TSan race. It is tracked by Reject compression_method argument for data lake engines #105667 and does not need a change here.

alexey-milovidov and others added 4 commits November 21, 2026 07:08
…cation

Conflicts:
- `src/Planner/Planner.cpp`: keep master's `shouldReadFromQueryCacheForSubquery` condition and this PR's `referenced_tables_modification_hash` argument of `tryAddReadFromQueryResultCacheStep`.
- `src/Storages/IStorage.h`: take master's removal of the `Databases/IDatabase.h` include, keep this PR's `Core/Types.h`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
A replacing refresh now sets `allow_reserved_column_names` on the refresh context in
`StorageMaterializedView::prepareRefresh` (added on master), between the two source hashes of
`REFRESH ... IF CHANGED`. A source view with `SQL SECURITY INVOKER` folds the settings it is read
with into its hash, so the pre-read and post-read hashes always differed, no watermark was recorded,
and every scheduled refresh rebuilt the view. The setting only relaxes the validation of column names
in `CREATE` and `ALTER` and cannot change the rows of a `SELECT`, so it is left out of the hash like
`max_table_size_to_drop`. This fixes `05446_refresh_if_changed_replacing_view_source`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=72f22177fe8d6f6536ff22645ec79bb38f77ceda&name_0=PR&name_1=Fast%20test
#108721

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 39d4e0b:

  • Merged origin/master (94239d4) to resolve the conflicts. In Planner.cpp I kept master's new shouldReadFromQueryCacheForSubquery condition together with this PR's referenced_tables_modification_hash argument. In IStorage.h I took master's removal of the Databases/IDatabase.h include.
  • 05446_refresh_if_changed_replacing_view_source (Fast test) was a real regression from an earlier merge: master made a replacing refresh set allow_reserved_column_names on the refresh context between the two source hashes, and an SQL SECURITY INVOKER source view folded it into its hash, so the view was rebuilt on every tick. The setting only affects CREATE/ALTER validation, so it is now left out of the hash, like max_table_size_to_drop.
  • clang-tidy: marked asTuple in QueryConsumedObjectSets.h as [[nodiscard]].
  • Style check: added the current_database = currentDatabase() filter to the system.query_log query in 05828_query_cache_partial_column_revoke.

ninja clickhouse builds. Locally, 86 of this PR's 100 tests pass, including 05446 and 05828; the other 14 need MinIO, Keeper or transactions, which my local server did not have, so they were not run to completion.

One review thread remains open: the A -> B -> A change of the effective SQL-security context during a single read (StorageView.cpp). It needs a design decision from the author, as explained in the thread.

std::atomic<bool> skip_insert = false; /// both of the above: don't even buffer the result
std::atomic<bool> result_is_incomplete = false; /// a consumer stopped reading before the end, see markResultIncomplete()
std::atomic<bool> was_finalized = false;
std::function<bool()> consistency_validator;

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.

[Blocker] Preserve the consistency validator when copying a cache writer

The existing QueryResultCacheWriter copy constructor (QueryResultCache.cpp:1594–1621) does not copy this new member. StreamInQueryResultCacheStep::clone uses that constructor, and FutureSetFromSubquery::buildOrderedSetInplace executes and finalizes the cloned writer when it successfully builds an IN set during index analysis. Its finalizeWrite therefore skips the consistency check entirely.

For example, an outer MergeTree key predicate with x IN (SELECT arrayJoin(groupArraySample(1)(x)) FROM memory_src SETTINGS use_query_cache = 1, query_cache_use_only_when_data_was_not_changed = 1, query_cache_min_query_runs = 0, query_cache_min_query_duration = 0) reaches this path. The resolved-function check marks the shared capture non-deterministic, but the cloned writer never consults it and stores the random sample under a reusable key. Post-read table-change checks are lost for the same reason.

Please copy consistency_validator in the copy constructor and cover a successfully cloned IN source, including an unseeded aggregate and a seeded control. This is verified by source tracing; no server reproduction was run in this job.

This branch was successfully deployed

1 active deployment
staging - docs — 6435c01a Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Detect when tables behind the query have changed - to improve query cache

4 participants