Skip to content

Fix logical error in ASOF JOIN when the right ASOF key is lazily replicated - #121385

Merged
harikrishnan94 merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-asof-join-nullable-key-lazy-replication
Oct 19, 2026
Merged

harikrishnan94 merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-asof-join-nullable-key-lazy-replication

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #89997

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 logical error (Bad cast from type DB::ColumnReplicated to DB::ColumnNullable) in an ASOF JOIN whose right side has a Nullable ASOF key produced through lazy column replication, for example by arrayJoin or a nested JOIN. enable_lazy_columns_replication is on by default, and on a release build the cast was unchecked, so the NULL filter on the ASOF key could keep or drop the wrong rows.

Description

On released 26.8, an ASOF LEFT JOIN on a Nullable(DateTime) key whose right-side key goes through arrayJoin fails the Bad cast from type DB::ColumnReplicated to DB::ColumnNullable assertion, which terminates the server process on a debug or sanitizer build; a release build makes the cast unchecked and reads the null map out of a ColumnReplicated, so the filter can keep or drop the wrong rows. CI report.

Root cause. HashJoin deliberately supports the lazy replication wrapper on the right side: materializeColumnsFromRightBlock peels it, promotes the nested column to Nullable, and re-wraps it. isLazyReplicationUseful is true for every Nullable column, since ColumnNullable::isFixedAndContiguous() is false. But the ASOF-key NULL filter in addBlockToJoin guards on the column type, peels only ColumnConst, and then asserts it is a ColumnNullable. The filter predates ColumnReplicated.

Fix. Build the prepared key columns before the ASOF-key NULL filter and read the null map from the prepared ASOF key with the original assert_cast. The existing all_key_columns loop already strips the wrapper with removeSpecialRepresentations, and it reads the whole block, so moving it above the filter does not change which rows are stored.

Validation. New test for hash and parallel_hash; its oracle is row equality against the enable_lazy_columns_replication = 0 arm, not the absence of an error. It passes 10/10 fixed; reading the null map from the unprepared key again aborts 10/10 with the reported message, on the = 1 arms only. grace_hash cannot reach the site: it materializes at its entry point and rejects ASOF.

correctNullabilityInplace is left alone: a wrapped column makes its checkAndGetColumn probe miss rather than abort, and removeColumnNullability then peels the wrapper, so I have no reproduction of a wrong value.


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

Version info

  • Merged into: 26.11.1.209-master (included in 26.11 and later)

groeneai and others added 3 commits September 21, 2026 12:35
HashJoin deliberately supports the lazy column replication wrapper on the
right side. materializeColumnsFromRightBlock peels it, promotes the nested
column to Nullable when the sample column is Nullable, and re-wraps it, and
isLazyReplicationUseful is true for every Nullable column because
ColumnNullable::isFixedAndContiguous() returns false. So addBlockToJoin
legitimately receives an ASOF key of type Nullable(T) whose column is a
ColumnReplicated(ColumnNullable(...)).

The ASOF-key NULL filter guarded on asof_column.type->isNullable(), which
says nothing about the wrapper, peeled exactly one representation
(ColumnConst), and then asserted the column was a ColumnNullable in order to
hoist its null map. The branch that cannot handle the wrapper was therefore
the only branch that ran for the column class that is always wrapped. The
filter predates ColumnReplicated and was never revisited for it.

Read nullness through IColumn::isNullAt instead. ColumnReplicated::isNullAt
resolves the logical row through its indexes, so no peel and no
materialization is needed, and the same call three lines above already reads
a const key's nullness this way. Indexing the nested column with the logical
row would not have been equivalent: ColumnReplicated::size() is the indexes
size, so under replication the nested column is smaller and that read is out
of bounds rather than merely wrong.

Deleting the assertion loses no coverage. The "type says Nullable, column is
not a ColumnNullable" invariant is still enforced in the same call by
assertBlocksHaveEqualStructureAllowReplicated, which compares the concrete
column class after peeling one replication level on both sides, and which
runs before the block is stored.

The regression test asserts row equality between the
enable_lazy_columns_replication = 0 and = 1 arms rather than the absence of
an error, because a fix that peeled the wrapper but indexed the nested null
map would not fail, it would silently keep or drop the wrong rows. It covers
the hash and parallel_hash entry points; grace_hash cannot reach the site,
since it materializes the block at its entry point and rejects ASOF.

Co-Authored-By: Claude Opus 5 <[email protected]>
One stress worker in three runs with join_use_nulls=1
(ci/jobs/scripts/stress/stress.py:383). Under that setting an unmatched
ASOF LEFT JOIN row returns NULL for the right-side columns instead of the
type default, so the k = 2 and k = 4 rows disagreed with the reference and
the test would have failed in Stress test and Upgrade check.

A query-local SETTINGS clause overrides a client option only for the
settings it names, so pinning it in the query is what makes the oracle
stable. Local runs could not have caught this: join_use_nulls is not in
SettingsRandomizer, only stress.py injects it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Collapse the added ASOF-key comment to the one non-obvious property: the wrapper resolves the logical row.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 21, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex). Two passes and one fix round:
round 1 raised 2 gate findings plus 2 from my own cold pass; the fix round pinned join_use_nulls;
the round-2 delta re-review and my second cold pass both returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test does not pin join_use_nulls, so it would disagree with its own reference on stress workers AGREE, fixed ci/jobs/scripts/stress/stress.py:383 sets join_use_nulls=1 on one worker in three, and with it the unmatched ASOF LEFT JOIN rows return \N where the reference has an empty tag and 0 (8 of 16 data rows). Invisible locally: join_use_nulls is not in SettingsRandomizer. Fixed by pinning it to 0 in both query-local SETTINGS lists, reference unchanged; the unfixed build still aborts 3/3 on the pinned test
2 ⚠️ The test never proves the right ASOF key reaches HashJoin as a ColumnReplicated, so reverting the fix could go undetected DISAGREE Measured false on this tree: the pristine-HEAD build returns rc=134 for this test in 10 of 10 runs while the fixed build returns rc=0 in 10 of 10 with output byte-equal to the reference, and rc=134 is reachable at HashJoin.cpp:963 only if the wrapper arrived. The parallel_hash scenario also aborts alone, so neither arm is a passenger. No representation oracle exists in any of the 37 in-tree enable_lazy_columns_replication tests, and dumpColumnStructure would itself force materialization
3 💡 IColumn::isNullAt is a virtual call per right-side row where the old code hoisted the null map DISAGREE Each surviving row then pays a hash map emplace plus a SortedLookupVector insert (HashJoinMethodsImpl.h:300-349), and the branch runs only for a Nullable ASOF key. No performance claim is made in this PR
4 💡 The test's coverage depends on the planner keeping the arrayJoin producer, with no SQL-visible assertion that it does DISAGREE Same substance as #2, reached independently before the gate ran. Mitigated by pinning the four relevant plan settings per query and by selecting r.dup so the arrayJoin cannot be pruned

Also checked, no finding: full_sorting_merge is the other ASOF-capable algorithm and is safe,
because FullMergeJoinCursor::setChunk calls removeSpecialColumnRepresentations before reading the
key's null map; grace_hash rejects ASOF and ConstantJoin cannot reach it; every other hard
ColumnNullable cast in the join path acts on freshly built output columns.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence.

Session id: cron:clickhouse-review-slot-10:20260921-141300

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

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [02c6851]

Summary: ✅


AI Review

Summary

PR #121385 fixes nullable ASOF JOIN key filtering with lazy column replication by reading the prepared key's null map. Reviewed head 02c6851a359c1d9becb0dc395088dabd85afb188, the regression coverage, and all prior discussion. No actionable findings.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary was available, and the current-head per-test CI artifact could not be retrieved. Execution evidence relies on the author's reported successful fixed runs and failing reverted runs. An accessible current-head run of 05233_asof_join_nullable_key_lazy_replication would close this independent verification gap.
Final Verdict

✅ Approve.

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

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 02c6851a359c1d9becb0dc395088dabd85afb188 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8fd9fca

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.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 the shard's Select historical data step timed out 3 times at 19:03Z (read timeout=10) and logged "Failed to fetch historical thresholds, will proceed without them", so the query was judged against the 0.15/0.25 bare floors instead of its learned 0.65 bar #121189 (mine, open)
Mergeable Check, PR praktika rollups of the row above, no independent failure #121189

CH Inc sync passes on this head, so it owes no row. The other red mark belongs to the cancelled first attempt on this same head (Finish Workflow of run 35619602002 at 15:33:58Z); the re-run finished it green at 21:03:06Z.

Session id: cron:our-pr-ci-monitor:20260921-213129

@PedroTadim

Copy link
Copy Markdown
Member

cc @vdimir

}
else
{
const auto & asof_column_nullable = assert_cast<const ColumnNullable &>(*asof_column.column).getNullMapData();

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.

Can we keep ColumnNullable as fast path and add additional check here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 0ce2499: checkAndGetColumn<ColumnNullable> keeps the direct null map read for the unwrapped column, and only the wrapped case falls back to isNullAt.

I measured which arm runs where instead of assuming it. With the fast path replaced by a throw, it fires only on the enable_lazy_columns_replication = 0 arm of the regression test; with the old assert_cast restored in the fallback, only the = 1 arm aborts, with the reported Bad cast from type DB::ColumnReplicated to DB::ColumnNullable at the same two addBlockToJoin frames. Unmutated, all four arms (hash and parallel_hash, both settings) match the reference.

Requested in review: read the null map directly when the ASOF key column
really is a ColumnNullable, and only fall back to IColumn::isNullAt for the
representations that the direct read cannot serve.

checkAndGetColumn<ColumnNullable> replaces the assert_cast that aborted, so
the wrapped ColumnReplicated(ColumnNullable(...)) case takes the fallback
instead of being asserted away, while the common unwrapped case keeps the
original per-row null map indexing and no longer pays a virtual call.

Measured with a mutation binary built from this tree, both join algorithms of
the regression test: with the fast path replaced by a throw, the
enable_lazy_columns_replication = 0 arm raises it (size=12) and the = 1 arm
does not, so the fast path is taken exactly for the unwrapped column; with
the fallback replaced by the old assert_cast, the = 1 arm aborts with the
reported 'Bad cast from type DB::ColumnReplicated to DB::ColumnNullable' at
the same two addBlockToJoin frames. Unmutated, all four arms return output
byte-identical to the committed reference.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0ce2499

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
Upgrade check (amd_release) / Error message in clickhouse-server.log the previous release leaves AggregateFunction(countResample(10, 5, 1), ...) tables that the upgraded server refuses to attach: Code: 69 ... The range given in function countResample is empty (ARGUMENT_OUT_OF_BOUND), logged by AsyncLoader::worker #121590 (external, merged into 26.9, not yet in a published release: see below)
Upgrade check (amd_release) / The mutation submitted before the upgrade was not finished the runner's system.mutations probe returns an empty result on that startup, and an empty probe is reported as an unfinished mutation instead of as a failed probe #121315 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent leaf #121590 and #121315, as above

Neither row belongs to this diff, which is one HashJoin.cpp branch plus its 05233 test. Both are new and fleet-wide, measured in CIDB over 30 days: the attach failure on 16 distinct PRs, first row ever at 2026-09-21 23:39 UTC; the probe row on 46 distinct PRs since 2026-09-20 22:22 UTC.

One caveat on the first row, so nobody tries to clear it by merging master. #121590 rewrites the previous release's 05079 and 05211 on the 26.9 branch, so it is absent from master by construction: the tree this job actually built (1de25165d745, the confirmed checkout of job 106784051781) scores 0 for the fix, and so does live master, while the fix commit itself scores 1. The upgrade check clones the newest published 26.9 release, today v26.9.2.8-stable, and compare(4d46c03d0066...v26.9.2.8-stable) is behind by 9 commits, so that release predates the fix. The row clears when the next 26.9 patch release is published, not on any action here.

Session id: cron:our-pr-ci-monitor:20260923-010313

@harikrishnan94 harikrishnan94 self-assigned this Oct 15, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

Let's try a simpler fix:
Move the all_key_columns loop above the filter. It already strips the wrapper. Read the null map of the peeled ASOF key with the old assert_cast.

Build the prepared key columns before the ASOF NULL filter and read the
null map from the prepared ASOF key, so the filter keeps the original
assert_cast and no longer sees the lazy replication wrapper.

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

Copy link
Copy Markdown
Collaborator Author

Done in 02c6851: the all_key_columns loop now runs before the ASOF NULL filter, and the filter reads the null map of the prepared key with the original assert_cast, so the checkAndGetColumn / isNullAt branch is gone and the direct ColumnNullable read is the only path.

The regression test passes 10/10 with identical rows in all four arms (hash / parallel_hash x lazy replication on/off). Putting *asof_column.column back into the cast aborts 10/10 with the original Bad cast from type DB::ColumnReplicated to DB::ColumnNullable, on the lazy replication arms only.

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

LGTM

@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Fix the CI and make it green

@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai Fix CI issues and make it green

@groeneai

Copy link
Copy Markdown
Collaborator Author

@harikrishnan94 All public CI on 02c6851 is green (175 check runs success or skipped, PR and Mergeable Check success, no failed test rows in CIDB). The only red is CH Inc sync: "tests failed (1 new, 4 known)" (the first run on the same commit said "2 new"). That run is in the private repo, which I can't access, so I can't see which test failed.

Could you paste the name and error of the new failure here? The only test a private run sees for the first time is this PR's 05233_asof_join_nullable_key_lazy_replication; if the failure is that test or anything in the ASOF join path, I'll fix it here right away.

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Oct 19, 2026
Merged via the queue into ClickHouse:master with commit bdca15a Oct 19, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@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 Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #121385 to 26.10: Fix logical error in ASOF JOIN when the right ASOF key is lazily replicated
@vdimir vdimir added v26.8-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Nov 10, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 10, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 10, 2026
Backport #121385 to 26.9: Fix logical error in ASOF JOIN when the right ASOF key is lazily replicated
leshikus pushed a commit that referenced this pull request Nov 13, 2026
leshikus pushed a commit that referenced this pull request Nov 13, 2026
vdimir pushed a commit that referenced this pull request Nov 13, 2026
Resolve the only conflict, in HashJoin::addBlockToJoin: 26.8 still
increments data->rows_to_join right after computing the row count
(master moved it later in #116991, which is not backported). Keep that
line and take #121385's move of the key-column loop above the ASOF
NULL filter unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 13, 2026
Cherry pick #121385 to 26.8: Fix logical error in ASOF JOIN when the right ASOF key is lazily replicated
robot-clickhouse added a commit that referenced this pull request Nov 13, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 13, 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-joins JOINs end-to-end (planning hooks + runtime join operators/algorithms). Single bucket to avoid pla... 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.8-must-backport v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants