Skip to content

Fix wrong results with parallel_hash JOIN and read-in-order-through-join - #109225

Merged
harikrishnan94 merged 35 commits into
ClickHouse:masterfrom
groeneai:fix-distinct-in-order-partial-merge-join
Sep 5, 2026
Merged

harikrishnan94 merged 35 commits into
ClickHouse:masterfrom
groeneai:fix-distinct-in-order-partial-merge-join

Conversation

@groeneai

@groeneai groeneai commented Jul 2, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116913
Related: #109216
Related: #110671

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 wrong results when join_algorithm = 'parallel_hash' is combined with a sorted consumer such as optimize_aggregation_in_order, optimize_distinct_in_order or LIMIT BY. With several join slots and a single-level hash map the join does not keep the order of the left table, so the read-in-order-through-join optimization must not advertise the left sort order in that case.

Description

Minimal reproducible example, wrong on master:

CREATE TABLE l (a UInt32, j UInt8) ENGINE = MergeTree ORDER BY (a, j);
CREATE TABLE r (j UInt8) ENGINE = MergeTree ORDER BY j;
INSERT INTO l SELECT intDiv(number, 8)::UInt32, (number % 8)::UInt8 FROM numbers(64);
INSERT INTO r SELECT number::UInt8 FROM numbers(8);

SELECT a, count() FROM l LEFT JOIN r ON l.j = r.j GROUP BY a ORDER BY a
SETTINGS join_algorithm = 'parallel_hash', max_threads = 8, optimize_aggregation_in_order = 1,
         max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0;

Master returns 1, 1, 1, 1, 1, 1, 1, 57; the correct answer is 8 per group.

chooseMethod leaves a key that materializes to one or two bytes single-level, and for a single-level map the left block is scattered across the slots and emitted slot by slot, so equal values of the left sorting key stop being contiguous while the ordered read is still installed.

The fix flips the IJoin::preservesLeftBlockOrder() default that #110671 introduced from true to false, so a join keeps the left order only if it says so: HashJoin, DirectKeyValueJoin, ConstantJoin and PasteJoin unconditionally, ConcurrentHashJoin only when it does not scatter. That also makes FullSortingMergeJoin safe by property rather than by plan shape: on master it inherits true and is safe only because a Sort step happens to sit between the join and the read.

Validated with debug builds of this branch and of master: the new test passes 10/10 runs here and fails 5/5 on master under the runner's default randomization. The stricter default costs nothing where the order really holds - 03711_read_in_order_through_join still asserts ReadType: InOrder for hash and parallel_hash, and it fails if either safe branch is removed.


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

Version info

  • Merged into: 26.9.1.767 (included in 26.9 and later)

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. In debug/sanitizer builds the chassert (findEqualRangeEndAssumeSorted.h) fires on the first run of the reproducer (5/5 runs aborted on the unpatched binary). In release the wrong result is order-dependent (flaky), which is exactly why the issue was reported as ~40-50%.
b Root cause explained? Yes. findReadingStep in optimizeReadInOrder.cpp propagates read-in-order (left sort property) through any INNER/LEFT ALL/ANY join with no delayed blocks. PartialMergeJoin re-scans left key ranges once per right block, so with >1 right block equal left-key values are no longer contiguous. optimize_distinct_in_order then plants DistinctSortedStreamTransform, whose equal-range search assumes contiguous equal values -> wrong DISTINCT in release, LOGICAL_ERROR in debug.
c Fix matches root cause? Yes. It stops advertising the left sort order across joins that do not preserve it (preservesLeftBlockOrder()), so DistinctSortedStreamTransform is not planted for partial_merge; a plain DistinctTransform is used (confirmed via EXPLAIN PIPELINE).
d Test intent preserved / new tests added? New regression test 04498_distinct_in_order_partial_merge_join. No existing test weakened. The read-in-order optimization is preserved for order-preserving joins (see g).
e Demonstrated in both directions? Yes. Unpatched binary: 5/5 reproducer runs abort. Patched binary: reference matches, and partial_merge/prefer_partial_merge return the correct 6 rows 20/20 runs.
f Fix is general, not a narrow patch? Yes. The fix is at the shared propagation site and covers every reorder-capable join: MergeJoin and JoinSwitcher override preservesLeftBlockOrder()=false; GraceHashJoin/SpillingHashJoin were already excluded via hasDelayedBlocks(); FullSortingMergeJoin is YShaped and naturally safe. Not a symptom guard in the transform.
g Generalizes across inputs / optimization preserved? Verified all algorithms return the correct 6 rows (hash, parallel_hash, full_sorting_merge, grace_hash, auto). The read-in-order optimization still fires for hash/direct/concurrent-hash joins (the condition only gained && preservesLeftBlockOrder(), which is true for them) - confirmed via EXPLAIN PIPELINE (ReadPoolInOrder, algorithm: InOrder still present for hash).
h Backward compatible? Yes. No setting default, on-disk/wire/metadata format, or new validation changed. Pure query-plan correctness fix. SettingsChangesHistory.cpp not applicable.
i Invariants and contracts preserved? Yes. The change restores the precondition that DistinctSortedStreamTransform / findEqualRangeEndAssumeSorted rely on (equal values contiguous). It only narrows when read-in-order is propagated; the join execution contract is unchanged.

Session id: cron:clickhouse-worker-slot-5:20260702-194900

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @KochetovNicolai — could you review this? It stops the read-in-order-through-join optimization from advertising the left sort order across PartialMergeJoin (which re-scans left key ranges per right block and so does not preserve it), fixing wrong DISTINCT results in release and the sorted-DISTINCT LOGICAL_ERROR in debug (#109216). New IJoin::preservesLeftBlockOrder() gates the propagation; hash/direct joins are unchanged.

@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c356add]

Summary: ✅


AI Review

Summary

This PR narrows read_in_order_through_join to joins that actually preserve the left stream order and fixes the wrong-result parallel_hash single-level-map case. The code path itself looks consistent, but the current head still leaves two opt-ins introduced by the fail-closed default (ConstantJoin and DirectKeyValueJoin) without a focused proof that ordered-read propagation still works through them.

Tests
  • ⚠️ [tests/queries/0_stateless/04498_parallel_hash_read_in_order_through_join.sql:1], [src/Interpreters/ConstantJoin.h:35], [src/Interpreters/DirectJoin.h:39] Flipping IJoin::preservesLeftBlockOrder() to fail-closed changes every join until it opts back in again. This head adds a good parallel_hash regression, but I still could not find a focused read_in_order_through_join probe for the new ConstantJoin/DirectKeyValueJoin opt-ins: 03711_read_in_order_through_join only covers HashJoin/ConcurrentHashJoin, while the current direct/constant tests only prove algorithm selection or unrelated bugs. Please add one small LEFT JOIN ... ON 1 = 1 probe for ConstantJoin and one dictionary LEFT JOIN probe for DirectKeyValueJoin with pinned read-in-order settings, asserting the left ReadType: InOrder (or another guard-sensitive sorted-consumer result).
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: add focused coverage proving the ConstantJoin and DirectKeyValueJoin opt-ins still preserve ordered-read propagation after the fail-closed default flip.

LLVM Coverage Report

Measured on commit c356add.

Metric Baseline Current Δ
Lines 88.80% 88.70% -0.10%
Functions 92.20% 92.10% -0.10%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 17/20 (85.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
Comment thread src/Interpreters/IJoin.h Resolved
…-in-order

The read-in-order-through-join optimization propagated read-in-order (and the
left sort property) through any INNER/LEFT ALL/ANY join without delayed blocks.
This is only valid for joins that stream the left side through once (hash,
direct). PartialMergeJoin (join_algorithm = partial_merge / prefer_partial_merge)
matches the left stream against the right side per right block, re-emitting left
key ranges for each right block, so when the right side has more than one block
equal left-key values are no longer contiguous in the joined stream.

With the left sort property falsely advertised, optimize_distinct_in_order plants
a DistinctSortedStreamTransform on top of the join. Its equal-range search assumes
sorted (contiguous equal) input, so:
  - release builds silently return wrong DISTINCT results (duplicate rows);
  - debug/sanitizer builds hit the "Equal values are not contiguous within the
    range assumed to be sorted" LOGICAL_ERROR and abort.

Fix: add IJoin::preservesLeftBlockOrder() (default true) and require it in
findReadingStep before propagating read-in-order through a join.
  - MergeJoin (PartialMergeJoin): false, re-scans left per right block.
  - JoinSwitcher: false, may switch to MergeJoin at runtime.
  - FullSortingMergeJoin: false, re-sorts the left side by the join keys. In
    practice its "Sort before JOIN" step already stops findReadingStep before the
    join, but the join genuinely does not preserve left order, so the contract is
    made explicit and robust against future plan changes.
Hash/direct/concurrent-hash keep the optimization unchanged; GraceHashJoin and
SpillingHashJoin were already excluded via hasDelayedBlocks().

Test 04498 freezes merges on the right table (SYSTEM STOP MERGES) so the two
inserts stay as two separate right-side blocks; without that a background merge
could collapse them and let the unfixed plan pass spuriously. Verified both
directions: the test aborts with the LOGICAL_ERROR on an unfixed binary and
returns the correct 6 rows for partial_merge, prefer_partial_merge and
full_sorting_merge with the fix.

Fixes ClickHouse#109216

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-distinct-in-order-partial-merge-join branch from 9325ef4 to c1b6c29 Compare July 2, 2026 23:52
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the updated fix (widened to full_sorting_merge, deterministic test):

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On an unfixed debug binary (Build ID 9300088f) the updated 04498 test (with SYSTEM STOP MERGES t2_04498) hits Equal values are not contiguous LOGICAL_ERROR and aborts on nearly every run.
b Root cause explained? read_in_order_through_join propagated the left sort property through any INNER/LEFT ALL/ANY join without delayed blocks. PartialMergeJoin re-scans left key ranges once per right block, so with >1 right block equal left-key values are no longer contiguous; optimize_distinct_in_order then plants DistinctSortedStreamTransform, whose equal-range search assumes contiguous-equal input -> wrong DISTINCT (release) / LOGICAL_ERROR (debug).
c Fix matches root cause? Yes. IJoin::preservesLeftBlockOrder() gates the propagation in findReadingStep; joins that reorder the left stream return false so DistinctSortedStreamTransform is not planted (plain DistinctTransform is used).
d Test intent preserved / new tests added? New regression test 04498 asserts correct DISTINCT for partial_merge, prefer_partial_merge and full_sorting_merge. SYSTEM STOP MERGES makes the multi-right-block precondition deterministic.
e Both directions demonstrated? Yes. Unfixed binary: LOGICAL_ERROR/abort. Fixed binary (Build ID 59998184): correct 6 rows, 25/25 runs, no abort.
f Fix is general across code paths? Audited all IJoin subclasses. Order-changing/rescanning joins overridden false: MergeJoin (PMJ), JoinSwitcher (may switch to MergeJoin at runtime), FullSortingMergeJoin (re-sorts left by join keys). Order-preserving joins keep default true: HashJoin, ConcurrentHashJoin, DirectKeyValueJoin. GraceHashJoin and SpillingHashJoin were already excluded by hasDelayedBlocks().
g Fix generalizes across inputs? Verified across join_algorithm values (hash, parallel_hash, grace_hash, partial_merge, prefer_partial_merge, full_sorting_merge, auto), both analyzers, and max_threads 1/2/4/8/16: all return the same result as the hash reference, no abort. The gate is join-algorithm-based, not input-shape-based.
h Backward compatible? Yes. No setting default, wire, or on-disk format change. The optimization is only withheld for joins that never preserved left order; correctness improves, no behavior to restore.
i Invariants and contracts preserved? Yes. The change restores the invariant DistinctSortedStreamTransform relies on (its input is contiguous-equal-sorted). preservesLeftBlockOrder() is a read-only predicate on the concrete join; the read-in-order gate now upholds it on the propagation path. Order-preserving joins keep the optimization unchanged (verified no regression).

Session id: cron:clickhouse-worker-slot-4:20260702-233000

The read-in-order-through-join fix in this PR made findReadingStep (second
pass) also require IJoin::preservesLeftBlockOrder(), so it no longer propagates
read-in-order through partial_merge / prefer_partial_merge (MergeJoin),
full_sorting_merge (FullSortingMergeJoin), or auto (JoinSwitcher).

topKThroughJoin's pass-1 deferral (second_pass_can_apply) still only excluded
joins with delayed blocks. With spilling off and the join side pinned, it kept
deferring the sound Sort + Limit pushdown to a second pass that now bails on
!preservesLeftBlockOrder(), so neither optimization fired and a query like
LEFT ALL JOIN ... ORDER BY left_pk LIMIT n fell back to a full join plus a full
sort on exactly those algorithms.

Mirror preservesLeftBlockOrder in the deferral via joinMayNotPreserveLeftBlockOrder,
so the pushdown runs in pass 1 for non-order-preserving algorithms. Order-preserving
joins (hash, direct, concurrent hash) are unchanged and still defer to read-in-order.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the topKThroughJoin deferral fix (b19568b), which widens this PR beyond the preservesLeftBlockOrder gate in findReadingStep.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN PLAN on SELECT l.pk, r.v FROM l LEFT ALL JOIN r ON l.j = r.j ORDER BY l.pk LIMIT 10 SETTINGS join_algorithm = 'partial_merge', max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0, query_plan_join_swap_table = 0 shows no pushed Limit on the left side (also prefer_partial_merge, full_sorting_merge).
b Root cause explained? This PR added !preservesLeftBlockOrder() to findReadingStep (pass 2), so read-in-order no longer propagates through PMJ/FSMJ/JoinSwitcher. But topKThroughJoin's pass-1 deferral (second_pass_can_apply) still only checked !joinMayHaveDelayedBlocks. With spilling off + side pinned it kept deferring to a pass 2 that now bails, so neither optimization fired -> full join + full sort.
c Fix matches root cause? Yes. Adds joinMayNotPreserveLeftBlockOrder (the pass-1 mirror of the exact pass-2 gate) to second_pass_can_apply, so the deferral is disabled precisely for the algorithms pass 2 can no longer serve.
d Test intent preserved / new tests added? New test 04499_top_k_through_join_non_order_preserving.sql: asserts the pushed Limit is present for partial_merge / prefer_partial_merge / full_sorting_merge and absent for hash, plus result correctness. Existing 04498 + all top_k_through_join gate tests still pass.
e Both directions demonstrated? Yes. 04499 returns 0 0 0 on the pre-fix binary (Build ID cbd38815), 1 1 1 after (Build ID 2dedcb88); 50/50 under randomized settings.
f Fix is general across code paths? Yes. The mirror covers both plan representations (JoinStep via preservesLeftBlockOrder(), JoinStepLogical via join_algorithms) and all three non-preserving algorithms + JoinSwitcher, matching every case findReadingStep rejects.
g Fix generalizes across inputs? Yes. Keyed on the join algorithm / IJoin flag, not on datatypes or wrappers, so it holds for any left/right column types. Verified partial_merge, prefer_partial_merge, full_sorting_merge, and hash (unchanged).
h Backward compatible? Yes. Pure query-plan optimization change, no setting default / on-disk / wire / metadata change. It only restores the pushdown these algorithms had before this PR; no SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. topKThroughJoin's soundness (LEFT/RIGHT + ANY/ALL, sort key from preserved side only) is unchanged. joinMayNotPreserveLeftBlockOrder is a strict tightening of second_pass_can_apply, so it can only enable the already-sound pushdown, never propagate order the join destroys. Order-preserving joins still defer to read-in-order (verified: hash keeps Prefix sort description, no explicit pushed Limit).

Session id: cron:clickhouse-worker-slot-3:20260703-004400

Comment thread src/Interpreters/IJoin.h Outdated
/// PartialMergeJoin does not: it re-scans left key ranges once per right block, so equal
/// left-key values are no longer contiguous once the right side has more than one block.
/// The read-in-order-through-join optimization relies on this to keep the left sort property.
virtual bool preservesLeftBlockOrder() const { return true; }

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.

ConcurrentHashJoin cannot keep the new default preservesLeftBlockOrder() == true. When HashJoin::chooseMethod(..., use_two_level_maps = true) falls back to key8, key16, or the single-LowCardinality map types, ConcurrentHashJoin::joinBlock scatters the left block across slots and ConcurrentHashJoinResult emits slot 0, then 1, etc. A left stream like (a, k) = (0, 0), (0, 1), (1, 0), (1, 1) therefore comes out as (0, 0), (1, 0), (0, 1), (1, 1), so equal a values are no longer contiguous even though the input was sorted by a.

That means optimize_distinct_in_order / optimizeReadInOrder can still apply sorted consumers unsafely for join_algorithm = 'parallel_hash' on those key shapes. Because topKThroughJoin runs before physical join conversion, the logical mirror in joinMayNotPreserveLeftBlockOrder also needs to stop deferring on JoinAlgorithm::PARALLEL_HASH unless the key shape is proven to use a two-level map.

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.

Confirmed and fixed in 3737f8b.

chooseMethod(use_two_level_maps=true) (HashJoin.cpp) leaves key8 / key16 and the single non-nullable LowCardinality path single-level, and ConcurrentHashJoin::joinBlock only passes the left block through unscattered when twoLevelMapIsUsed(). So the fix is precise rather than a blanket disable:

  • Physical: ConcurrentHashJoin::preservesLeftBlockOrder() now returns twoLevelMapIsUsed(). Read-in-order still propagates for two-level key shapes (verified: UInt64 key keeps Read type: InOrder), and stops for single-level ones.
  • Logical (topKThroughJoin): parallel_hash is treated as non-order-preserving only when it is forced without a hash fallback. With the default direct,parallel_hash,hash list the planner picks plain HashJoin for small right sides (order preserving), and when it switches to ConcurrentHashJoin for a large right side the second pass's physical gate above still refuses order propagation, so correctness holds either way. This avoids disabling the deferral for the common hash-fallback path (04209 / 04230 / 04234).

Repro (debug), single-level key8, optimize_aggregation_in_order=1: before, GROUP BY a returned a=0..6 -> 1, a=7 -> 57; after, every a returns its correct count. Covered in 04498 (correctness + an EXPLAIN assertion that read-in-order is not planted for the single-level key but still is for a UInt64 key) and 04499 (the pushdown fires for forced parallel_hash).

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.

parallel_hash with a hash fallback is still not safe to defer unconditionally. In the current code, PlannerJoins::tryCreateJoin picks ConcurrentHashJoin whenever PARALLEL_HASH is enabled and rhs_size_estimation is absent or above the threshold, even if HASH is also enabled (src/Planner/PlannerJoins.cpp:1234-1238). joinMayNotPreserveLeftBlockOrder in src/Processors/QueryPlan/Optimizations/topKThroughJoin.cpp:119-127 only checks for the presence of a HASH fallback, so it still defers for direct,parallel_hash,hash.

If that physical join then lands on a single-level ConcurrentHashJoin, pass 2 bails out on preservesLeftBlockOrder() == false and we again lose both optimizations. So the original top-k part of this thread is still present for the HASH-fallback / no-estimate-or-large-RHS path; the current fix only covers forced parallel_hash.

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.

Confirmed and fixed in 2dd2e59.

Reproduced on the pre-fix binary: direct,parallel_hash,hash + a UInt8 (key8, single-level) join key + a right side >= parallel_hash_join_threshold -> tryCreateJoin picks ConcurrentHashJoin, pass 1 deferred (the old guard only fired without a hash fallback), pass 2 bailed on !preservesLeftBlockOrder(), so the left read was Default and no Limit was pushed (full join + full sort).

rhs_size_estimation is only filled in the second pass and the map type is unknown at this logical stage, so I cannot mirror tryCreateJoin's choice here. I dropped the !hash_fallback carve-out: parallel_hash is now treated as possibly non-order-preserving whenever it is enabled. Running the pushdown is never worse than deferring: the injected Sort + Limit on the left is itself satisfied by a read-in-order scan of the primary key when applicable. Verified via EXPLAIN that the default-list large-RHS single-level case now streams the left InOrder with a pushed Limit 10, and the two-level (UInt64) case is unchanged in correctness.

Coverage: added a default-list (parallel_hash + hash fallback) pushdown assertion to 04499 (guard-sensitive: 0 pre-fix, 1 post-fix). Pinned join_algorithm = 'hash' in 04209/04230/04234 so those keep exercising the read-in-order / swap / FINAL deferral gate with an order-preserving algorithm.

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.

ConcurrentHashJoin::preservesLeftBlockOrder() itself still looks correct, but the top-k part from this thread is back in the current code. topKThroughJoin still defers based only on !joinMayHaveDelayedBlocks(...) at src/Processors/QueryPlan/Optimizations/topKThroughJoin.cpp:329-335, so a parallel_hash,hash logical join can still defer even when the eventual physical ConcurrentHashJoin later reports preservesLeftBlockOrder() == false for a single-level map (src/Interpreters/ConcurrentHashJoin.h:78). That recreates the "both optimizations disabled" path for the fallback / large-RHS case.

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.

🕵 Both parts of this thread now point at master's code, not at this PR's diff.

ConcurrentHashJoin::preservesLeftBlockOrder() — the correctness fix — is confirmed still in place (src/Interpreters/ConcurrentHashJoin.h:79), and it is the only physical gate that matters for read-in-order: findReadingStep reads it directly (optimizeReadInOrder.cpp:162).

The topKThroughJoin deferral heuristics for a logical join (joinMayHaveDelayedBlocks / joinMayNotPreserveLeftBlockOrder) were dropped from this PR during the rework, after #110671 landed the findReadingStep gate on master; the only change left in topKThroughJoin.cpp is a comment. So the behaviour described here is master's current behaviour, unchanged by this branch, and it is a lost-optimization (perf) case rather than a wrong result: the Sort + Limit pushdown that the deferral falls back to is itself sound. Tracking it as a follow-up instead of re-expanding a Bug Fix PR that is still awaiting human review.

…evel maps

ConcurrentHashJoin (join_algorithm = 'parallel_hash') builds its inner HashJoins
with two-level maps, but chooseMethod leaves a single 1-byte (key8) or 2-byte
(key16) numeric key, or a single non-nullable LowCardinality key, single-level.
For those key shapes joinBlock scatters the left block across slots and
ConcurrentHashJoinResult emits slot 0, then 1, ..., so equal left-key values stop
being contiguous even for a sorted left input. Inheriting the default
preservesLeftBlockOrder() == true let optimize_distinct_in_order /
optimizeReadInOrder plant a sorted DISTINCT/aggregation consumer on that scattered
stream, giving wrong results (and LOGICAL_ERROR in debug/sanitizer builds).

Override ConcurrentHashJoin::preservesLeftBlockOrder() to twoLevelMapIsUsed(): the
order is preserved only when the shared two-level map keeps the left block
unscattered. This is precise, so read-in-order still fires for two-level key shapes.

topKThroughJoin runs before physical join selection, where the map type is unknown.
Mirror the gate there for parallel_hash only when it is forced without a hash
fallback; when hash is also enabled the planner picks plain HashJoin (order
preserving) unless the right side is large, and in that switched case the second
pass's physical gate still refuses order propagation.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate for the parallel_hash / ConcurrentHashJoin fix (commit 3737f8b), addressing the fourth review finding.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug build, single-level key8 join key, forced parallel_hash, optimize_aggregation_in_order=1: SELECT a, count() ... LEFT ALL JOIN ... ON tl.j = tr.j (j UInt8) GROUP BY a ORDER BY a returns a=0..6 -> 1, a=7 -> 57 instead of 8 per group, every run.
b Root cause explained? ConcurrentHashJoin builds inner HashJoins with two-level maps, but chooseMethod(use_two_level_maps=true) leaves key8/key16 and single non-nullable LowCardinality keys single-level. For those, joinBlock scatters the left block across slots and ConcurrentHashJoinResult emits slot 0, then 1, ..., so equal left-key values stop being contiguous. Inheriting preservesLeftBlockOrder() == true let read-in-order/DISTINCT-in-order plant a sorted consumer on that scattered stream.
c Fix matches root cause? Yes. ConcurrentHashJoin::preservesLeftBlockOrder() returns twoLevelMapIsUsed() (order preserved iff the block is not scattered), gating the exact mechanism from (b).
d Test intent preserved / new tests added? Yes. 04498 extended with the parallel_hash correctness case + an EXPLAIN assertion (read-in-order not planted for single-level key, still planted for a UInt64 two-level key). 04499 extended with a parallel_hash pushdown assertion. No existing assertions weakened.
e Both directions demonstrated? Yes. Baseline binary (no fix): wrong agg a=7 -> 57 and single-level EXPLAIN InOrder count = 1. Fixed binary: correct 8 per group and InOrder count = 0; UInt64 key still InOrder count >= 1.
f Fix is general across code paths? Yes. Physical gate keyed on twoLevelMapIsUsed() covers every single-level shape (key8, key16, single non-nullable LowCardinality) uniformly, not just the one reported. The sibling reordering joins (MergeJoin, JoinSwitcher, FullSortingMergeJoin) were already gated; ConcurrentHashJoin was the remaining one.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified key8 (UInt8) and key16 (UInt16) scatter and are fixed; UInt64 (two-level) preserves order and keeps read-in-order (not over-disabled). The gate reads the actual chosen map type, so LowCardinality and multi-key packing route correctly by construction.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation change. Only a query-plan decision that previously produced wrong results now produces correct ones; two-level parallel_hash retains the read-in-order fast path.
i Invariants and contracts preserved? Yes. preservesLeftBlockOrder()'s contract (left rows emitted in original stream order) now matches ConcurrentHashJoin's actual behavior. twoLevelMapIsUsed() reads data->type, fixed at HashJoin construction and stable when plan optimization queries it; hash_joins[0]->data is always populated (slots >= 1). The logical mirror only tightens the pass-1 deferral; the pass-2 physical gate remains the correctness authority.

Session id: cron:clickhouse-worker-slot-2:20260703-021400

…allback

The pass-1 deferral in topKThroughJoin only treated parallel_hash as
non-order-preserving when it was forced without a hash fallback. But
PlannerJoins::tryCreateJoin still picks ConcurrentHashJoin for the default
direct,parallel_hash,hash list when there is no right-side estimate or the
right side is at least parallel_hash_join_threshold, and a single-level map
key (key8 / key16 / single non-nullable LowCardinality) then scatters the
left order. The map type and right-side size are unknown at the logical
stage (rhs_size_estimation is filled in the second pass), so a hash fallback
does not guarantee order preservation. In that case the deferral bailed in
the second pass on the physical !preservesLeftBlockOrder() gate and both the
Sort+Limit pushdown and read-in-order were lost, leaving a full join plus a
full sort. Treat parallel_hash as possibly non-order-preserving whenever it
is enabled and run the pushdown in pass 1; the injected Sort+Limit is itself
satisfied by a read-in-order scan when applicable, so it is never worse.

Pin join_algorithm='hash' in the 04209/04230/04234 gate tests so they keep
exercising the read-in-order / swap / FINAL deferral gate with an
order-preserving algorithm. Add a default-list (parallel_hash + hash
fallback) pushdown assertion to 04499. Pin the read-in-order trio in the
04498 parallel_hash key8 block and both EXPLAIN probes so CI randomization
of query_plan_read_in_order cannot make the guard go blind.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. direct,parallel_hash,hash + UInt8 (key8) join key + right side >= parallel_hash_join_threshold (500k rows) + query_plan_join_swap_table=0, max_bytes_*_before_external_join=0. Pre-fix EXPLAIN: left Read type: Default, no pushed Limit. Deterministic.
b Root cause explained? The pass-1 deferral (joinMayNotPreserveLeftBlockOrder) only flagged parallel_hash when there was no hash fallback. But PlannerJoins::tryCreateJoin picks ConcurrentHashJoin for the default list when there is no RHS estimate or RHS >= threshold, even with hash enabled; on a single-level map key it scatters the left order. Pass 1 deferred, pass 2 then bailed on the physical !preservesLeftBlockOrder() gate, so neither the Sort+Limit pushdown nor read-in-order fired: full join + full sort.
c Fix matches root cause? Yes. rhs_size_estimation is filled only in the second pass and the map type is unknown at the logical stage, so the deferral cannot mirror the planner's choice. Dropped the !hash_fallback carve-out: parallel_hash is treated as possibly non-order-preserving whenever enabled, so the pushdown runs in pass 1 instead of deferring to a path pass 2 can refuse.
d Test intent preserved / new tests added? Yes. Added a default-list (parallel_hash + hash fallback) pushdown assertion to 04499 (guard-sensitive: 0 pre-fix, 1 post-fix). Pinned join_algorithm='hash' in 04209/04230/04234 so they keep testing the read-in-order / swap / FINAL deferral gate with an order-preserving algorithm (their intent), not join order preservation. Pinned the in-order trio in the 04498 key8 block + both EXPLAIN probes (Finding B).
e Both directions demonstrated? Yes. Pre-fix (Build ID 1208eab9): default-list large-RHS single-level -> no pushed Limit, left Default. Post-fix (Build ID 12e8af95): pushed Limit 10 + left Read type: InOrder. 04498/04499 40/40 under randomization; full top_k/read-in-order/distinct family 170/170 (stateful env-skipped).
f Fix is general across code paths? Yes. The two gates are consistent: the physical authority is ConcurrentHashJoin::preservesLeftBlockOrder() == twoLevelMapIsUsed() (pass 2, CR#4, unchanged); the logical mirror now treats parallel_hash conservatively (pass 1). The other order-changing algorithms (partial_merge/prefer_partial_merge/full_sorting_merge/auto) were already handled. No sibling gate left stale.
g Fix generalizes across inputs? Yes. Verified single-level (UInt8/key8) large RHS now fires the pushdown, and two-level (UInt64) still streams InOrder + correct results (not over-disabled). The logical mirror is key-shape-agnostic (it must be: the map type is unknown at that stage), so all parallel_hash key shapes take the sound pushdown path; the precise physical gate still lets read-in-order through in pass 2 for order-preserving shapes when the pushdown does not run.
h Backward compatible? Yes. No setting default, on-disk/wire format, or metadata change. Pure query-plan optimization gating; both before and after produce correct results (this only affects which of two equivalent-or-better plans is chosen). No SettingsChangesHistory.cpp change needed.
i Invariants and contracts preserved? Yes. The pushdown soundness sketch (LEFT/RIGHT + ALL/ANY, sort key only on preserved side) is join-algorithm-independent and unchanged. joinMayNotPreserveLeftBlockOrder is only consulted to decide defer-vs-pushdown; making it return true for parallel_hash never enables an unsound pushdown, it only avoids a deferral that would lose both optimizations. Physical preservesLeftBlockOrder() gate in findReadingStep remains the correctness authority.

Session id: cron:clickhouse-worker-slot-3:20260703-040100

The parallel_hash and direct,parallel_hash,hash pushdown assertions test the
logical-stage mirror (joinMayNotPreserveLeftBlockOrder over JoinStepLogical),
which only exists in the new analyzer. Under the old analyzer topKThroughJoin
sees the already-built physical ConcurrentHashJoin and reads its exact
preservesLeftBlockOrder() (true for the two-level UInt64 map used here), so it
correctly defers and read-in-order fires instead. That is a different but
equally correct plan with no explicit pushed Limit, so the assertion returned 0
under the old-analyzer job. Pin enable_analyzer=1 on both the wrapper and the
EXPLAIN subquery so the two assertions stay deterministic on both analyzers.

The old-analyzer job forbids changing enable_analyzer inside a subquery when the
session value differs, hence the pin on both levels.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixup pushed (4b13612): the parallel_hash and direct,parallel_hash,hash pushdown assertions in 04499 were not old-analyzer robust and failed the Stateless tests (..., old analyzer, ...) job (1 1 1 1 1 0 expected, 1 1 1 0 0 seen). Root cause: those two assertions target the logical-stage mirror (joinMayNotPreserveLeftBlockOrder over JoinStepLogical), which only exists in the new analyzer. Under the old analyzer topKThroughJoin inspects the already-built physical ConcurrentHashJoin and reads its exact preservesLeftBlockOrder() (true for the two-level UInt64 map here), so it correctly defers and read-in-order fires instead - a different but equally correct plan with no explicit pushed Limit. Pinned enable_analyzer = 1 on both the wrapper and the EXPLAIN subquery of those two probes (the old-analyzer job forbids changing the setting in a subquery when the session value differs). The four analyzer-independent probes (partial_merge / prefer_partial_merge / full_sorting_merge / hash) are unchanged and still run under both analyzers.

The 04209 / 04230 / 04234 test-level rows shown under Bugfix validation are the inverted "did-not-reproduce-on-master" semantics for pre-existing gate tests dragged into the changed-file set; both Bugfix validation (functional tests) jobs report success (the actual regression test 04498 validates the fix), so no action was needed there.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-client --enable_analyzer=0 running the parallel_hash / default-list probes returns 0; --enable_analyzer=1 returns 1. Reproduced the exact CI 1 1 1 0 0 locally on the old analyzer.
b Root cause explained? The two probes assert the logical-stage mirror joinMayNotPreserveLeftBlockOrder(JoinStepLogical), which only runs under the new analyzer. Under the old analyzer topKThroughJoin sees the physical ConcurrentHashJoin; for the UInt64 two-level map preservesLeftBlockOrder() is true, so it defers and read-in-order fires (verified: left read InOrder, Prefix sort description: pk ASC) - no pushed Limit, assertion returns 0. Both plans are correct.
c Fix matches root cause? Yes. Pin enable_analyzer = 1 on exactly the two analyzer-dependent probes so they assert the mechanism (logical mirror) on the analyzer where it exists. Not a bound-widening or blanket skip.
d Test intent preserved / new tests added? Yes. The assertions still prove the CR#4/CR#5 logical-mirror pushdown fires for parallel_hash / default-list. The four analyzer-independent probes are untouched. No coverage removed; the whole test still runs under the old analyzer (only the two logical-mirror probes are analyzer-pinned) rather than being skipped with no-old-analyzer.
e Both directions demonstrated? Yes. New analyzer: 1 1 1 1 1 0 (pass). Old analyzer pre-fix: 1 1 1 0 0 (fail). Old analyzer post-fix: 1 1 1 1 1 0 (pass). 30/30 randomized runs pass on each analyzer; the guard stays live because the pin forces the new-analyzer path where CR#4/CR#5 (baseline 0, fixed 1) governs.
f Fix is general across code paths? N/A (test-determinism setting pin, not a code change). The underlying code fixes (CR#1-CR#5) already cover PMJ / FSMJ / ConcurrentHashJoin.
g Fix generalizes across inputs? N/A (test-determinism setting pin, not a code change).
h Backward compatible? N/A (test-only change; no setting default, format, or validation change).
i Invariants and contracts preserved? N/A (test-only change). The fix does not touch any server code or the test's other assertions.

Session id: cron:clickhouse-worker-slot-4:20260703-083300

The 04499 top-k-through-join regression used a right table with a 100x
fan-out, so a LEFT ALL JOIN made the top-10 rows all pk = 0. A pushdown
that kept only the first left row (a wrong Limit 1) or attached the limit
to the wrong side would still return ten pk = 0 rows and keep the
assertions green, so the test did not actually prove the topKThroughJoin
contract.

Make the join one-to-one (each left key matches exactly one right row) so
the correctness probes return the exact top-10 pk 0..9. A wrong pushed
limit now changes the returned rows instead of hiding behind equal pk. The
EXPLAIN probes still assert the pushed Limit step fires for every
non-order-preserving algorithm; the one-to-one correctness probes pin its
value and side.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the current binary, forcing a Limit 1 left-prefix before the join (SELECT * FROM tl ORDER BY pk LIMIT 1) returns a single 0 with one-to-one data vs 0..9 with the correct Limit 10; the old 100x fan-out data returned ten 0s in both cases.
b Root cause explained? The old right table had each key 10x, so LEFT ALL JOIN made the top-10 rows all pk = 0. A pushdown that kept only the first left row (wrong Limit 1), or attached the limit to the right side, still produced ten pk = 0 rows, so the correctness probe passed spuriously; the EXPLAIN probes only checked a Limit step exists, not its value.
c Fix matches root cause? Yes. Made the join one-to-one (both tables SELECT number, number FROM numbers(100000)) so the top-10 pk are the distinct sequence 0..9; a wrong pushed limit value or side now changes the returned rows.
d Test intent preserved / new tests added? Yes, and strengthened. The %Limit EXPLAIN probes (pushdown fires) are unchanged; the correctness probes now additionally pin the pushed limit's value and side.
e Both directions demonstrated? Yes. Pushdown ON -> %Limit probe = 1 and correctness = 0..9; pushdown OFF (query_plan_top_k_through_join=0) -> %Limit probe = 0; forced Limit 1 left-prefix -> single 0 (differs from reference).
f Fix is general across code paths? N/A (test rigor change, not a code bug). The covered algorithms (partial_merge / prefer_partial_merge / full_sorting_merge / parallel_hash / default list / hash) are unchanged.
g Fix generalizes across inputs? N/A (test rigor change, not a code bug).
h Backward compatible? N/A (test-only change).
i Invariants and contracts preserved? N/A (test-only change). Verified 50/50 under randomization on BOTH new and old analyzer; dropped an earlier tl_04499[10] join-header annotation probe that was flaky because the annotation is absent when the randomizer sets query_plan_optimize_join_order_limit=0.

Session id: cron:clickhouse-worker-slot-3:20260703-092701

…sion

buildInputOrderInfo(DistinctStep) only traverses the join when
query_plan_read_in_order_through_join is on. The stateless runner randomizes
it (and the rest of the read-in-order trio); when it lands at 0 the sorted
consumer is never planted, so the partial_merge / prefer_partial_merge /
full_sorting_merge queries return the correct 6 rows even on an unfixed binary
and the guard goes blind. Pin the trio on those queries so the through-join
path this test guards is actually exercised.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a debug server with the line-163 preservesLeftBlockOrder() gate removed (unpatched), the committed .sql aborts every run with Equal values are not contiguous within the range assumed to be sorted.
b Root cause explained? The stateless runner randomizes query_plan_read_in_order_through_join. buildInputOrderInfo(DistinctStep) only traverses the join when that setting is on (optimizeReadInOrder.cpp:1406, findReadingStep:144). At 0, findReadingStep stops at the join, the plan stays plain DistinctTransform, and the unfixed binary returns the correct 6 rows, so the guard goes blind.
c Fix matches root cause? Yes. Pin the full read-in-order trio (optimize_read_in_order, query_plan_read_in_order, query_plan_read_in_order_through_join = 1) on the three main DISTINCT queries so the through-join path is always exercised.
d Test intent preserved / new tests added? Yes. Same queries, same expected output (reference unchanged: 6 distinct rows + three count() = 6); the pin only removes the randomization blind spot.
e Both directions demonstrated? Yes. Unpatched: LOGICAL_ERROR abort in DistinctSortedStreamTransform::transform. Patched: output == reference. 04498 + 04499 pass 80/80 under randomization on both analyzers.
f Fix is general across code paths? N/A (test-determinism setting pin, not a code change).
g Fix generalizes across inputs? N/A (test-determinism setting pin, not a code change).
h Backward compatible? N/A (test-determinism setting pin, not a code change).
i Invariants and contracts preserved? N/A (test-determinism setting pin, not a code change).

Session id: cron:clickhouse-worker-slot-5:20260703-111800

Comment thread src/Interpreters/ConcurrentHashJoin.h Resolved
ConcurrentHashJoin::preservesLeftBlockOrder() returned twoLevelMapIsUsed(),
which is false for single-level maps (key8, key16, single non-nullable
LowCardinality). But with one slot (max_threads == 1, so slots == 1)
dispatchBlock short-circuits on num_shards == 1 and joinBlock passes the
left block through unscattered regardless of the map type, so order is
preserved. PlannerJoins::tryCreateJoin can build a ConcurrentHashJoin with
max_threads == 1, and the strict predicate then disabled read-in-order /
optimize_distinct_in_order / optimize_aggregation_in_order / LIMIT BY
in-order on a join that actually satisfies the contract.

Return `slots == 1 || twoLevelMapIsUsed()`. Add a focused max_threads = 1
key8 regression to 04498 asserting the in-order path fires again and stays
correct, alongside the existing multi-slot (gated) and two-level (fires)
cases.

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

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse-local / debug server: SELECT a, count() FROM t3 LEFT ALL JOIN t4 ON t3.j = t4.j GROUP BY a ORDER BY a SETTINGS join_algorithm='parallel_hash', max_threads=1, optimize_aggregation_in_order=1, optimize_read_in_order=1, query_plan_read_in_order=1, query_plan_read_in_order_through_join=1 with j UInt8 (key8). EXPLAIN shows no Read type: InOrder on the pre-fix binary (Build ID c760e2e0) and InOrder on the fixed binary (1c6359ff).
b Root cause explained? ConcurrentHashJoin::preservesLeftBlockOrder() returned twoLevelMapIsUsed(), false for single-level maps (key8/key16/single non-nullable LowCardinality). But slots = toPowerOfTwo(min(max_threads,256)) is 1 when max_threads == 1, and PlannerJoins::tryCreateJoin can build a ConcurrentHashJoin then. With slots == 1, dispatchBlock short-circuits on num_shards == 1 and joinBlock passes the left block through unscattered for any map type, so order IS preserved. The strict predicate wrongly reported non-preservation, so findReadingStep bailed and disabled read-in-order / optimize_distinct_in_order / optimize_aggregation_in_order / LIMIT BY in-order on a compliant join.
c Fix matches root cause? Yes. Predicate becomes `slots == 1
d Test intent preserved / new tests added? Yes. Existing multi-slot (gated, InOrder=0) and two-level (fires, InOrder>0) assertions unchanged. Added a focused max_threads=1 key8 block asserting the in-order path fires again (InOrder>0) AND correctness (8 per group).
e Both directions demonstrated? Yes. Pre-fix binary c760e2e0: max_threads=1 key8 InOrder=0. Fixed binary 1c6359ff: InOrder=1. max_threads=8 key8 stays InOrder=0 on both (CR#4 gate intact). 20 randomized-settings iterations match reference; both analyzers match.
f Fix is general across code paths? Yes. The single physical order-preservation authority for parallel_hash is ConcurrentHashJoin::preservesLeftBlockOrder(). slots == 1 covers every single-slot construction (PlannerJoins::tryCreateJoin, clone). The logical mirror (joinMayNotPreserveLeftBlockOrder, topKThroughJoin) is conservative and remains correct: it can only over-defer, never plant a sorted consumer unsafely; the physical gate is the correctness authority.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. slots is independent of key type, so the one-slot fast path holds for every map shape (key8/key16/single LowCardinality single-level AND two-level UInt64+). The multi-slot single-level gate (key8/key16/LowCardinality scatter) is untouched and still returns false; two-level still returns true. Boundary slots == 1 handled by the added regression.
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or new validation changed. Pure query-plan optimization enablement; the plan just regains read-in-order where it was already sound.
i Invariants and contracts preserved? Yes. preservesLeftBlockOrder() still exactly matches what joinBlock/dispatchBlock do at runtime: order preserved iff slots == 1 (unscattered) OR two-level map (unscattered). Both slots and the map type are fixed at build time, so the value is stable when optimizeReadInOrder queries it during plan optimization.

Session id: cron:clickhouse-worker-slot-2:20260703-125000

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c356addd3 with master cdc26e3bd (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b339930

Every failure below has an owner: a fixing PR (ours 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
Stress test (arm_debug) / generic Check failed with exit code 1 harness false red, not PR-caused. The server shut down slowly, so stop_server entered its 60 s grace branch, and the server then DID exit inside it. The recheck kill -s 0 "$pid" || return in tests/docker_scripts/stress_tests.lib uses a bare return, which yields the status of the kill that just failed because the process is gone, so the successful late shutdown returns 1 and fails the job. Corroborated by the run's own rows: Test script exit code OK, Server successfully started OK, Warning: server did not stop yet OK, no Possible deadlock on shutdown row, empty fatal.log, and hung_check.log ending No queries hung. a fix task is created (investigating at full effort - fixing PR link to follow on this pull request)
Bugfix validation (functional tests, amd64/aarch64) / 04209_top_k_through_join_read_in_order_gate + 04500_read_in_order_through_constant_join not a failure: these rows are the regression tests failing against the master binary as the Bugfix validation gate requires, and both checks report success -

Nothing else is red at this commit: Fast test, Fast test (arm_darwin), Style check, Bugfix validation (unit tests) and the other nine Stress test flavours are green, and Finish Workflow completed successfully.

Measured breadth for the harness row, 30 days over all Stress test (*) runs: five check runs across five distinct branches, one of them master, carry the pair (Warning: server did not stop yet OK, generic Check failed FAIL), and none of the five carries a Possible deadlock on shutdown row. That is the discriminator against the separate, already-tracked deadlock-on-shutdown red.

Session id: cron:our-pr-ci-monitor:20260828-070000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the generic Check failed with exit code 1 row on my CI finish ledger for Stress test (arm_debug): #116841. stop_server returned the failing kill -s 0 status on the branch that means the server did shut down, so stress_runner.sh aborted under set -e.

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Dear @vdimir, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze

Copy link
Copy Markdown
Member

This agentic fix looks related to this other agentic fix: #110671

@groeneai Replace the existing test cases by a simple test with a minimal reproducible example. Avoid slop (like "load-bearing") in all shapes and forms.

@harikrishnan94: The problem is real, could I ask you to take a look at the PR?

The three test files added by this PR covered every join algorithm that
touches the read-in-order-through-join gate. Most of those arms already
behaved correctly on master: partial_merge is covered by
04500_read_in_order_through_partial_merge_join, full_sorting_merge is
blocked by its own pre-JOIN sort, and the rest were EXPLAIN plan probes
rather than result oracles.

The only shape whose classification this change moves is parallel_hash
with a single-level map, which returns wrong results without it. That is
now the whole test: 04498_parallel_hash_read_in_order_through_join, one
query, 8 groups of 8 rows.

Measured with a debug build of this branch and a debug build of master:
10/10 runs pass with the fix, 5/5 runs fail on master under the test
runner's default randomization (the runner injected
query_plan_read_in_order_through_join=0, optimize_aggregation_in_order=0
and max_threads=1, all of which the query-level SETTINGS override, so the
defective path is exercised every run).

Source comments are trimmed to the local invariant. The comment in
FullSortingMergeJoin.h is dropped: it described the absence of an
override. The 04209 comment is corrected instead of extended, because
FullSortingMergeJoin no longer reports that it preserves the left order.

No behaviour change: the diff under src/ against the previous head is
comments only.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in c746029.

The three test files are replaced by one, 04498_parallel_hash_read_in_order_through_join: two small tables and a single query, 23 lines. Measured with debug builds of this branch and of master, it passes 10/10 runs here and fails 5/5 on master under the test runner's default randomization.

What I dropped: the partial_merge / prefer_partial_merge / full_sorting_merge arms, which were already correct on master and covered by 04500_read_in_order_through_partial_merge_join; the EXPLAIN PLAN probes; and the plan checks for the ConstantJoin and DirectKeyValueJoin opt-ins. The order-preserving direction is still asserted elsewhere: 03711_read_in_order_through_join pins the exact ReadType lists for hash and parallel_hash, and I confirmed it fails if either safe branch of ConcurrentHashJoin::preservesLeftBlockOrder is removed. Those two opt-ins now have no plan assertion, so tell me if you want one back.

Source comments went from 33 added lines to 12, and the one in FullSortingMergeJoin.h that only described the absence of an override is gone. The diff is +57/-10 over 10 files, down from +514/-12 over 15. I rewrote the description around the reproducer.

@harikrishnan94

harikrishnan94 commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

@groeneai Can confirm RIGHT/FULL join non joined processed rows are also taken care of?

@@ -0,0 +1,23 @@
-- `parallel_hash` does not keep the order of the left table for a narrow join key, so read-in-order

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 reduced repro is good for the parallel_hash wrong-result carrier, but the code in this PR also explicitly opts ConstantJoin and DirectKeyValueJoin back into read_in_order_through_join after flipping the IJoin default to fail-closed. I couldn't find a remaining focused FilledJoinStep probe for either path: 03711 proves HashJoin / ConcurrentHashJoin, and 04652_direct_join_dictionary_sparse_key keeps max_threads = 1 and does not pin the read-in-order settings, so it never exercises the same boundary.

Could we keep one small LEFT JOIN ... ON 1 = 1 or dictionary EXPLAIN / result probe alongside this repro? Otherwise those opt-ins are effectively untested on the current head.

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.

Correct for ConstantJoin and DirectKeyValueJoin: neither has a focused plan assertion on this head. That gap is already stated on the PR with a standing offer to add one, and the call is the reviewers': @ rschu1ze asked for the existing cases to be replaced by a single minimal reproducible example, so re-adding arms unasked would undo that. I will add exactly the probe that is asked for.

For the parallel_hash carrier the coverage is already in-tree: forcing ConcurrentHashJoin::preservesLeftBlockOrder to return false makes the existing 03711_read_in_order_through_join fail, with six ReadType lists flipping to Default while the 'hash' arm stays unchanged.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@harikrishnan94 Yes. The two mechanisms are disjoint on join kind, so a non-joined-rows stream is never present in a plan this PR's classification can affect.

findReadingStep gates read-in-order-through-join on isInnerOrLeft(kind) (optimizeReadInOrder.cpp:161, from 64e4306fa83; that file has a zero-line diff in this PR), and that conjunct precedes preservesLeftBlockOrder in the same &&, so for RIGHT/FULL the new fail-closed default is never evaluated. TableJoin::needStreamWithNonJoinedRows is the mirror predicate, returning isRightOrFull(kind()) (TableJoin.cpp:718). The only other consumer of preservesLeftBlockOrder is topKThroughJoin.cpp:130, reachable only under join_kind == JoinKind::Left (:404).

Measured on the test's two tables with parallel_hash, max_threads = 8, optimize_aggregation_in_order = 1, join kind as the only variable:

kind master ac95bf3c this branch
INNER InOrder, wrong (7 57) Default, correct
LEFT InOrder, wrong (7 57) Default, correct
RIGHT Default, correct Default, correct
FULL Default, correct Default, correct

RIGHT/FULL are identical on both arms, so as a check that this is not a blind probe I ran the same shape with the sort key on r (its own primary key) and only the kind changed: r as the left child of a LEFT join gets InOrder on master, r as the preserved side of RIGHT/FULL gets Default. The decline follows the kind, not the query shape.

The reduced test asserts only the parallel_hash carrier. If you want a negative plan assertion for RIGHT/FULL, or one for the ConstantJoin / DirectKeyValueJoin opt-ins, tell me which and I will add exactly that. I have not added them unasked because @ rschu1ze asked for the cases to be replaced by a single minimal reproducible example.

@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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c746029e98abca112e626cde5a4db04bc3a7656c

CI is fully finished on this head. 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, old analyzer, 5/6) / Container memory budget exceeded (/docker) /docker cgroup leaf OOM kills the concurrent shutdown gdb attaches; job ERROR, no test failed #117202 (external, merged 2026-08-31), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) same leaf OOM as above #117202 (external, merged 2026-08-31), absent from this tree; a fix task owns the 6/6 residual noted below
Integration tests (amd_tsan, 2/6) / Container memory budget exceeded (/docker) same leaf OOM as above #117202 (external, merged 2026-08-31), absent from this tree

All three rows are one signature, not three. The /docker cgroup leaf that bounds the nested
test containers is capped at 40.78 GiB, and docker compose stop signals every node of a
cluster at once, so each node that outlives the 60 s deadline attaches gdb at the same moment.
On an ASan build each attach holds about 3.4 GiB of anonymous memory, so a nine-node cluster asks
for roughly the whole leaf and the kernel kills the debuggers. #117202 serializes that attach.
It is merged, but it is outside the tree this run built: the fix symbol GDB_ATTACH_LOCK is
absent at c746029e98ab and present at the merge commit 7fc3004ed25a, and compare reports
this head behind that commit. So the run predates the fix. These rows clear when the branch next
picks master up. I am not merging master here purely to re-run CI, to keep the review load down.

Measured caveat, stated so it is not a surprise later: on true-master trees that DO contain
#117202, the 2/6 and 5/6 shards are clean (0 of 13 post-fix trees) but 6/6 still fires
(13 of 13, every one at 1214-1215 test rows with no failing test). So a 6/6 row may return
after the master merge. A fix task owns that residual and its fixing-PR link will be posted here
when one opens.

Bugfix validation (functional tests, amd64/aarch64) are green. Both carry a FAIL row for
04209_top_k_through_join_read_in_order_gate, which is this PR's own new test running against a
pre-fix binary, so that row is the intended proof the test reproduces the bug, not a failure.

Mergeable Check and PR are praktika aggregators. They report the rows above and carry no
separate defect. Config Workflow, Style check and CH Inc sync are all success on this head.

Session id: cron:our-pr-ci-monitor:20260831-203000

@rschu1ze

rschu1ze commented Sep 2, 2026

Copy link
Copy Markdown
Member

Let's merge from master and then merge @harikrishnan94

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master in: 728cc58

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 728cc58

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
Docs examples / Documentation examples trunk-side, and not reachable from this diff: 2104 of 2226 examples are ok and the one unexpected failure is Function/timeSeriesPrometheusValueToString#0, whose documented output box is one character wider than the box the server prints #117789 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Bugfix validation (functional tests, amd64/aarch64) is green on both arches; the FAIL rows CIDB
records for 04209_top_k_through_join_read_in_order_gate are that check's inverted semantics, i.e.
the new regression test correctly fails against the pre-fix binary.

Session id: cron:our-pr-ci-monitor:20260903-053000

@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 4, 2026
@harikrishnan94

Copy link
Copy Markdown
Contributor

@groeneai What is pending? Why the checks still failing? Make this PR merge-ready.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Nothing is pending on my side.

Of the 170 checks on 728cc58, one was red: Docs examples, which is also what Mergeable Check named as its blocker. It is not reachable from this diff. The documented output table of timeSeriesPrometheusValueToString was one character wider than the server prints; #117827 fixed that on master at 2026-09-03T09:33:59Z, while the Docs examples run here completed at 02:38:19Z the same day, so it predates the fix and has not re-run since. Docs examples has been green on every master run after that merge.

The other non-green entry is CH Inc sync ("build failed"), which is the private sync and not something I can act on.

To pick the fix up in the head itself I merged master cdc26e3b. New head: c356addd. The change is untouched by the merge: same 10 files, +57/-10. CI is running on the new head now.

@harikrishnan94
harikrishnan94 added this pull request to the merge queue Sep 5, 2026
Merged via the queue into ClickHouse:master with commit 1d6237c Sep 5, 2026
175 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 Sep 5, 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-request PR origin: a maintainer pinged or directed groeneai 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

7 participants