Skip to content

Fix: possible race condition on EXCHANGE TABLES query with sharded cache - #97411

Merged
scanhex12 merged 5 commits into
ClickHouse:masterfrom
scanhex12:sharded_cache_db
Feb 20, 2026
Merged

scanhex12 merged 5 commits into
ClickHouse:masterfrom
scanhex12:sharded_cache_db

Conversation

@scanhex12

@scanhex12 scanhex12 commented Feb 19, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Continue of #61135, but with sharded cache

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.2.1.986
  • Backported to: 26.1.4.25, 25.12.7.20

@clickhouse-gh

clickhouse-gh Bot commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c4618f7]

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Feb 19, 2026
@serxa serxa self-assigned this Feb 19, 2026
@serxa
serxa requested a review from Copilot February 19, 2026 17:50

Copilot AI left a comment

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.

Pull request overview

This PR extends the earlier EXCHANGE TABLES race-condition fix to work with a sharded, per-query storage cache by caching resolved table UUIDs in the query context, and adds a stateless test to reproduce the concurrent SELECT/EXCHANGE TABLES scenario.

Changes:

  • Add a sharded per-query storage UUID cache in Context and use it from DatabaseCatalog table lookup paths.
  • Introduce Context::getOrCacheStorage() helper to resolve and cache StorageID→UUID mappings.
  • Add a new stateless shell test covering concurrent SELECT and EXCHANGE TABLES.

Reviewed changes

Copilot reviewed 4 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/queries/0_stateless/03915_exchange_tables_race.sh New concurrent test for SELECT vs EXCHANGE TABLES race symptom (LOGICAL_ERROR).
tests/queries/0_stateless/03915_exchange_tables_race.reference Empty expected output for the new shell test.
src/Interpreters/DatabaseCatalog.cpp Route table resolution through the query-context cache when available.
src/Interpreters/Context.h Add sharded StorageCache to ContextData and declare getOrCacheStorage().
src/Interpreters/Context.cpp Implement Context::getOrCacheStorage() using a sharded mutex/set and UUID lookup.

Comment thread src/Interpreters/Context.h Resolved
Comment thread src/Interpreters/Context.h Resolved
if (exception && !storage.second)
exception->emplace(Exception(
ErrorCodes::UNKNOWN_TABLE,
"Table {} does not exist anymore - maybe it was dropped",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Previously, we had a better error message here that suggested other table names in getTableImpl.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Will it be triggered only if the table was dropped during execution? If yes, that's fine.

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.

Will it be triggered only if the table was dropped during execution

I think so

Comment thread src/Interpreters/Context.h Resolved
@scanhex12
scanhex12 requested a review from serxa February 19, 2026 20:28
@scanhex12 scanhex12 added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Feb 19, 2026
@koletzilla

koletzilla commented Feb 20, 2026 •

Copy link
Copy Markdown
Contributor

Hi! Do you think this would also solve #61072?

@scanhex12

Copy link
Copy Markdown
Member Author

@koletzilla Yes, this PR solve exactly this problem

robot-clickhouse added a commit that referenced this pull request Feb 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Feb 25, 2026
Backport #97411 to 26.1: Fix: possible race condition on EXCHANGE TABLES query with sharded cache
clickhouse-gh Bot added a commit that referenced this pull request Feb 25, 2026
Backport #97411 to 25.12: Fix: possible race condition on EXCHANGE TABLES query with sharded cache
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Feb 26, 2026
@yakov-olkhovskiy

Copy link
Copy Markdown
Member

@scanhex12 @serxa ppl ask this fix to be backported to 25.10 - can we safely do it?

serxa added a commit that referenced this pull request Mar 13, 2026
`& (NumShards - 1)` is only a correct modulo when `NumShards` is a power
of two. With `NumShards == 6`, the bitmask is `5 == 0b101`, so only bits
0 and 2 can be set in the result. The possible shard indices are
0, 1, 4, 5 — shards 2 and 3 are never selected, making 2 out of 6
shards permanently empty and concentrating all load onto the other four.

Fix by using `% NumShards` instead.

Follow-up to #97411.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
alexey-milovidov added a commit that referenced this pull request May 16, 2026
…e_tables_race.sh

The C++ fix in `Context.cpp` / `Context.h` / `DatabaseCatalog.cpp` was reimplemented
with a sharded cache and merged into master via #97411
(#97411). The accompanying test was
committed under the new name `03915_exchange_tables_race.sh`, so the original
`03007_exchange_tables_race.sh` would be a duplicate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Jul 26, 2026
The per-query storage cache `Context::getOrCacheStorage` (added in ClickHouse#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. ClickHouse#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 ClickHouse#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-ClickHouse#108728 behavior). To keep ClickHouse#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 ClickHouse#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: ClickHouse#97411
Related: ClickHouse#108728
Related: ClickHouse#108726

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
niyue pushed a commit to niyue/ClickHouse that referenced this pull request Aug 21, 2026
When a concurrent EXCHANGE TABLES swaps a table with a different column
type between query analysis and header computation, partial evaluation in
ActionsDAG::updateHeader can hand a function an argument column whose type
no longer matches the type the function was resolved for. Executing the
function then trips an internal LOGICAL_ERROR (e.g. in
FunctionBinaryArithmetic::executeImpl2), which aborts the server in
debug/sanitizer builds.

Detect the argument type mismatch in executeActionForPartialResult before
executing the function and raise a recoverable TYPE_MISMATCH instead. The
normal execution path already throws ILLEGAL_TYPE_OF_ARGUMENT for the same
query, so legitimate queries are unaffected.

This is the abort targeted by the existing regression test
03915_exchange_tables_race.sh (added in ClickHouse#97411).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The per-query storage cache `Context::getOrCacheStorage` (added in ClickHouse#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. ClickHouse#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 ClickHouse#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-ClickHouse#108728 behavior). To keep ClickHouse#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 ClickHouse#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: ClickHouse#97411
Related: ClickHouse#108728
Related: ClickHouse#108726

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

The C++ fix in `Context.cpp` / `Context.h` / `DatabaseCatalog.cpp` was reimplemented
with a sharded cache and merged into master via ClickHouse#97411
(ClickHouse#97411). The accompanying test was
committed under the new name `03915_exchange_tables_race.sh`, so the original
`03007_exchange_tables_race.sh` would be a duplicate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v25.12-must-backport v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants