Skip to content

Fix wrong value for a virtual column on the right side of direct JOIN - #113698

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-virtual-column-misbinding
Aug 7, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-direct-join-virtual-column-misbinding

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 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):

Fix a wrong value returned for a virtual column such as _table or _database selected from the right side of a JOIN served by DirectKeyValueJoin (a key-value storage such as EmbeddedRocksDB, KeeperMap, Redis, or a dictionary). The query returned the contents of a data column instead, or failed with LOGICAL_ERROR.

Description

SELECT dd.v, dd._table FROM t LEFT JOIN <key-value table> AS dd ON t.pref = dd.k returned
VALA KEYA where VALA s2 is correct: the join key column's value appeared where the table
name belongs. With a key type other than LowCardinality(String) it failed with LOGICAL_ERROR
(Bad cast ... to ColumnLowCardinality). Both occur at stock settings, since join_algorithm
defaults to direct,parallel_hash,hash.

Root cause: DirectKeyValueJoin::joinBlock builds the right-side columns in two steps that
disagree about indexing. convertBlockStructure skips any header column the storage does not
report (DirectJoin.cpp:36-37), returning a compacted column vector, and the insertion loop
re-indexes it positionally against the uncompacted header (:188-192). A
plan-materialized virtual column is exactly the skipped case, so a data column gets published
under the virtual column's name and declared type. For a dictionary getByKeys also prepends
the key columns (IDictionary.h:460-466), so the key lands in the slot reserved for _table.

The fix declines DirectKeyValueJoin in tryDirectJoin when a mapped header column is absent
from the storage's sample block, letting the existing HashJoin fallback, whose right subtree
does materialize virtual columns, answer the query. That function already carries two bail-outs
of this shape for the join key (PlannerJoins.cpp:1108-1113); this is the same rule for non-key
columns. DirectJoin.cpp is unchanged, so its positional re-index becomes unreachable here
rather than being removed.

Direct join is still chosen for every normal-column shape, and no existing test loses coverage.
Dictionaries and EmbeddedRocksDB are verified affected by measurement; KeeperMap and Redis
by construction, having an identical getSampleBlock. One deliberate behaviour change, pinned by
a test arm: with join_algorithm = 'direct' alone such a query now returns NOT_IMPLEMENTED
rather than a wrong value, as the existing bail-outs for a mixed ON condition and for
RIGHT JOIN already do.

Version info

  • Backported to: 26.7.4.8, 26.6.3.18, 26.5.7.18

`SELECT dd._table FROM t LEFT JOIN <key-value table> AS dd ON t.pref = dd.k`
returned the contents of the join key column where the table name belongs, or
failed with `LOGICAL_ERROR` `Bad cast from type DB::ColumnNullable to
DB::ColumnLowCardinality`, depending on the key type. Both happen at stock
settings, because `join_algorithm` defaults to `direct,parallel_hash,hash`.

`DirectKeyValueJoin::joinBlock` builds the right-side columns in two steps that
disagree about indexing. `convertBlockStructure` skips any header column the
storage does not report and returns a compacted column vector, then the
insertion loop re-indexes that vector positionally against the uncompacted
header. A virtual column such as `_table` or `_database` is materialized at plan
time and is therefore in the header and never in the storage sample block, so it
is exactly the skipped case and a data column ends up published under its name
and declared type. For a dictionary the misalignment is guaranteed, because
`IDictionary::getByKeys` filters out non-attributes and then prepends the key
columns, so the key occupies the slot reserved for the virtual column.

Decline `DirectKeyValueJoin` in `tryDirectJoin` when a mapped header column is
absent from the storage sample block, so the existing `HashJoin` fallback, whose
right subtree does materialize virtual columns, answers the query.
`tryDirectJoin` already declines for the join key under the same two conditions
a few lines above; this applies that rule to non-key columns. The guard is about
the storage being unable to supply the column, not about a column name, because
`_database` misbehaves identically.

`DirectJoin.cpp` is deliberately unchanged. Repairing the positional index there
would stop publishing another column's data but still leave the query
unanswerable, because the filled-join plan has no right subtree that could
materialize the unbound slot.

Direct join remains selected for every normal-column shape, and no existing test
loses coverage. With `join_algorithm = 'direct'` pinned alone, such a query now
returns `NOT_IMPLEMENTED` rather than a wrong value, which is the pre-existing
behaviour of the two bail-outs already present for a mixed `ON` condition and
for `RIGHT JOIN`.
The test creates an EmbeddedRocksDB table, so it must not run in a build without
rocksdb.  `use-rocksdb` is a required-build-flag gate, not only a replicated-database
skip: tests/clickhouse-test:3080-3083 returns FailureReason.BUILD for any `use-*` tag
absent from the build flags, which collect_build_flags fills from
`system.build_options WHERE name LIKE 'USE_%'`.  Fast test configures
-DENABLE_LIBRARIES=0 and never re-enables rocksdb, so USE_ROCKSDB is unset,
registerStorageEmbeddedRocksDB is compiled out, and an untagged test does not skip --
it runs and its first CREATE TABLE fails with UNKNOWN_STORAGE.  The same tag also
covers the two stateless `old analyzer` ParamSets, which pair `old analyzer` with
DBReplicated, where these queries are UNKNOWN_IDENTIFIER and never reach the code
under test.

Of the 35 stateless tests that create such a table, this was the only one carrying
neither `use-rocksdb` nor `no-fasttest`.

`no-fasttest` is deliberately not added: both gates sit in the same should_skip_test
and both return a FailureReason, so it would cover no job that `use-rocksdb` does not.
`no-parallel-replicas` is deliberately not added either, unlike the two sibling
direct-join tests: measured against a server configured the way `install.sh
--parallel-rep` does it, all twelve arms behave identically to the plain flavour, the
EXPLAIN arm still shows DirectKeyValueJoin being chosen, and the whole file passes.
Those siblings join a real left table, whereas every arm here has a constant subquery
on the left, which is not a parallel-replicas-eligible reading step.
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds by an independent reviewer that never edits the code, plus two automated
full-scope passes. Round 1 raised 6 findings (2 blockers, 3 majors, 1 nit) and bounced; round 2
found 0 new ones and the automated pass returned 0. Every round-1 finding is closed below, each on
a measurement rather than an argument. The source fix reviewed clean in both rounds and did not
change between them: the entire round-2 delta is one -- Tags: line on the new test.

# Finding Verdict Resolution
❌ 1 The new test creates an EmbeddedRocksDB table with no -- Tags: line. use-rocksdb is a required-build-flag gate, not only a replicated-database skip, so in a build without rocksdb the test would not skip: it would run and its first CREATE TABLE would fail with UNKNOWN_STORAGE. AGREE Tag added. Gate mechanics re-derived independently: clickhouse-test:3081-3083 maps any use_* tag absent from the build flags to FailureReason.BUILD, and collect_build_flags:5203-5209 fills those from system.build_options WHERE name LIKE 'USE_%' AND value in ('ON','1'). Of the 35 stateless tests that create such a table, 0 now lack both use-rocksdb and no-fasttest.
❌ 2 tryKeyValueJoin in the legacy analyzer (ExpressionAnalyzer.cpp:1212-1253) validates only the join key and returns a DirectKeyValueJoin for any right header, so the same defect looked reachable there with the planner-side guard bypassed. AGREE The structural reading is correct and the path is nevertheless unreachable for a right-side virtual, so a guard there would be dead code. 32 cells (4 shapes x 2 carriers x LEFT/INNER x 2 binaries) all return Code: 47 UNKNOWN_IDENTIFIER, identical before and after the fix. The rejecting step is not the join selector at all: ActionsDAG::project throws at ActionsDAG.cpp:1804-1805, reached from appendProjectResult (ExpressionAnalyzer.cpp:1890), so the legacy analyzer never admits a right-side virtual into the joined column set. Bounded as a property of that analyzer rather than of DirectKeyValueJoin: the rejection is identical for all six join algorithms including hash, and identical with a plain MergeTree right side. Two positive controls make those zeros a real absence: the virtual reads correctly straight off the storage at enable_analyzer = 0, and the legacy direct-join path is confirmed taken for this fixture (Using direct join logged once for the plain shape, zero times for the virtual one). ExpressionAnalyzer.cpp is unchanged.
⚠️ 3 Independent second axis: the two stateless old analyzer job parameter sets would run these queries where they are Code: 47 and never reach the code under test. AGREE Covered by the same tag, verified through the mechanism rather than the tag name. Of 91 parameter sets, exactly 3 contain old analyzer; one is an integration set and never runs stateless tests, and both stateless ones also carry DBReplicated, which becomes --replicated-database and skips any use-rocksdb test at clickhouse-test:2977-2979. --analyzer has exactly one consumer, so there is no other stateless route with the analyzer off.
⚠️ 4 Both sibling direct-join tests carry no-parallel-replicas with the reason written into the file; this test has two arms sensitive in opposite directions. AGREE, tag declined on measurement Requested as a measurement, not an assumed tag. On a server configured the way install.sh --parallel-rep does it, all twelve arms are byte-identical to the plain flavour, the EXPLAIN arm still shows DirectKeyValueJoin being chosen (so the correctness arms still witness the fix rather than measuring the hash fallback), and the whole file passes. Four configuration oracles fire plus an engagement control showing a ParallelReplicas node in a real plan. The sibling difference is explained rather than copied: those tests join a real left table, whereas every arm here has a constant subquery on the left, which is not a parallel-replicas-eligible reading step. An unjustified skip tag would only remove coverage.
⚠️ 5 A legacy-analyzer regression arm was requested, conditional on finding 2's measurement. AGREE, arm deliberately not added In the measured (unreachable) branch such an arm could only assert Code: 47, which passes identically on unfixed code, so it would be a control masquerading as a witness.
💡 6 The regression slice omitted the one existing test that joins a rocksdb table and requests a subcolumn, leaving that axis unmeasured. AGREE Closed on source and then measured anyway. getSampleBlock() carries no subcolumns (that is the separate getSampleBlockWithSubcolumns), so a requested subcolumn is absent from the storage sample block exactly like a virtual and the guard declines to HashJoin, never a wrong value. Both subcolumn tests A/B clean on base and fix, and the check is non-vacuous: the LEFT JOIN shape does reach DirectKeyValueJoin and returns the correct value, surviving because the subcolumn is computed above the join while the right header carries the physical column.

Also examined and found sound, independently of the fix plan: the guard's placement inside the
per-column loop is side-effect-free, since the loop's only writes are two function-local blocks;
using the mapped storage name rather than the header name is required, because right-header names
are unique execution names such as t2.id_0; the carrier set was re-enumerated from scratch and
matched, including the negative that DirectJoinMergeTreeEntity is unaffected because its sample
block is a plan header that does carry materialized virtuals, which is what shows this is not
"direct join is broken"; and all eight file:line citations in this pull request's description
resolve identically against both master and this branch.

One finding was opened by the reviewer and then withdrawn by the reviewer: an apparent
discrepancy in a commit message count turned out to be a broken probe on the reviewer's side (a
case-sensitive grep missing seven tests that spell the engine Engine=EmbeddedRocksDB), not a
false claim.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A 3-line fixture plus one plain SELECT, no settings and no fuzzer: CREATE TABLE s2 (k LowCardinality(String), v String) ENGINE = EmbeddedRocksDB PRIMARY KEY k then SELECT dd.v, dd._table FROM (SELECT CAST('KEYA','LowCardinality(String)') AS pref) AS t LEFT JOIN s2 AS dd ON t.pref = dd.k returns VALA KEYA on every run of the pristine binary. With a String or Nullable(UInt64) key the same query gives LOGICAL_ERROR instead.
b Root cause explained? Yes. convertBlockStructure skips any header column the storage does not report (DirectJoin.cpp:36-37), returning a compacted column vector; the insertion loop re-indexes it positionally against the uncompacted header (:188-192). A plan-materialized virtual column is exactly the skipped case, so a data column is published under the virtual column's name and declared type. Measured directly: dumpColumnStructure(dd._table) reports declared LowCardinality(String) with an actual Nullable(UInt64), which is the dictionary key column.
c Fix matches root cause? Yes, at the decision layer. tryDirectJoin decides whether the direct lookup can answer the query and already carries two bail-outs of this exact shape for the join key (PlannerJoins.cpp:1108-1113); the new conjunct is that rule applied to non-key columns, three lines away. Guarding the typeid_cast in FunctionsConversion.cpp or adding a check to ActionsDAG::updateHeader was rejected: both are symptom sites, and neither can fix the silent wrong results, which never reach a cast.
d Test intent preserved / new tests added? New test only, no existing test touched: 04816_direct_join_virtual_column.{sql,reference}, tagged use-rocksdb with 8 correctness arms, 1 negative control, 1 serverError NOT_IMPLEMENTED arm and an EXPLAIN pair. Each correctness arm is paired with the same query under join_algorithm = 'hash' as its oracle.
e Both directions demonstrated? Yes, through the test runner with a per-arm server restart and the server's buildId() asserted equal to readelf -n each time. Pristine binary 4164ff0e35091cf1a1cf92dedc3b320c6236b7fe: [ FAIL ], printing VALA KEYA and then losing the connection when the dictionary arm aborts. Fixed binary cc2aa0d83f71e853e1aed0f616d8e4ea2c702c13: [ OK ]. 50 runs with randomization and 50 without, all passing.
f Fix is general across code paths? Yes. The guard sits in the shared planner decision, not per storage: all five IKeyValueEntity implementations were enumerated, the three affected ones are covered by one conjunct, and DirectJoinMergeTreeEntity was measured correct before and after. LEFT, INNER, ANY LEFT and SEMI LEFT all reproduce and are all fixed, so nothing is scoped to one join kind. The legacy selector in ExpressionAnalyzer.cpp is deliberately untouched, because the legacy analyzer never binds a right-side virtual at all: measured over 4 shapes x 2 carriers (EmbeddedRocksDB and dictionary) x LEFT/INNER x both binaries = 32 cells, every one UNKNOWN_IDENTIFIER. The rejection is also join-algorithm-independent (all six algorithms including hash) and storage-independent (a plain MergeTree right side behaves the same, and is correct with enable_analyzer = 1), so it is a property of that analyzer rather than of DirectKeyValueJoin, and a guard there would be dead code. Positive controls: SELECT v, _table FROM s2 SETTINGS enable_analyzer = 0 returns the correct value, and the legacy direct-join path is confirmed taken for this fixture (Using direct join logged once for the plain shape, zero times for the virtual one).
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Key types measured: LowCardinality(String), String, a Nullable(String) left key, Nullable(UInt64) and UInt64. Both _table and _database reproduce and are both fixed, so the guard keys on "the storage cannot supply this column" rather than on a column name. Dictionaries with 1 and with 4 attributes, and an empty result via ANTI LEFT, all behave correctly.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is required, and no serialization format changes. The one behaviour change is that join_algorithm = 'direct' pinned alone now returns NOT_IMPLEMENTED instead of a wrong value. That is the pre-existing contract of pinning a single algorithm, measured identical for the existing bail-outs on a mixed ON condition and on RIGHT JOIN, and it is pinned by its own test arm.
i Invariants and contracts preserved? Yes. The invariant restored is that a column published under a header name carries a column of that header's declared type. The return {} is inside the :1139-1148 loop, whose only writes are to two function-local blocks declared at :1135 and :1137, so an early return discards only locals. DirectJoin.cpp is unchanged: the positional re-index still exists but is unreachable for this class, since the planner no longer builds a DirectKeyValueJoin for a header the storage cannot fill.

Session id: cron:clickhouse-review-slot-53:20260806-160300

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @nickitat, could you review this? DirectKeyValueJoin::joinBlock builds the right-side columns in two steps that disagree about indexing: convertBlockStructure skips any header column the storage cannot supply and returns a compacted vector, then the insertion loop re-indexes it positionally against the uncompacted header, so a plan-materialized virtual column such as _table gets another column's data published under its name and declared type. The fix declines the direct algorithm in tryDirectJoin for that case so the existing HashJoin fallback answers the query.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

This one looks worth backporting: the wrong value is returned at stock settings, since
join_algorithm defaults to direct,parallel_hash,hash, and I measured the same rc=0 wrong value
on the official stable release 26.7.3.19. The commit that armed the misbinding is 52a7925e20ce729,
which 26.7, 26.6 and 26.5 contain (behind_by = 0 against each) while 26.3 and 25.8 do not, so the
affected set is those three.

@PedroTadim, could you add v26.7-must-backport, v26.6-must-backport and
v26.5-must-backport if you agree? I do not have permission to set labels, and I am deliberately
not opening release-branch pull requests for it.

@PedroTadim

Copy link
Copy Markdown
Member

cc @vdimir easy to review

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12e926f]

Summary: ✅


AI Review

Summary

This PR teaches tryDirectJoin to decline DirectKeyValueJoin whenever the right-side header contains a column the key-value storage cannot actually return, so queries that project right-side virtual columns now fall back to HashJoin instead of publishing another column's data under the virtual column name. I did not find a remaining correctness gap in the reachable planner path, and the new stateless coverage exercises both RocksDB and dictionary reproductions along with the join_algorithm = 'direct' failure mode.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.90% 86.50% +5.60%
Functions 91.30% 91.90% +0.60%
Branches 72.90% 78.80% +5.90%

Changed lines: Changed C/C++ lines covered: 6/7 (85.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 12e926f35 with master a96691076 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 16bd8e494; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 689.52 MiB 687.14 MiB -2.38 MiB (-0.34%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@vdimir vdimir self-assigned this Aug 7, 2026
@PedroTadim
PedroTadim enabled auto-merge August 7, 2026 10:52
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 54981e6 Aug 7, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 7, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 7, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 7, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 7, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 7, 2026
Backport #113698 to 26.7: Fix wrong value for a virtual column on the right side of direct JOIN
PedroTadim added a commit that referenced this pull request Aug 7, 2026
Backport #113698 to 26.5: Fix wrong value for a virtual column on the right side of direct JOIN
PedroTadim added a commit that referenced this pull request Aug 7, 2026
Backport #113698 to 26.6: Fix wrong value for a virtual column on the right side of direct JOIN
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
VighneshPath pushed a commit to VighneshPath/ClickHouse that referenced this pull request Sep 16, 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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.5-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants