Repository navigation
Fix read consistency for tables renamed or exchanged during a query - #110048
Conversation
The per-query storage cache `Context::getOrCacheStorage` (added in #97411) pins a table name to the storage first resolved for it within a query, so a running query keeps reading the table version it was planned against even when a concurrent query renames or exchanges that table. #108728 added two freshness checks to the cache-hit path - reject the hit if the cached storage's current qualified name no longer matches the requested name, and reject it if the requested `StorageID` carries a UUID that differs from the cached one. Both silently defeat the pinning: after a concurrent `EXCHANGE TABLES` renames the pinned storage (and reassigns the name to a different UUID), resolving the original name re-resolves to the swapped table, so the query is analyzed for one column type and executed against another - raising a spurious `LOGICAL_ERROR` (and aborting the server in debug/coverage builds). This regressed `03915_exchange_tables_race` on `master`: the check `Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3)` started dying with Logical error: 'Arguments of 'multiply' have incorrect data types: 'n' of type 'Int256', '0.123' of type 'Float64'' on 2026-07-07 - the day #108728 merged - after 4.5 months with zero occurrences. Only the old analyzer is affected (the new analyzer resolves storages once). Restore the pinning: a cache hit is reused whenever its cached UUID still resolves to a live table, regardless of the storage's current name or the requested UUID (this is the pre-#108728 behavior). To keep #108728's fix - `CREATE OR REPLACE ... POPULATE` must drop the old table by the temporary name after its internal `EXCHANGE`, not the live one - a query that renames or exchanges a table now drops the affected names from its own per-query storage cache (`dropStorageCacheEntry`, called from `InterpreterRenameQuery`). So the query's own later lookups re-resolve to the current tables, while concurrent queries keep their own per-query caches and stay isolated. Verified on a local build: 3000 `SELECT n * 0.123 FROM (SELECT * FROM t)` racing a continuous `EXCHANGE TABLES` under the old analyzer produce zero `LOGICAL_ERROR` with the fix (vs. reproducing it with the #108728 checks in place), while `04492`/`04493` keep passing. Covered by existing tests: `03915_exchange_tables_race` (external exchange, must not raise `LOGICAL_ERROR`) and `04492`/`04493_create_or_replace_materialized_view_populate_keeps_subscription` (internal exchange, subscription must survive). CI report (Server died on master): https://play.clickhouse.com/play?user=play&run=1&tab=Query%20F#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIGNoZWNrX25hbWUsIHRlc3RfbmFtZSwgcmVwb3J0X3VybApGUk9NIGNoZWNrcwpXSEVSRSBjaGVja19zdGFydF90aW1lID49IG5vdygpIC0gSU5URVJWQUwgMjQgSE9VUgogICAgQU5EIChoZWFkX3JlZiA9ICdtYXN0ZXInIEFORCBzdGFydHNXaXRoKGhlYWRfcmVwbywgJ0NsaWNrSG91c2UvJykpCiAgICBBTkQgdGVzdF9zdGF0dXMgIT0gJ1NLSVBQRUQnCiAgICBBTkQgKHRlc3Rfc3RhdHVzIExJS0UgJ0YlJyBPUiB0ZXN0X3N0YXR1cyBMSUtFICdFJScpCiAgICBBTkQgY2hlY2tfc3RhdHVzICE9ICdzdWNjZXNzJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIExJS0UgJ2xpYkZ1enplciUnCiAgICBBTkQgY2hlY2tfbmFtZSAhPSAnQ2xpY2tIb3VzZSBLZWVwZXIgSmVwc2VuJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIElMSUtFICclZXhwZXJpbWVudGFsJScKICAgIEFORCBwb3NpdGlvbih0ZXN0X25hbWUsICdTZXJ2ZXIgZGllZCcpID4gMApPUkRFUiBCWSBjaGVja19zdGFydF90aW1l Related: #97411 Related: #108728 Related: #108726 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [cfb6bd8] Summary: ✅
AI ReviewSummaryThis PR restores per-query table pinning across concurrent Findings
Tests
Final Verdict
|
| /// internal `EXCHANGE` instead of shutting down the live one (see #108726). | ||
| if (storage.second) | ||
| return storage; | ||
|
|
There was a problem hiding this comment.
RefreshTask still has callers that intentionally poll the current table behind a name, so making every live cache hit reusable here is too broad.
For non-APPEND refreshable materialized views, StorageMaterializedView::getTargetTableId explicitly clears the UUID before returning the target id (src/Storages/StorageMaterializedView.cpp:1043). RefreshTask::waitForLatestTargetTable then loops on tryGetTable(storage_id, context) until the UUID at that name becomes last_success_table_uuid (src/Storages/MaterializedView/RefreshTask.cpp:633). With this unconditional hit reuse, once one iteration caches the old target UUID, later iterations in the same refresh_context will keep getting that renamed-away table as long as its UUID is still live after the internal EXCHANGE, so the loop can never observe the new UUID and can raise a false TABLE_UUID_MISMATCH. RefreshTask::getAndLockTargetTable has the same “retry until the name points at a different table” assumption in its retry path.
So we still need a current-name lookup path for these refresh coordination callers instead of globally treating every live cached UUID as fresh.
There was a problem hiding this comment.
This describes the long-standing behavior, not a regression introduced here. This PR restores the pre-#108728 cache-hit path (if (storage.second) return storage;), which is exactly what getOrCacheStorage did from its introduction in #97411 (2026-02-19) until #108728 added the two freshness checks on 2026-07-07.
The refresh-coordination code cited here was all written against, and coexisted with, that unconditional-live-cache behavior for ~2 months: waitForLatestTargetTable (since 2026-05-08), the getAndLockTargetTable "expect to see a different table by the same name" retry loop, and the IdentifierResolver UNKNOWN_TABLE/TABLE_UUID_MISMATCH → name fallback (since 2026-05-21). #108728 changed only getOrCacheStorage plus tests — no RefreshTask/IdentifierResolver changes and no refresh-path tests — so its freshness checks were never written or validated against these polling loops and were on master for only 3 days.
So if the pinning genuinely defeats a RefreshTask polling loop, that is a pre-existing concern independent of this PR; this change does not make it worse. dropStorageCacheEntry is invoked only for a rename/exchange performed by the query's own context (InterpreterRenameQuery); the refresh-coordination loops wait on background/replication-driven swaps performed in a different context, so their behavior is unchanged from what shipped before #108728.
Note also that these loops self-heal on the exact event they wait for: once the old target UUID is actually dropped, tryGetByUUID returns null, the stale entry is erased, and the name re-resolves to the new table. A dedicated cache-bypass path for refresh coordination, if warranted, is a separate change to the (experimental) refreshable-MV coordination and out of scope for this targeted regression fix.
…xchange-read-consistency
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@clickgapai, after this is merged, submit a PR with an additional test. |
The only regression coverage for this fix was `03915_exchange_tables_race`, which reaches the drifted-argument path through a concurrent `EXCHANGE TABLES`. That is an inherent TOCTOU race, so the path is not hit on every run and the per-arch Bugfix Validation jobs cannot classify the test: all four legs reported "Bug does not reproduce on this arch", which makes the merge-blocking `new_tests_check` hook fail (its `has_ft` branch has no fallback). A race is not required to reach the path. `ActionsDAG::updateHeader` matches header columns to DAG input nodes by name only, so binding a header column whose type differs from the type the DAG's function nodes were resolved for reproduces the drift directly, single-threaded and deterministically. The new test does exactly that and covers both failure modes the guard addresses: a strict function resolved for `Float64` handed `Int256` (the shape `03915_exchange_tables_race` races for), and a wrapper-only `String` -> `Nullable(String)` drift through `materialize`, which a wrapper-stripped type comparison would miss. A third case pins that a non-drifted argument is still folded, so the fix cannot be satisfied by disabling constant folding. Verified both directions on a debug build: against master's `executeActionForPartialResult` the first case aborts the test binary with `Logical error: 'Unexpected return type from negate. Expected Float64. Got Int256'` through `updateHeader` -> `evaluatePartialResult` -> `executeActionForPartialResult` (in debug and sanitizer builds `LOGICAL_ERROR` is an assertion failure, which is why this aborted the server during query planning); with the guard all three cases pass, 10 runs each. Also take master's version of `03915_exchange_tables_race` verbatim. Master rewrote that test after this branch forked it (pinning `enable_analyzer` and capping concurrent clients to stop the flaky check from OOMing), and ClickHouse#110048 has since fixed the read-consistency root cause the test races for, so the branch's own rewrite is both superseded and no longer the right place for this fix's coverage. Co-Authored-By: Claude Fable 5 <[email protected]>
The zero-row branch of the skipped fold builds an empty column of the node's declared result type, but not every result type can be instantiated: everything deriving from `IDataTypeDummy` throws `NOT_IMPLEMENTED` from `createColumn`. A captured lambda is an ordinary `FUNCTION` node whose result type is `DataTypeFunction`, so when one of its captured arguments was bound to a differently-typed header column, skipping the fold replaced one error with another: `Method createColumn is not implemented for data type Function( -> Float64)`. Leave the column null for those types instead. `dynamic_cast` is used rather than `typeid_cast`, because the latter compares `typeid` for exact equality and so never matches a base class. Verified on a debug build: the new `DriftOnNonInstantiableResultTypeIsSkippedCleanly` case fails with exactly that message without this hunk and passes with it. Full unit suite: 22356 tests pass. Also reword the test file's introduction. It presented a concurrent `EXCHANGE TABLES` as the current production source of the type mismatch, which is no longer accurate now that ClickHouse#110048 has restored the per-query storage-cache pinning. These tests do not depend on where the mismatch comes from - they inject it directly - so the wording is now historical. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Thanks — I looked into this but don't have a clean, confident result to post yet. If you can point me at a specific file/line or the exact behaviour you want checked, I'll dig in precisely. |
|
Hi @alexey-milovidov — while reviewing this PR I found the following:
Happy to discuss — close anything that's wrong or already addressed. |
…e-exchange-read-consistency Fix read consistency for tables renamed or exchanged during a query
The per-query storage cache
Context::getOrCacheStorage(added in #97411) pins a table name to the storage first resolved for it within a query, so a running query keeps reading the table version it was planned against even when a concurrent query renames or exchanges that table.#108728 added two freshness checks to the cache-hit path: reject the hit if the cached storage's current qualified name no longer matches the requested name, and reject it if the requested
StorageIDcarries a UUID that differs from the cached one. Both silently defeat the pinning. After a concurrentEXCHANGE TABLESrenames the pinned storage (and reassigns the name to a different UUID), resolving the original name re-resolves to the swapped table, so the query is analyzed for one column type and executed against another — raising a spuriousLOGICAL_ERROR(and aborting the server in debug/coverage builds).This regressed
03915_exchange_tables_raceonmaster. The checkStateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3)started dying withon 2026-07-07 — the day #108728 merged — after 4.5 months with zero occurrences. Only the old analyzer is affected (the new analyzer resolves storages once).
Fix. Restore the pinning: a cache hit is reused whenever its cached UUID still resolves to a live table, regardless of the storage's current name or the requested UUID (the pre-#108728 behavior). To keep #108728's fix —
CREATE OR REPLACE ... POPULATEmust drop the old table by the temporary name after its internalEXCHANGE, not the live one — a query that renames or exchanges a table now drops the affected names from its own per-query storage cache (Context::dropStorageCacheEntry, called fromInterpreterRenameQuery). So the query's own later lookups re-resolve to the current tables, while concurrent queries keep their own per-query caches and stay isolated.Verified on a local build (RelWithDebInfo, old analyzer): 3000
SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1)racing a continuousEXCHANGE TABLESproduce 0LOGICAL_ERRORwith the fix (the same harness reproduces theLOGICAL_ERRORwith #108728's checks present), while04492/04493_create_or_replace_materialized_view_populate_keeps_subscriptionkeep passing. Regression coverage stays in the existing03915_exchange_tables_race(external exchange) and04492/04493(internal exchange) tests.CI report (Server died on
master): https://play.clickhouse.com/play?user=play&run=1&tab=Query%20F#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIGNoZWNrX25hbWUsIHRlc3RfbmFtZSwgcmVwb3J0X3VybApGUk9NIGNoZWNrcwpXSEVSRSBjaGVja19zdGFydF90aW1lID49IG5vdygpIC0gSU5URVJWQUwgMjQgSE9VUgogICAgQU5EIChoZWFkX3JlZiA9ICdtYXN0ZXInIEFORCBzdGFydHNXaXRoKGhlYWRfcmVwbywgJ0NsaWNrSG91c2UvJykpCiAgICBBTkQgdGVzdF9zdGF0dXMgIT0gJ1NLSVBQRUQnCiAgICBBTkQgKHRlc3Rfc3RhdHVzIExJS0UgJ0YlJyBPUiB0ZXN0X3N0YXR1cyBMSUtFICdFJScpCiAgICBBTkQgY2hlY2tfc3RhdHVzICE9ICdzdWNjZXNzJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIExJS0UgJ2xpYkZ1enplciUnCiAgICBBTkQgY2hlY2tfbmFtZSAhPSAnQ2xpY2tIb3VzZSBLZWVwZXIgSmVwc2VuJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIElMSUtFICclZXhwZXJpbWVudGFsJScKICAgIEFORCBwb3NpdGlvbih0ZXN0X25hbWUsICdTZXJ2ZXIgZGllZCcpID4gMApPUkRFUiBCWSBjaGVja19zdGFydF90aW1lRelated: #108728
Related: #97411
Related: #108726
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes an unreleased regression from #108728 (master only); no stable release is affected.
Documentation entry for user-facing changes
🤖 Generated with Claude Code
Version info
26.8.1.168(included in26.8and later)