Skip to content

Fix NOT_FOUND_COLUMN_IN_BLOCK for an IN over a parameterized view in a distributed query - #123662

Merged
PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/parameterized-view-in-set-on-shard
Oct 10, 2026
Merged

PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/parameterized-view-in-set-on-shard

Conversation

@groeneai

@groeneai groeneai commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113550

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 NOT_FOUND_COLUMN_IN_BLOCK (or THERE_IS_NO_COLUMN) when a query sent to other servers (a Distributed table, remote, parallel replicas) has an IN over a parameterized view called without its database name inside an expression the servers return, for example countIf(x IN (SELECT y FROM pv(p = 1))), a GROUP BY key or a SELECT item. Also fixed NOT_AN_AGGREGATE when one query spells the same parameterized view call both with and without its database name.

Description

On 26.8.2.7 and 26.9.7.6:

CREATE TABLE t (x UInt64) ENGINE = Memory; INSERT INTO t VALUES (2);
CREATE VIEW pv AS SELECT x FROM t WHERE x >= {p:UInt64};
SELECT countIf(number IN (SELECT x FROM pv(p = 0))) FROM remote('127.0.0.{2,3}', numbers(4));
-- NOT_FOUND_COLUMN_IN_BLOCK: Not found column countIf(in(__table3.number, __set_...)) in block.
-- There are only columns: countIf(in(__table3.number, __set_...)); expected 2, as `default.pv(p = 0)` gives

An IN set is named after the tree hash of its subquery, and the shards return that name inside the column. TableFunctionNode hashed the call as typed (pv), while #113550 sends it to the shards qualified (default.pv(...)), so the shards hash a different name and the initiator does not find the column. WHERE IN, GLOBAL IN and a single shard are not affected.

TableFunctionNode::updateTreeHashImpl now hashes a resolved parameterized view by the name toASTImpl sends (one shared predicate: qualified unless the database name contains a dot), as TableNode hashes its storage. For a call typed qualified the hash bytes are unchanged, so a fixed initiator works with 26.9 and unfixed master shards and a 26.9 initiator behaves as before (measured, also with a dotted default_database; 26.8 names every IN set differently from 26.9+ anyway). isEqualImpl now compares two parameterized views by storage too (still comparing FINAL and SETTINGS), so SELECT x IN (SELECT y FROM pv(p = 0)) ... GROUP BY x IN (SELECT y FROM db.pv(p = 0)) no longer fails with NOT_AN_AGGREGATE. EXPLAIN QUERY TREE and EXPLAIN SYNTAX are unchanged, and tests/performance/parameterized_view_analysis.xml takes the same time.

05320 covers countIf, NOT IN, a GROUP BY key, a SELECT item, remote, serialize_query_plan = 1, two calls with different arguments and parallel replicas; 05339 covers both spellings in one query; each fails on master. Also measured: a lambda, a CTE, a UNION, a non-default database.


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

Version info

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

groeneai and others added 3 commits October 3, 2026 06:15
…ch on shards

An `IN` set is named `__set_<tree hash of its subquery>`, and that name is
part of every column a shard returns whose expression contains the `IN`
(an aggregate argument, a `GROUP BY` key, a `SELECT` item); the initiator
matches those columns by name. `TableFunctionNode::updateTreeHashImpl`
hashed a parameterized view call as typed (`pv`), while `toASTImpl` sends
it qualified (`default.pv(...)`, ClickHouse#113550), so each shard hashed a different
name and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`, or
`THERE_IS_NO_COLUMN` with `serialize_query_plan = 1`.

A resolved parameterized view is now hashed by
`storage_id.getFullNameNotQuoted()`, the way `TableNode` hashes its
storage. For a call typed qualified the hash bytes are unchanged, so a
fixed initiator works with 26.9 and unfixed master shards and a 26.9
initiator behaves as before. Hashing only the storage id (without the
name bytes) also fixes a single-version cluster, but breaks the qualified
spelling against 26.9 and unfixed master shards in both directions
(measured), so the name bytes are kept.

`isEqualImpl`, `toASTImpl` and `dumpTreeImpl` are unchanged, so
`EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX` output does not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The runner draws `automatic_parallel_replicas_mode = 2` in a quarter of the
runs, and then the analyzer turns `enable_parallel_replicas` off for the query,
so the arm read `data` locally and printed the expected row on master too.
`enable_parallel_replicas = 1` also falls back to a local read silently.

Pin `automatic_parallel_replicas_mode = 0`, use `enable_parallel_replicas = 2`
so an unsupported shape throws, and check in `system.query_log` that the query
reached the parallel-replicas coordinator
(`ParallelReplicasHandleAnnouncementMicroseconds`, as in 04907).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the tree-hash comment in TableFunctionNode::updateTreeHashImpl to one invariant line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 3, 2026
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review
  • ⚠️ test-liveness (Gate B r1): the parallel-replicas arm could run without parallel replicas when the runner draws automatic_parallel_replicas_mode = 2. AGREE, fixed: the arm pins mode 0 and enable_parallel_replicas = 2, and the test checks ParallelReplicasHandleAnnouncementMicroseconds in system.query_log (with mode 2 the probe prints 0). Gate B r2: no findings.
  • 💡 a call in a database whose name contains a dot is hashed qualified although it is sent unqualified; only matters if a shard's default database is that same database during a rolling upgrade. Noted, not changed.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT countIf(number IN (SELECT x FROM pv(p = 0))) FROM remote('127.0.0.{2,3}', numbers(4)) fails every time with NOT_FOUND_COLUMN_IN_BLOCK on master, 26.8.2.7 and 26.9.7.6.
b Root cause explained? Yes. An IN set is named after the tree hash of its subquery and the shards return that name in the column. The parameterized view call was hashed as typed (pv) but sent qualified (default.pv), so the shards named the set differently.
c Fix matches root cause? Yes. The node whose hash disagreed now hashes the qualified name; no guard at the column-matching site, no setting.
d Test intent preserved / new tests added? New test 05320_parameterized_view_in_set_on_shard, 8 arms, each fails on master. The parallel-replicas arm pins automatic_parallel_replicas_mode = 0 and checks in system.query_log that parallel replicas engaged. No existing test changed.
e Both directions demonstrated? Yes, on Build-ID-checked binaries: the test fails on master (Code 10, Code 8 with the distributed plan settings) and passes with the fix, 50/50 with randomized settings, 20/20 with serialize_query_plan = 1.
f Fix is general across code paths? Yes. TableNode already hashes its storage; other table functions and unresolved nodes hash as before; GLOBAL IN and scalar subqueries name their sets on the initiator. All parameterized-view tests pass.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured: aggregate argument, SELECT item, GROUP BY, ORDER BY, NOT IN, tuple IN, nested subquery, CTE, JOIN inside the subquery, view over the view, remote, Distributed, parallel replicas, serialize_query_plan, non-default database, two calls with different arguments. Type wrappers N/A.
h Backward compatible? (maintainer-approved exception only) Yes. No setting; nothing persisted uses the hash; the qualified call hashes as before, so a fixed initiator works with 26.9 and unfixed master shards and a 26.9 initiator behaves as before (measured).
i Invariants and contracts preserved? Yes. Equality is unchanged, so equal nodes still hash alike; unresolved nodes keep the typed name; EXPLAIN QUERY TREE and EXPLAIN SYNTAX output is unchanged.

Session id: cron:clickhouse-impl-self-slot-57:20261003-070500

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [236e48f]

Summary: ✅


AI Review

Summary

This PR correctly targets the tree-hash mismatch behind NOT_FOUND_COLUMN_IN_BLOCK / THERE_IS_NO_COLUMN for distributed IN over parameterized views, and it also tightens TableFunctionNode::isEqualImpl so pv(...) and db.pv(...) can match as one logical table expression. But two of the new regression tests still do not force the analyzer path they are supposed to cover, and the hash/equality contract is still broken for parameterized views in dotted databases, so I do not think the change is ready to merge yet.

Findings

❌ Blockers

  • [src/Analyzer/TableFunctionNode.cpp:129, src/Analyzer/TableFunctionNode.cpp:148] TableFunctionNode::isEqualImpl now treats two resolved parameterized views with the same storage_id as equal regardless of spelling, but TableFunctionNode::updateTreeHashImpl still canonicalizes only the non-dotted case. For a dotted database, pv(p = 0) hashes as pv + a.b.pv, while the qualified spelling hashes as a.b.pv + a.b.pv, even though isEqual says they are the same node. Anything keyed by tree hash (__set_... names, cached analysis keyed by structural identity, etc.) can still split one logical expression into two and reproduce exactly the kind of IN / GROUP BY divergence this PR is fixing. Suggested fix: hash resolved parameterized views by the same storage-based canonical spelling that equality uses, and keep isSentQualified only for choosing the wire form in toASTImpl.

⚠️ Majors

  • [tests/queries/0_stateless/05320_parameterized_view_in_set_on_shard.sql:1, tests/queries/0_stateless/05339_parameterized_view_spelled_two_ways.sh:10] Both new regression tests exercise analyzer-only TableFunctionNode behavior, but neither one forces enable_analyzer = 1 nor opts out of the old-analyzer CI profile. The stateless suite still runs lanes where allow_experimental_analyzer = 0 by default (see tests/queries/0_stateless/04108_chunk_buffer_reader_writer_race.sql:15 and tests/queries/0_stateless/04647_no_blocks_marshalling_for_local_shard_plan.sh:14), and neighboring parameterized-view shard tests already pin the analyzer for exactly this reason (tests/queries/0_stateless/04678_parameterized_view_database_on_shard.sh:14, tests/queries/0_stateless/04907_parallel_replicas_parameterized_view_in_subquery.sql:33). As written, these two tests can go through the legacy planner and pass without ever touching the repaired code path, so they are false-green coverage. Suggested fix: pin SET enable_analyzer = 1 near the top of 05320, and either add --enable_analyzer 1 to the client in 05339 or tag it no-old-analyzer.
Final Verdict

❌ Not ready yet: one correctness hole remains in the storage-spelling hash for dotted databases, and the two new regression tests are still non-deterministic with respect to the analyzer/old-analyzer split.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 3, 2026
@@ -0,0 +1,50 @@
-- Tags: shard

-- An `IN` over a parameterized view, called unqualified, inside an expression that the shards

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.

Could you pin enable_analyzer = 1 near the top? This fix lives in TableFunctionNode, so the regression only exists on the analyzer path. The stateless runner still randomizes enable_analyzer (see tests/queries/0_stateless/05042_streaming_queries_lazy_materialization.sql:4), and sibling parameterized-view shard tests already pin it (tests/queries/0_stateless/04678_parameterized_view_database_on_shard.sh:14, tests/queries/0_stateless/04907_parallel_replicas_parameterized_view_in_subquery.sql:33). As written, a randomized run can bypass the repaired code path and still pass.

@clickhouse-gh

clickhouse-gh Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 236e48fa0 with master 727bdd7b6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0d2ade023; 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

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +14.6 s (+6%) in total before that adjustment.

Job report

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f14a9b4

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
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04227_materialized_cte_reused_with_in_subquery not from this PR: Code: 60 UNKNOWN_TABLE for _materialized_cte_ct_* when a reused MATERIALIZED CTE feeds an IN subquery on parallel replicas; the runner reproduces it 207/207 with the drawn optimize_move_to_prewhere = 0 and 0/194 without random settings #123121 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04819_dynamic_aggregate_function_state_version flaky (1/28 reruns): the initiator got Code: 432 Unknown codec family code: 0 from replica 127.0.0.2 at the first Native fetch while the replica read with ReadPoolParallelReplicas; the same shape hit 7 PRs today on this new job a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05218_timeseries_alp_codec flaky: timeSeriesSamples(ts_alp32) resolves the target as default.ts_alp32 on a parallel replica (Code: 60 UNKNOWN_TABLE); 8 PRs today on this new job #118518 (external, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database (the rerun does not use one, so it passes there): the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 35 PRs today on this new job a fix task is created (fix in progress, fixing-PR link to follow here)
Integration tests (arm_binary, distributed plan, targeted) / test_inserts_with_keeper_retries/test.py::test_ambiguous_zk_commit_kill_preserves_data flaky: it also failed on 2 other PRs and once on master in the last 30 days #123076 (mine, open)
Mergeable Check, PR rollups, red only because of the rows above #123121, #118518, #123076 and the two fix tasks above (a fix task is created for each)

None of these touches the parameterized-view hash this PR changes. All 160 checks completed and Finish Workflow is green; CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261003-130342

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 04819_dynamic_aggregate_function_state_version row of the ledger above (arm_binary, ParallelReplicas, Code: 432 Unknown codec family code: 0): #123649 (mine, open).

Correction to that row: the failing request is the fetch with output_format_native_encode_types_in_binary_format=1 (test line 102), not the first Native fetch. The job log shows the three earlier fetches succeeding, and the same holds for all 7 PRs that hit this row today on this job.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@PedroTadim PedroTadim self-assigned this Oct 8, 2026
Comment thread src/Analyzer/TableFunctionNode.cpp Resolved
PedroTadim and others added 4 commits October 8, 2026 11:40
…er servers

`isEqualImpl` still compared the name as typed, so `pv(p = 0)` and
`db.pv(p = 0)` hashed alike but were different nodes, and a query that
spells one view both ways (e.g. a `SELECT` item and its `GROUP BY` key)
failed with `NOT_AN_AGGREGATE`. A plain table already compares by storage.

The hash qualified every parameterized view, while `toASTImpl` sends a
view in a dotted database (`a.b`) unqualified. In a cluster with
`default_database` set to such a database, an upgraded initiator and an
older shard then named the `IN` set differently in both directions. Both
now use one predicate, so the hash covers exactly the name that is sent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A view stores its body with the parameterized view's name qualified, so
the inlined call already hashes like the one the shards parse and the arm
passes without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…meterized view

The predicate now runs on every tree hash of the node, and `Identifier`
splits the name into a vector of parts on each call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Analyzer/TableFunctionNode.cpp Resolved
groeneai and others added 2 commits October 8, 2026 16:50
…e storage

`TableFunctionNode::isEqualImpl` returned early on equal storages, so it
ignored `FINAL`/`SAMPLE` and per-call `SETTINGS`, which the tree hash does
include. With parameterized views now compared by storage across spellings,
`x IN (SELECT y FROM pv(p = 0) FINAL) ... GROUP BY x IN (SELECT y FROM
db.pv(p = 0))` passed the GROUP BY check and then failed in the planner with
`NOT_FOUND_COLUMN_IN_BLOCK` instead of `NOT_AN_AGGREGATE`. The same happened
on master for one spelling, e.g. `merge(...) FINAL` against `merge(...)`.

Compare the storage, then fall through to the settings and modifiers, as
`TableNode::isEqualImpl` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The serialized-plan variant fails with THERE_IS_NO_COLUMN instead of
NOT_FOUND_COLUMN_IN_BLOCK; check it outside the distributed-plan CI flavor too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const auto full_name = storage ? storage_id.getFullNameNotQuoted() : String{};

/// Hash the name `toASTImpl` sends to other servers: `IN` set names derive from this hash.
const auto & name = isSentQualified(*this) ? full_name : table_function_name;

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.

isEqualImpl now makes pv(...) and db.pv(...) the same parameterized-view node whenever they resolve to the same storage_id, but the hash here only normalizes the unqualified spelling when the database name has no dot.

That breaks the equality/hash invariant again for databases like `a.b`: pv(p = 0) and `a.b`.pv(p = 0) compare equal, but the first hashes pv + a.b.pv while the second hashes a.b.pv + a.b.pv. Anything keyed by tree hash can still split one logical expression into two and reproduce the NOT_AN_AGGREGATE / prepared-set bugs this PR is trying to close.

Can we hash parameterized views by the same storage-based canonical spelling that isEqualImpl uses, and keep isSentQualified only for choosing the wire form in toASTImpl?

# shellcheck source=../shell_config.sh
. "$CUR_DIR"/../shell_config.sh

$CLICKHOUSE_CLIENT -q "

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.

This new regression script still inherits the runner's randomized enable_analyzer, but the behavior under test lives in TableFunctionNode. In an old-analyzer / random-settings run these queries can go through the legacy planner and pass without ever touching the repaired equality/hash path, so the test becomes a false green.

Please pin --enable_analyzer=1 (or tag the file no-old-analyzer) before the first query, like the neighboring parameterized-view shard tests do.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 01ccfda

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, targeted) / test_cluster_discovery/test.py::test_cluster_discovery_startup_and_stop, ::test_cluster_discovery_no_crash_on_empty_static_cluster, ::test_cluster_discovery_macros not from this PR: node3 cannot restart, its six start attempts all fail with Code: 57 ... Mapping for table with UUID=... already exists on a leftover _tmp_replace_*.sql of an interrupted CREATE OR REPLACE on the plain_rewritable database disk; the other two tests then see 4 of 5 nodes. The same tests failed on 6 other PRs and on master in the last 5 days #123832 (mine, open)
Finish Workflow / Post Hooks consequence of the row above: Bugfix validation (functional tests, *) was dropped after that job failed, so the bug-fix check had no result to read #123832 (mine, open)
Mergeable Check, PR rollups, red only because of the rows above #123832 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

None of these touches the parameterized-view code this PR changes. The red job dropped the later jobs, so most stateless jobs did not run on this head. CIDB has no other FAIL or ERROR row on it.

Session id: cron:our-pr-ci-monitor:20261009-003008

@PedroTadim
PedroTadim enabled auto-merge October 9, 2026 15:48
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c1122e2

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
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05316_secret_arguments_declared_by_engines not from this PR: the test came with #123364, and under DatabaseReplicated its last query_log check counts the CREATE DICTIONARY row twice (0 2 instead of 0 1; the password stays hidden) #124928 (external, merged 17:58Z). This run was dispatched at 15:49Z, before that merge, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the rows above (Failed: Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2)) #124928 (external, merged)

Session id: cron:our-pr-ci-monitor:20261010-003008

@PedroTadim
PedroTadim added this pull request to the merge queue Oct 10, 2026
Merged via the queue into ClickHouse:master with commit aa47c06 Oct 10, 2026
163 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

3 participants