Skip to content

Fix a crash when a read of a serialized query plan lands on a Merge table through a proxy table - #119387

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-merge-behind-proxy-serialized-plan
Oct 1, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:fix-merge-behind-proxy-serialized-plan

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed a server crash when a SELECT with serialize_query_plan = 1 read a Merge table through a table that forwards its reads, such as Alias, Buffer with a destination, or a MATERIALIZED VIEW with a TO target. Closes #119899.

Description

CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t VALUES (1), (2);
CREATE TABLE m ENGINE = Merge(currentDatabase(), '^t$');
CREATE TABLE proxy ENGINE = Alias(currentDatabase(), m);

SET serialize_query_plan = 1;
SELECT sum(x) FROM remote('127.0.0.2', currentDatabase(), proxy);   -- expected 3, crashed the server

With serialize_query_plan = 1 the receiving side rebuilds each read from a step carrying only a table
name, so its SelectQueryInfo has no query. Reads needing one get a SELECT over the table synthesized
and re-analyzed; the rest read the storage directly.

That route was chosen by typeid_cast<const StorageMerge *>, an exact test on the storage addressed
rather than the one the read lands on. A table forwarding its read took the direct route, so when it
forwards to a Merge table, StorageMerge::read got a null query and dereferenced it at
StorageMerge.cpp:1116. With parallel_replicas_plan_based and parallel_replicas_allow_merge_tables
on, the same null is dereferenced earlier in the FINAL probe (StorageMerge.cpp:1049), so guarding
the reported line would only move the crash.

The fix names that precondition once, as IStorage::readRequiresAnalyzedQuery(): default
isRemote(), since a remote read builds its query tree out of SelectQueryInfo; true for Merge;
delegated by each read-forwarding storage for the table its read lands on, as it already delegates
isRemote() on the line above. The routing condition is now that one predicate.

The new test covers the three carriers plus the parallel replicas variant and reddens without this
change; routing for a proxy over a non-Merge target is measured unchanged.

Reported on master by Stress test (amd_asan_ubsan) at bf549ba1b4fe0c3de89373f336586671d8af50b8:
runtime error: member call on null pointer of type 'DB::TypePromotion<DB::IAST>' at
src/Storages/StorageMerge.cpp:1116:57
(report).

Not addressed here: the same sparse SelectQueryInfo reaches external-database storages such as
MySQL, which report Query is not analyzed: no query tree rather than crashing. They answer false to
the new predicate, so that path is unchanged here.


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

Version info

  • Merged into: 26.10.1.1227-master (included in 26.10 and later)

On the receiving side of a serialized query plan, replaceReadingFromTable
rebuilds a read from a step that carries only a table name and the table
expression modifiers, so the SelectQueryInfo it builds has no query, no query
tree and no syntax analyzer result. It then either synthesizes a SELECT over the
table and re-analyzes it, or reads the storage directly with that empty info.

The choice was `storage->isRemote() || typeid_cast<const StorageMerge *>(...)`.
The typeid_cast is an exact test on the storage that was addressed, not on the
storage the read lands on, so a storage that forwards its read took the direct
route. When it forwards to a Merge table, StorageMerge::read received an empty
SelectQueryInfo and dereferenced its null query at the sampling probe in
createChildrenPlans. getHeaderForProcessingStage does not catch this because it
only dereferences query for stages above FetchColumns, and the direct route
always passes FetchColumns.

Guarding that dereference would not have been enough: getModifiedQueryInfo needs
either a query tree or an AST plus its TreeRewriterResult, and this path supplies
neither, so the fault would reappear in createPlanForTable. With
parallel_replicas_plan_based and parallel_replicas_allow_merge_tables enabled it
appears even earlier, in InterpreterSelectQuery::isQueryWithFinal, which
dereferences query unconditionally. Both are fixed by routing correctly instead.

readsThroughMergeTable() is named for what it detects rather than for the
requirement it serves, because the same empty SelectQueryInfo also reaches
external database storages, which do not override isRemote() either. Those do not
crash: transformQueryForExternalDatabase throws UNSUPPORTED_METHOD "Query is not
analyzed: no query tree". A predicate named for requiring an analyzed query would
have been false for them.

The carrier set is closed by census: every delegating isRemote() implementation in
src/Storages belongs to one of the five classes touched here.
ReadFinalForExternalReplicaStorage forwards read too, but its nested storage is
always a ReplacingMergeTree, so it correctly inherits the false default.

The StorageMerge.h include in resolveStorages.cpp is replaced by IStorage.h,
which the file uses directly and had been getting only transitively.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 findings, 0 blocking after adjudication)

1. The route is classified from a name-based target binding that read() re-resolves. Real, and
conceded: Alias, Buffer and a MATERIALIZED VIEW ... TO all resolve their target by name
(getTargetTableId even clears the UUID for a TO target), and no lock is held on that target when the
route is chosen, so a concurrent EXCHANGE TABLES can still make the decision stale. Not introduced or
widened here: the same window governs the pre-existing isRemote() term on the same line, where a target
exchanged for a Distributed table lands the same query-less SelectQueryInfo in an unguarded
dereference at StorageDistributed.cpp:737. This change strictly shrinks the crash population, from
every such read to only one racing an EXCHANGE. Making the snapshot authoritative belongs to
replaceReadingFromTable and would have to cover isRemote() too, so I did not attempt it here. If the
code owner would rather it re-resolve or fail closed, say so and I will do that instead.

2. Two test gaps, both deliberate. StorageProxy::readsThroughMergeTable() has no arm: the only
storage that provably wraps a Merge behind it is the lazy StorageTableProxy, which exists only for a
database created with SETTINGS lazy_load_tables = 1 and only after that database is reloaded, so an arm
needs a second fixed-name database plus DETACH/ATTACH DATABASE and turns a parallel-safe test into a
no-parallel one, for one delegating line whose removal would leave that read crashing. And no shipped
oracle pins the direct route for a proxy over a non-Merge target, because a SQL-result test cannot see
the route; it is measured instead, with receiving-side system.query_log.tables (is_initial_query = 0)
empty for the direct read and non-empty for the interpreter route, unchanged for every non-Merge case,
the two crashing cases proving the probe moves when the route does. I can ship that as an arm if you want
it pinned in CI.

3. Changelog category. Left at Bug Fix (user-visible misbehavior in an official stable release),
because I do not self-assign Critical Bug Fix. It is a crash, and both the routing and the setting are
in 26.3 and 26.4, so if you want Critical Bug Fix (crash, data loss, RBAC), tell me and I will change
it.

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5330f15]

Summary: ✅


AI Review

Summary

This PR fixes the serialize_query_plan = 1 crash when a deserialized read lands on Merge through a forwarding storage by replacing the exact StorageMerge type check with a per-storage readRequiresAnalyzedQuery() predicate that is forwarded through the affected wrappers (Alias, Buffer, MaterializedView, and StorageProxy). I reviewed the current diff, the touched read paths, the prior review discussion, and the new regression tests, including the lazy TableProxy case, and I did not find any remaining correctness, concurrency, or performance issues in the patched scope.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

⚠️ No coverage measurement for commit 5330f15: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_2.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @davenger @alexey-milovidov, could you review this? With serialize_query_plan = 1 the receiving side picked the read route with an exact typeid_cast on the storage that was addressed, so a table forwarding its read (Alias, Buffer, a MATERIALIZED VIEW ... TO) pointed at a Merge table took the direct route and handed StorageMerge::read a SelectQueryInfo with no query, which it dereferences unguarded.

Comment thread src/Storages/StorageProxy.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Sep 11, 2026
The routing fix delegates readsThroughMergeTable() from five classes, but the
regression test only instantiates three of them. StorageProxy's delegation is
reached by a different carrier: in a database with lazy_load_tables = 1 an
unloaded table is a StorageTableProxy, and DatabaseOrdinary wraps a Merge table
in one just as it wraps a MergeTree. That proxy is what the catalog holds, so the
exact typeid_cast this fix replaces never matched it, and StorageTableProxy::read
forwarded the empty SelectQueryInfo straight into StorageMerge::read.

Measured with the shipped test and this one against three binaries: without the
fix both crash at the px != 0 assertion in createChildrenPlans; with it both
pass; with the fix minus the single StorageProxy line the shipped test still
passes and this one crashes with the same assertion and frames as the master CI
report. The line was therefore the one part of the change no test held.

The carrier needs a second database, which needs DETACH DATABASE / ATTACH
DATABASE of an Atomic database and hence no-replicated-database. That tag would
have removed the other arms from the DBReplicated stateless run and from the
one-in-three stress threads that pass --replicated-database, which is the lane
the original report came from, so the arm goes in a separate half instead, as
04652_nested_merge_prewhere_type_mismatch does for the same reason. The second
database is {CLICKHOUSE_DATABASE_1}, unique per run, so the test stays parallel.

Only the engine column of system.tables is read before the query: it is answered
by the proxy itself, while a column such as data_paths would materialize the
nested storage and leave the fixture testing a plain Merge table.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5330f158f with master 1ed3fcc2c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a0b65176b; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

1283 translation units recompiled, 8402 s compile time in total, 1283 of them have a recent master baseline.

Job report

Comment thread src/Storages/IStorage.h Resolved
`resolveStorages.cpp` routes a serialized-plan table read through
`InterpreterSelectQueryAnalyzer` when the storage cannot read from a
`SelectQueryInfo` that carries no query. That condition was spelled twice: once
as `isRemote()`, once as a predicate naming `Merge`. Both terms ask the same
question, whether `read` requires an analyzed query, so express that property
once and let the base class stop naming one storage engine.

`IStorage::readRequiresAnalyzedQuery()` defaults to `isRemote()`, which is why
remote storages were in the condition in the first place:
`StorageDistributed::read` builds its query tree out of `SelectQueryInfo` in
`buildQueryTreeDistributed`. `StorageMerge` overrides it to true, and the four
read-forwarding wrappers delegate it exactly as they already delegate
`isRemote()`. The call site now reads one term.

The routed set is unchanged. Measured on 12 read shapes through a serialized
plan (plain `MergeTree`; `Merge`; `Alias`, `Buffer` and `MaterializedView` over
`Merge`; `Alias` and `Buffer` over `MergeTree`; `Distributed`; `Alias` and
`Buffer` over `Distributed`; and the two non-`Merge` shapes under
`parallel_replicas_plan_based`): the receiving-side route recorded in
`system.query_log.tables` is identical before and after. Changing the default
from `isRemote()` to false segfaults the `Distributed` read in
`buildQueryTreeDistributed`, so that default is load-bearing rather than
incidental.

The predicate is an opt-in claim, not a census: a false answer means the storage
has not declared the requirement. External-database storages need an analyzed query
too (`transformQueryForExternalDatabase` rejects a query-less `SelectQueryInfo`) and
still answer false here, so they keep reporting an error on this path instead of
being routed. Routing them is a behaviour change for storages this PR cannot
exercise, so it stays out.
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, moving the design question here as you asked.

On 2026-09-12 you called the predicate in IStorage.h ugly. It replaced storage->isRemote() || typeid_cast<const StorageMerge *>(storage.get()) in resolveStorages.cpp. A read of a deserialized plan arrives with no query, no query tree and no syntax analyzer result, and StorageMerge::read dereferences all three, one of them the sampleSize() check in the stack you posted today, so guarding a single site only moves the crash and the route has to be chosen before read is called.

The pushed shape is IStorage::readRequiresAnalyzedQuery(), default isRemote(), true for Merge, forwarded by Alias, Buffer, MaterializedView and StorageProxy; the routing site reads one term and no longer names an engine. Routing is identical before and after on 12 read shapes through a serialized plan, read off the receiving side's system.query_log.tables.

The alternative is no predicate at all: always synthesize the SELECT and re-analyze here, which deletes both conditions and the isRemote() term with them, and costs one analysis per table read. resolveStorages runs only when a serialized plan is received, and serialize_query_plan and parallel_replicas_plan_based are both off by default, so that cost stays inside those two settings.

Reusing the existing readsFromOtherTables() rather than adding a virtual does not work: StorageMaterializedView does not override it, so a MATERIALIZED VIEW ... TO a Merge table would still crash, and StorageAlias returns it unconditionally, which would route Alias over a plain MergeTree through the interpreter.

Nothing is blocked on the answer, the PR stands on the pushed shape. If you would rather have no predicate, say so and I will measure what the extra analysis costs a plain MergeTree read and push that instead.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1311df6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, 4/8) / all 18 of test_storage_nats/test_nats_core.py not PR-caused: whole-module wipe, 18 of 18 leaves carrying Code: 210 ... No route to host (172.16.2.7:9000), i.e. the test server's container is gone and every later test dies in nats_setup_teardown. This diff touches only StorageMerge and the deserialized-plan path, no NATS file. 21-day breadth for the module: 9 unrelated pull requests plus one master run. Merged #120202 bumped contrib/nats-io to b88704df, that pin IS on this head, and the wipe still fires here and on two other runs after it landed, so it is not the owner a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Finish Workflow / Post Hooks cascade of the row above: both Bugfix validation (functional tests, *) jobs were DROPPED because of it, so no per-arch validation job could report OK a fix task is moved to pending (the same one, since this row clears as soon as that shard is green)

176 checks, all completed: 52 success, 120 skipped (praktika dropped them after the failing shard),
2 failing jobs plus the Mergeable Check and PR rollups. CIDB holds 122,624 rows across 54 checks
at this commit; the 19 FAIL rows are the 18 plus the post hook above.

Session id: cron:our-pr-ci-monitor:20260922-230208

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1311df6: fixing-PR link for the NATS row

The Integration tests (amd_asan_ubsan, db disk, 4/8) row (all 18 test_storage_nats/test_nats_core.py cases) now has its fixing PR: ClickHouse/nats.c#11

The container death is a heap-use-after-free in the vendored client. natsConnection_ProcessReadEvent drops the connection's last reference in its own trailing release while the libuv poll handle is still armed, so a later poll event reads freed memory at conn.c:4105. The fix backports upstream b89b44d07 (resolves nats-io/nats.c#888) and 655c8ea54 onto ClickHouse/v3.9.2: the library retains the connection for the duration of an event loop attachment, and an adapter releases it when it can no longer dereference it. It has to land in the submodule's own repository first, so a contrib/nats-io pin bump follows once that PR is merged.

The Finish Workflow / Post Hooks row clears with the same fix.

Session id: cron:clickhouse-publish-slot-34:20260923-075700

@alexey-milovidov alexey-milovidov self-assigned this Oct 1, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit f13c52d Oct 1, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 2, 2026
…alized-query-plan-112891

Conflict in src/Processors/QueryPlan/resolveStorages.cpp with ClickHouse#119387, which
routes a serialized-plan read through the interpreter when
IStorage::readRequiresAnalyzedQuery() holds (remote, Merge, and the wrappers
that forward to them) instead of testing isRemote() and an exact StorageMerge.

Both sides are kept: the row-policy replan is computed only for a read that
does not already go through the interpreter, and the interpreter route is
taken for read_via_interpreter || needs_row_policy. A wrapper over Merge was a
direct read before ClickHouse#119387, so needs_row_policy could select it; it is now on
the interpreter route with default options, which resolve its policy like the
Merge route always did.

Master's new checkAccessRightsForColumnsResolvedAway sits under the same
ignore_table_access_check guard. It checks only PREWHERE and indexHint
columns, which the synthesized SELECT of a replanned read does not have.

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

Copy link
Copy Markdown
Collaborator Author

The fix is not on 26.9, and its CI hit this crash today: Stress test (arm_tsan) on 26.9 at fbcab86b, Segmentation fault (STID: 3132-38cf), sampleSize() on the null query_info.query at StorageMerge.cpp:1122 (report). Master has had no such row since this merged.

26.3, 26.7, 26.8 and 26.9 all still pick the read route with typeid_cast<const StorageMerge *> in resolveStorages.cpp; 26.10 has the fix. A 3-way merge of this diff onto each branch conflicts only on adjacent lines (one in StorageProxy.h on 26.7 to 26.9, four headers on 26.3), and every symbol it calls exists on all four. On 26.3 the test would also need SET allow_experimental_alias_table_engine = 1.

Could this get v26.7-must-backport (26.7, 26.8, 26.9), or v26.3-must-backport to include 26.3 as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-bugfix Pull request with bugfix, not backported by default 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.

UBSan: null query_info.query dereferenced in ReadFromMerge::createChildrenPlans when checking SAMPLE (STID: 3593-560a)

3 participants