Skip to content

Fix wrong results for reverse-key tables with join shard optimization - #100861

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-reverse-key-read-by-layers
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:fix-reverse-key-read-by-layers

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

ReadFromMergeTree::readByLayers() hardcoded ReadType::InOrder when creating per-layer
readers for the query_plan_join_shard_by_pk_ranges optimization. For tables with reverse
primary keys (ORDER BY col DESC with allow_experimental_reverse_key = 1), InReverseOrder
is required to produce ascending query output. Instead, each layer read in physical DESC order,
producing wrong results like 4, 3, 2, 1, 0, 9, 8, 7, 6, 5 instead of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

The bug requires all three conditions to be met simultaneously:

  1. read_in_order_use_virtual_row = 1 — enables virtual rows, which allows read-in-order-through-join for INNER joins (without it, read-in-order is skipped for INNER joins and sharding never activates)
  2. enable_join_runtime_filters = 0 — removes the BuildRuntimeFilter step from the plan, which otherwise blocks optimizeJoinByShards from traversing the right side of the join
  3. Table uses allow_experimental_reverse_key = 1 with a DESC primary key

When all three conditions are met, optimizeJoinByShards runs after optimizeReadInOrder has
already set up InReverseOrder reading. The shard optimization splits data into layers and
calls readByLayers(), which creates per-layer readers — but hardcodes ReadType::InOrder
instead of respecting input_order_info->direction.

Fix: use input_order_info->direction to select the correct ReadType. Direction > 0 means
InOrder, direction < 0 means InReverseOrder.

This was a flaky test failure in 03668_shard_join_in_reverse_order — 12 failures in 70K runs
(0.017%) because CI randomizes both read_in_order_use_virtual_row and
enable_join_runtime_filters, and the failure requires both to be in non-default states.

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 wrong query results for tables with reverse primary keys (allow_experimental_reverse_key) when query_plan_join_shard_by_pk_ranges, read_in_order_use_virtual_row, and disabled runtime join filters are all active simultaneously. The join shard optimization would read data in physical (descending) order instead of the requested ascending order.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

ReadFromMergeTree::readByLayers() hardcoded ReadType::InOrder when
creating per-layer readers for the join shard-by-PK-ranges optimization.
For tables with reverse primary keys (ORDER BY col DESC), InReverseOrder
is needed to produce ascending query output. Each layer would read in
physical DESC order instead of the requested ASC order, producing wrong
results like [4,3,2,1,0,9,8,7,6,5] instead of [0,1,2,3,4,5,6,7,8,9].

The bug triggers when all three conditions are met:
- read_in_order_use_virtual_row = 1 (enables read-in-order for INNER joins)
- enable_join_runtime_filters = 0 (removes BuildRuntimeFilter step,
  allowing the shard optimization to traverse both join sides)
- Table uses allow_experimental_reverse_key = 1 with DESC ordering

Fix: use input_order_info->direction to select the correct ReadType.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session d2a0ab6c)

a) Deterministic repro? ✅ YES

CREATE TABLE t0 (c0 Int) ENGINE = MergeTree() ORDER BY (c0 DESC) 
  SETTINGS index_granularity = 1, allow_experimental_reverse_key = 1;
INSERT INTO TABLE t0 (c0) SELECT number FROM numbers(10);
SELECT c0 FROM t0 JOIN t0 tx USING (c0) ORDER BY c0 
  SETTINGS query_plan_join_shard_by_pk_ranges = 1, max_threads = 2, 
           query_plan_read_in_order_through_join = 1,
           read_in_order_use_virtual_row = 1, enable_join_runtime_filters = 0;

Returns 4, 3, 2, 1, 0, 9, 8, 7, 6, 5 (wrong) every time without the fix.

b) Root cause explained? ✅ YES
readByLayers() hardcodes ReadType::InOrder at line 969. For reverse-key tables, input_order_info->direction = -1, requiring InReverseOrder. The shard optimization creates 2 layers; each layer reads in physical DESC order instead of logical ASC order. The FinishSorting step trusts the input is pre-sorted ascending (based on the read-in-order optimization), but it isn't — so wrong results pass through.

c) Fix matches root cause? ✅ YES
Changed the hardcoded ReadType::InOrder to (input_order_info->direction > 0) ? ReadType::InOrder : ReadType::InReverseOrder. This directly addresses the direction mismatch.

d) Test intent preserved? ✅ YES
The fix is in source code only (ReadFromMergeTree.cpp). The test 03668_shard_join_in_reverse_order is unchanged — it still tests reverse-key + shard-join ordering.

e) Both directions demonstrated? ✅ YES

  • Without fix: deterministic wrong output 4, 3, 2, 1, 0, 9, 8, 7, 6, 5
  • With fix: 50/50 passes returning 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
  • Also 50/50 passes via clickhouse-test --test-runs 50 with full randomization

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @novikd — could you review this? It fixes wrong results for reverse-key tables when the join shard optimization kicks in (ReadFromMergeTree::readByLayers hardcodes ReadType::InOrder instead of respecting input_order_info->direction).

@amosbird

Copy link
Copy Markdown
Collaborator

So this seems related to read_in_order_use_virtual_row. I’m wondering how it behaves with reverse sort keys. BTW You might be interested in #94017

@groeneai

Copy link
Copy Markdown
Collaborator Author

@amosbird Yes, exactly — the bug is specifically in the readByLayers() code path that read_in_order_use_virtual_row enables. When that setting is true, INNER joins can use read-in-order optimization, which calls readByLayers(). The bug is that readByLayers() hardcodes ReadType::InOrder at line 969 regardless of the input_order_info->direction — so for reverse-key tables (DESC), it reads layers in the wrong direction, producing wrong results.

Thanks for pointing to #94017 — that's a great stress-testing approach. Once that lands, it would exercise exactly this code path (reverse keys + read-in-order through joins) across the entire test suite, which should catch any similar bugs. My fix here ensures readByLayers() correctly uses InReverseOrder when input_order_info->direction indicates it, so both normal and forced-reverse-key tables will work correctly.

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f16377f]

Summary: ❌

job_name test_name status info comment
Bugfix validation (functional tests) failure
04000_reverse_key_join_shard_read_by_layers FAIL cidb
Stateless tests (arm_asan_ubsan, azure, parallel) failure
03100_lwu_14_parallel FAIL cidb
04033_issue_94659 FAIL cidb
01300_svg FAIL cidb
04050_text_index_starts_ends_with FAIL cidb
02073_mv_dependency_recreate FAIL cidb
04072_jit_decimal_expressions FAIL cidb
00584_view_union_all FAIL cidb
Scraping system tables FAIL cidb
Stateless tests (arm_asan_ubsan, azure, sequential) failure
02494_query_cache_bugs FAIL cidb
01079_parallel_alter_modify_zookeeper_long FAIL cidb
Fast test (arm_darwin) error

AI Review

Summary

This PR adds a regression test (04000_reverse_key_join_shard_read_by_layers.sql/.reference) for wrong ordering with reverse primary keys under join-shard optimization. However, the PR description/changelog claim an implementation fix in ReadFromMergeTree::readByLayers, while the actual diff contains only tests and no src/ changes. High-level verdict: request changes until either the real fix is included or the PR is clearly scoped as test-only.

Findings

❌ Blockers

  • [tests/queries/0_stateless/04000_reverse_key_join_shard_read_by_layers.sql:12] PR scope mismatch: description says behavior is fixed in production code, but diff adds only a test. This can mislead release notes and leave the reported wrong-results path unfixed.
    • Suggested fix: include the corresponding src/Processors/QueryPlan/.../ReadFromMergeTree::readByLayers change that uses direction-aware ReadType, or change title/description/changelog to explicitly say this PR is test-only.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ⚠️ Core behavior is claimed fixed, but no core-code change is present in the PR diff.
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ User-facing behavior claim changed in metadata without corresponding implementation in this PR.
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Changelog/title claim a bug fix implementation, but diff appears test-only.
Safe rollout ⚠️ Rollout cannot happen for the claimed fix unless production code change is included.
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Add the actual implementation fix in the relevant src/ code path; or
    2. Re-scope PR metadata (title, description, and changelog entry/category text) to clearly indicate a test-only change.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 27, 2026
@vdimir
vdimir force-pushed the fix-reverse-key-read-by-layers branch from 385a177 to a629546 Compare March 27, 2026 10:24
@vdimir

vdimir commented Mar 27, 2026

Copy link
Copy Markdown
Member

So this seems related to read_in_order_use_virtual_row. I’m wondering how it behaves with reverse sort keys.

@amosbird good point. In general, it should work since it simply takes the first/last row from the index. So if the order is reversed, it should also pick values accordingly. That said, it probably needs more testing, and there may be other related issues.

@vdimir vdimir self-assigned this Mar 27, 2026

@vdimir vdimir left a comment

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.

Test was missing, but I've added it to current branch

@groeneai
groeneai force-pushed the fix-reverse-key-read-by-layers branch from a629546 to 996c25a Compare March 27, 2026 14:51
pufit and others added 2 commits March 29, 2026 11:00
New test 04000_reverse_key_join_shard_read_by_layers pins the settings
that deterministically trigger the readByLayers bug: read_in_order_use_virtual_row=1
and enable_join_runtime_filters=0. Without the fix, these settings cause the
join shard optimization to read reverse-key table layers in physical DESC
order instead of the requested ASC order, producing wrong results.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix-reverse-key-read-by-layers branch from 04ea70f to f13ac9b Compare March 29, 2026 15:32
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, check the CI, the test has failed.

The test 04000_reverse_key_join_shard_read_by_layers uses `-- { echo ON }`
which echoes all comments and Tags to stdout. The reference file was missing
the Tags line and bugfix comment block, causing a Fast test diff failure.

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

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Thanks for the heads up — the failure was on the previous commit (f13ac9b). The .reference file was missing the echoed tags/comments added by that commit. Already pushed fix in 3b6f70b — CI is running on it now.

@clickhouse-gh

clickhouse-gh Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 92.86% (13/14) · Uncovered code

Full report · Diff report

…d-by-layers

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

DROP TABLE IF EXISTS t_reverse_key;

CREATE TABLE t_reverse_key (c0 Int) ENGINE = MergeTree() ORDER BY (c0 DESC) SETTINGS index_granularity = 1, allow_experimental_reverse_key = 1;

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.

The PR description says this change fixes ReadFromMergeTree::readByLayers by switching from hardcoded ReadType::InOrder to direction-aware read type, but this PR diff contains only tests (04000_...sql/.reference) and no corresponding change under src/.

As it stands, this looks like a regression test without the implementation fix, so the wrong-results bug can still reproduce in production paths while the PR title/changelog claim it is fixed. Please include the actual code change (or clarify if this PR is intentionally test-only and update title/changelog accordingly).

@alexey-milovidov

Copy link
Copy Markdown
Member

The test 02859_replicated_db_name_zookeeper is fixed in #101952

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing as redundant — PR #101654 by @vitlibar merged the identical fix on April 5.

What happened:

CIDB confirmation: Zero master failures for 03668_shard_join_in_reverse_order since April 5 (previously 214 failures/day at peak). Fix is working.

Thank you @vdimir for the review and approval!

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants