Skip to content

Fix read consistency for tables renamed or exchanged during a query - #110048

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix-storage-cache-exchange-read-consistency
Jul 26, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix-storage-cache-exchange-read-consistency

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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''
(query: SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1))

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).

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 ... 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 (Context::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 (RelWithDebInfo, old analyzer): 3000 SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1) racing a continuous EXCHANGE TABLES produce 0 LOGICAL_ERROR with the fix (the same harness reproduces the LOGICAL_ERROR with #108728's checks present), while 04492/04493_create_or_replace_materialized_view_populate_keeps_subscription keep passing. Regression coverage stays in the existing 03915_exchange_tables_race (external exchange) and 04492/04493 (internal exchange) tests.

CI report (Server died on master): https://play.clickhouse.com/play?user=play&run=1&tab=Query%20F#U0VMRUNUIGNoZWNrX3N0YXJ0X3RpbWUsIGNoZWNrX25hbWUsIHRlc3RfbmFtZSwgcmVwb3J0X3VybApGUk9NIGNoZWNrcwpXSEVSRSBjaGVja19zdGFydF90aW1lID49IG5vdygpIC0gSU5URVJWQUwgMjQgSE9VUgogICAgQU5EIChoZWFkX3JlZiA9ICdtYXN0ZXInIEFORCBzdGFydHNXaXRoKGhlYWRfcmVwbywgJ0NsaWNrSG91c2UvJykpCiAgICBBTkQgdGVzdF9zdGF0dXMgIT0gJ1NLSVBQRUQnCiAgICBBTkQgKHRlc3Rfc3RhdHVzIExJS0UgJ0YlJyBPUiB0ZXN0X3N0YXR1cyBMSUtFICdFJScpCiAgICBBTkQgY2hlY2tfc3RhdHVzICE9ICdzdWNjZXNzJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIExJS0UgJ2xpYkZ1enplciUnCiAgICBBTkQgY2hlY2tfbmFtZSAhPSAnQ2xpY2tIb3VzZSBLZWVwZXIgSmVwc2VuJwogICAgQU5EIGNoZWNrX25hbWUgTk9UIElMSUtFICclZXhwZXJpbWVudGFsJScKICAgIEFORCBwb3NpdGlvbih0ZXN0X25hbWUsICdTZXJ2ZXIgZGllZCcpID4gMApPUkRFUiBCWSBjaGVja19zdGFydF90aW1l

Related: #108728
Related: #97411
Related: #108726

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.8.1.168 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cfb6bd8]

Summary: ✅


AI Review

Summary

This PR restores per-query table pinning across concurrent RENAME / EXCHANGE and clears the query-local cache after the query itself renames a table, which does address the old-analyzer 03915_exchange_tables_race regression. I still cannot approve it as-is because the unconditional cache-hit reuse is broader than the query-read contract: refreshable materialized view paths still need "current table at this name" lookups during retries, and the reverted cache semantics can pin the pre-EXCHANGE target long enough to raise false TABLE_IS_DROPPED / TABLE_UUID_MISMATCH.

Findings

⚠️ Majors

  • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110048#discussion_r3561980838] [src/Interpreters/Context.cpp:1568] getOrCacheStorage now reuses any live cached UUID, but RefreshTask::getAndLockTargetTable still has retry paths that are explicitly waiting for the name to resolve to a different table. StorageMaterializedView::readImpl passes a query context into that loop (src/Storages/StorageMaterializedView.cpp:391-413), so DatabaseCatalog::getTable goes through the per-query cache (src/Interpreters/DatabaseCatalog.cpp:1245-1257). If the first lookup pins the pre-EXCHANGE target and tryLockForShare or trySyncReplica fails while that old table is shutting down (src/Storages/MaterializedView/RefreshTask.cpp:1602-1638), the next iteration sees the same cached StoragePtr, hits the "expect a different table by the same name" logic (src/Storages/MaterializedView/RefreshTask.cpp:1592-1599), and can still throw a false TABLE_IS_DROPPED / rethrow the stale sync exception even though the replacement table is already live at the name. The same unconditional pinning can also keep waitForLatestTargetTable on the old UUID until DROP completes (src/Storages/MaterializedView/RefreshTask.cpp:618-647) when the refresh context has its own query context (src/Storages/StorageInMemoryMetadata.cpp:154-160).
    Suggested fix: keep the pinning default for ordinary query reads, but add a current-name lookup / cache-bypass path and use it from RefreshTask::waitForLatestTargetTable and the retrying parts of RefreshTask::getAndLockTargetTable.
Tests
  • ⚠️ No regression test currently exercises the refreshable-MV retry path while the pre-EXCHANGE target UUID is still live under a temporary name. A focused test that forces one failed getAndLockTargetTable attempt before the old table is dropped would prove the cache-bypass path.
Final Verdict
  • Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 10, 2026
/// internal `EXCHANGE` instead of shutting down the live one (see #108726).
if (storage.second)
return storage;

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.

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.

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 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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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
  • StressHouse run: dc82f2aa-0fd9-4cae-8875-8b3ef472c619
  • MIRAI run: bdb2dfde-b1e6-4a05-ac6b-5b68dd6f99e5
  • PR check IDs:
    • clickbench_22975_1784718639
    • clickbench_22981_1784718639
    • clickbench_22992_1784718639
    • tpch_adapted_1_official_23004_1784718639
    • tpch_adapted_1_official_23022_1784718639
    • tpch_adapted_1_official_23044_1784718639

@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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@clickgapai, after this is merged, submit a PR with an additional test.

Merged via the queue into master with commit 2bf3033 Jul 26, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-storage-cache-exchange-read-consistency branch July 26, 2026 19:23
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 26, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 27, 2026
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]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 27, 2026
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]>
@clickgapai

Copy link
Copy Markdown
Contributor

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.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…e-exchange-read-consistency

Fix read consistency for tables renamed or exchanged during a query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants