Skip to content

compareTrackAt() - devirtualization for IColumn::compareAt() for merge sorted - #99013

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
4ertus2:compare_at_track
Mar 15, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
4ertus2:compare_at_track

Conversation

@4ertus2

@4ertus2 4ertus2 commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

IColumn::compareAt() is too slow when colled as virtual function in cycle. PR makes a tracked version of it. IColumn::compareTrackAt() return {-N, 0, N} instead of {-1, 0, 1}. It passes a cycle inside virtual call. Then it's possible for compiler to devirtualize compareAt() inside the function.

Changelog category (leave one):

  • Performance improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

add IColumn::compareTrackAt() for sorted merges


Note

Medium Risk
Touches the core IColumn comparison API and changes MergeJoin cursor advancement logic to skip multiple rows at once, so subtle ordering/null/NaN edge cases could affect join correctness even though behavior is intended to be equivalent.

Overview
Adds a new virtual IColumn::compareTrackAt() API that extends compareAt() to return a signed run length (e.g., -N/0/+N) so callers can advance over multiple strictly-less/greater rows in one call, enabling better devirtualization and fewer virtual calls.

Updates MergeJoin’s sorted-range matching to use compareTrackAt() on the first sort key and advance cursors via nextN() based on the returned magnitude, while keeping remaining key comparisons unchanged; also adjusts helper comparison code to return Int64 and removes the old per-step cursor compare helper. ColumnVector marks size()/compareAt() as final and provides a final override of compareTrackAt() for the devirtualization path.

Written by Cursor Bugbot for commit d5c3994. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.685

@4ertus2

4ertus2 commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Continuation of partial merge join optimizations #96922

base

after this PR:

Queries executed: 15.

localhost:9000, queries: 15, QPS: 0.234, RPS: 20739740.177, MiB/s: 376.660, result RPS: 2.339, result MiB/s: 0.000.

0%              4.187 sec.
10%             4.228 sec.
20%             4.242 sec.
30%             4.243 sec.
40%             4.256 sec.
50%             4.268 sec.
60%             4.278 sec.
70%             4.282 sec.
80%             4.296 sec.
90%             4.303 sec.
95%             4.303 sec.
99%             4.354 sec.
99.9%           4.354 sec.
99.99%          4.354 sec.

Comment thread src/Columns/IColumn.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

This is a great idea!

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 9, 2026
@alexey-milovidov alexey-milovidov self-assigned this Mar 9, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Changelog category

Change to performance improvement and make sure we have at least one automated performance test to show it.

@clickhouse-gh

clickhouse-gh Bot commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d5c3994]

Summary: ✅

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 9, 2026
@4ertus2

4ertus2 commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor Author

I've also tried std::visit + std::variant devirtualization. It's more general but less powerfull in this case

    using TypesVariant = std::variant<
        const IColumn *,
        const ColumnVector<Int32> *,
        const ColumnVector<UInt32> *,
        const ColumnVector<Int64> *,
        const ColumnVector<UInt64> *>;
    TypesVariant first_left_column;

    template <bool left_nulls, bool right_nulls>
    MergeJoinEqualRange getNextEqualRangeImpl(MergeJoinCursor & rhs)
    {
        if (atEnd() || rhs.atEnd())
            return MergeJoinEqualRange{position(), rhs.position(), 0, 0};

        return std::visit(
            [&] (const auto * first_column) -> MergeJoinEqualRange
            {
                while (true)
                {
                    int cmp = compareAtCursor<left_nulls, right_nulls>(rhs, *first_column);
                    if (cmp < 0)
                    {
                        next();
                        if (atEnd())
                            break;
                    }
                    else if (cmp > 0)
                    {
                        rhs.next();
                        if (rhs.atEnd())
                            break;
                    }
                    else if (!cmp)
                        return MergeJoinEqualRange{position(), rhs.position(), getEqualLength(), rhs.getEqualLength()};
                }
                return MergeJoinEqualRange{position(), rhs.position(), 0, 0};
            },
            first_left_column);
    }

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

@@ -122,7 +122,10 @@ int nullableCompareAt(const IColumn & left_column, const IColumn & right_column,
}
}

return left_column.compareAt(lhs_pos, rhs_pos, right_column, null_direction_hint);
if constexpr (track)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nullable columns bypass compareTrackAt when track=true

Medium Severity

When track=true, nullableCompareAt only calls compareTrackAt in the final non-nullable branch. All nullable code paths (both-nullable, left-nullable, right-nullable) still call compareAt, returning only {-1, 0, 1}. In getNextEqualRangeImpl, when nullable columns are present, nextN(-cmp) always advances by 1 instead of skipping multiple rows, silently defeating the optimization purpose of compareTrackAt.

Fix in Cursor Fix in Web

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.

@4ertus2, worth fixing or okay?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's expected for now. I didn't test it for nullable types yet. It requires a decision what to check in track first: nulls or values, how much of them to take in track and how to implement null&values track gracefully.

It's some king of future work I think. At least I have to update my TPC-H for nullable types and get some meditation over it.

@clickhouse-gh

clickhouse-gh Bot commented Mar 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.20% 83.80% +0.60%
Functions 20.40% 23.90% +3.50%
Branches 75.30% 76.40% +1.10%

PR changed lines: PR changed-lines coverage: 96.88% (93/96)
Diff coverage report
Uncovered code

@alexey-milovidov
alexey-milovidov merged commit 4dd540f into ClickHouse:master Mar 15, 2026
159 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 Mar 15, 2026
zlareb1 added a commit to zlareb1/ClickHouse that referenced this pull request Mar 17, 2026
PR ClickHouse#99013 added `IColumn::compareTrackAt` for devirtualized multi-row
skipping in partial-merge join. Two coverage gaps filled:

1. `04042_partial_merge_join_float_nan`: exercises
   `ColumnVector<Float64>::compareTrackAt` (ColumnVector.h:157) with
   `NaN`/`Inf` keys in `partial_merge` join. Verifies that `NaN` matches
   `NaN` (merge-join semantics: `compareAt` returns 0 for equal sort
   positions) and that track-skipping works correctly for floating-point
   keys including negative infinity.

2. `04043_partial_merge_join_multikey_track`: exercises
   `MergeJoin.cpp:327-340` — `compareTrackAt` on the first sort key
   forces `track > 1` on left runs that are strictly less than the right
   cursor; secondary keys then use regular `compareAt`. Verifies that
   multi-row skipping on key1 does not accidentally skip valid (key1,
   key2) matches.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@4ertus2

4ertus2 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor Author

I had very different results for the test on my laptop and server. So I rerun this bench with fully optimized tables on current master on server. The previous run in this PR was wtih not optimized tables. The results now are consistent with my laptops ones. And they are much better for fully optimized TPC-H tables

after OPTIMIZE FINAL

Queries executed: 77.

localhost:9000, queries: 77, QPS: 4.508, RPS: 399780068.670, MiB/s: 7260.510, result RPS: 45.077, result MiB/s: 0.001.

0%              0.212 sec.
10%             0.214 sec.
20%             0.214 sec.
30%             0.215 sec.
40%             0.215 sec.
50%             0.216 sec.
60%             0.217 sec.
70%             0.218 sec.
80%             0.220 sec.
90%             0.227 sec.
95%             0.229 sec.
99%             0.237 sec.
99.9%           0.279 sec.
99.99%          0.279 sec.

current default JOIN

Queries executed: 74.

localhost:9000, queries: 74, QPS: 2.618, RPS: 232183784.595, MiB/s: 4216.750, result RPS: 26.180, result MiB/s: 0.001.

0%              0.319 sec.
10%             0.338 sec.
20%             0.347 sec.
30%             0.353 sec.
40%             0.359 sec.
50%             0.368 sec.
60%             0.374 sec.
70%             0.380 sec.
80%             0.387 sec.
90%             0.406 sec.
95%             0.419 sec.
99%             0.497 sec.
99.9%           0.581 sec.
99.99%          0.581 sec.

So it looks like PMJ is faster if sourses (one or both) are already sorted by joining key. And much slower if we need sort them berore JOIN. Mainly cause it's a single-threaded part of the algorithm.

leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Jul 16, 2026
Covers compareTrackAt (devirtualized IColumn::compareAt for merge-sorted
join, PR ClickHouse#99013) which the existing partial_merge tests do not exercise:
- 04546: Float64/NaN/Inf keys (CompareHelper NaN handling, NaN=NaN match).
  NaN rows pinned last via isNaN() so ORDER BY is deterministic under
  randomized nan_direction_hint.
- 04547: multi-key sort, first-key multi-row track skipping interacting
  with secondary-key matching.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Covers compareTrackAt (devirtualized IColumn::compareAt for merge-sorted
join, PR ClickHouse#99013) which the existing partial_merge tests do not exercise:
- 04546: Float64/NaN/Inf keys (CompareHelper NaN handling, NaN=NaN match).
  NaN rows pinned last via isNaN() so ORDER BY is deterministic under
  randomized nan_direction_hint.
- 04547: multi-key sort, first-key multi-row track skipping interacting
  with secondary-key matching.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants