Repository navigation
Detect when tables behind a query have changed - #108721
alexey-milovidov wants to merge 313 commits into
Conversation
|
Workflow [PR], commit [6435c01] Summary: ❌
AI ReviewSummaryAdds table modification hashes, optional query-cache consistency, and Findings❌ Blockers
💡 Nits
Tests
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 VerdictStatus: ❌ 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. |
CI statusAll PR-relevant checks are green: the full build matrix (amd/arm × debug/asan/tsan/msan/ubsan/binary/coverage), 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 (
The |
|
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. Fix: Regressions added:
Both verified locally against a build with the fix. |
…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]>
Decision on the remaining AI-Review Block (URL / object storage
|
|
CI note: the |
|
CI triage / status (automated continue-pr pass)
Sole CI red —
The workflow is already re-running, which should clear the flaky red. No code change is needed. |
|
Merged current
Review state: 0 unresolved threads, AI Review ✅ Approve. The only red before the merge was |
|
CI triage — The failure is
Clears on re-run. The rest of CI is green so far; AI-Review is ✅ with 0 unresolved threads. |
|
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
All three clear on re-run; the failed jobs cannot be re-run yet because the parent workflow run ( @groeneai, there is no open tracking issue for |
|
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.
None of these touch |
# 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]>
# 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]>
|
🕵 Pushed d92b774:
@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 ( The |
|
This is the Iceberg write race from #127670: with a row format, The fix in progress is my #105667. For a new table or a table function it rejects a After #105667, the race stays reachable only through a row-format table whose definition was stored before the upgrade ( |
…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]>
|
🕵 Pushed 72f2217:
|
…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]>
Fixes the `modernize-use-nodiscard` error of clang-tidy in `QueryConsumedObjectSets.h`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=72f22177fe8d6f6536ff22645ec79bb38f77ceda&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #108721 Co-Authored-By: Claude Fable 5.2 <[email protected]>
…_partial_column_revoke` The style check requires the `current_database = currentDatabase()` condition in queries to `system.query_log`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=72f22177fe8d6f6536ff22645ec79bb38f77ceda&name_0=PR&name_1=Style%20check #108721 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]>
|
🕵 Pushed 39d4e0b:
One review thread remains open: the |
# Conflicts: # src/Storages/MergeTree/MergeTreeData.cpp
… 26.12 in the settings history The `settings_changes_history` style check requires a new setting to be recorded under the current version, which is now 26.12. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=39d4e0b0c62d1a2f2c0b0646a6c1aebe3cdd3e37&name_0=PR&name_1=Style%20check #108721 Co-Authored-By: Claude Fable 5.2 <[email protected]>
Fixes the `modernize-use-nodiscard` clang-tidy error in `ReadFromObjectStorageStep.cpp`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=108721&sha=39d4e0b0c62d1a2f2c0b0646a6c1aebe3cdd3e37&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29 #108721 Co-Authored-By: Claude Fable 5.2 <[email protected]>
| 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; |
There was a problem hiding this comment.
[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.
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
getModificationHashonIStoragereturns an optionalUInt128that 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 returnsNULLwhen 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 -> Atransition):MergeTreefamily: 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 metadataALTERand 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.MergeandDistributed: combine the hashes of the underlying tables (Distributedasks each shard throughsystem.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.ViewandMaterializedVieware looked through: a view hashes the tables behind its storedSELECT(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.URLand object storage (S3, ...) trust the resource's strong (non-weak)ETagwhen one is exposed, and fail closed (reportNULL) otherwise - for glob/failover patterns, a weak or absentETag, or an unreachable source. TheETagis loop-free for content (the sameETagdenotes the same content), but unlike the engines above there is no monotonic version to fold, so anA -> B -> Arewrite 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.Filefails closed: its only change signals are size and modification time, both weak.It is exposed as a lazily-computed
modification_hashcolumn insystem.tables, and used for two features: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; aFiletable; aURL/object-storage table without a strongETag; 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 aDistributedtable cannot be seen and remain part of the best-effort window; a subquery whose ownSETTINGSclause 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 CHANGEDfor 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
clickhousebinary was built and all new tests pass locally, including a functional check thatDistributed.modification_hashchanges when a remote table changes and thatIF CHANGEDskips refreshes while the source is unchanged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a
modification_hashcolumn tosystem.tablesthat changes whenever the data behind a table changes. Based on it, added a settingquery_cache_use_only_when_data_was_not_changedto make the query cache consistent (a cached result is reused only while the referenced tables are unchanged) and aREFRESH ... IF CHANGEDoption for refreshable materialized views to skip refreshes when the source data did not change.Workflow [PR]
Sync PR [sync-upstream/pr/108721]