Skip to content

Fix wrong ORDER BY with read-in-order when a String key column is compared with a FixedString constant - #123677

Merged
NIKTONIKTO717 merged 7 commits into
ClickHouse:masterfrom
aschoube:fix-read-in-order-fixedstring-constant
Oct 11, 2026
Merged

NIKTONIKTO717 merged 7 commits into
ClickHouse:masterfrom
aschoube:fix-read-in-order-fixedstring-constant

Conversation

@aschoube

@aschoube aschoube commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #123669
Related: #94017
Related: #117238

Read-in-order skipped sorting on a String key column compared with a FixedString constant, and returned rows in the wrong order:

CREATE TABLE t (k UInt8, s String) ENGINE = MergeTree ORDER BY (k, s);
INSERT INTO t VALUES (1, 'V0\0\0'), (1, 'V0'), (1, 'V0\0'), (2, 'X');

SELECT k, hex(s) FROM t WHERE s = toFixedString('V0', 3) ORDER BY k, s DESC;
-- 1  5630
-- 1  563000
-- 1  56300000      <- ascending, but DESC was requested

appendFixedColumnsFromFilterExpression treats the non-constant argument of every column = constant as fixed to a single value, and read-in-order then drops the fixed key column from the sort. That holds only when equals means the values are byte-identical. equals compares a String with a FixedString zero-padded, so s = toFixedString('V0', 3) holds for 'V0', 'V0\0' and 'V0\0\0'. These three values sort differently, so s is not fixed, and the step that is skipped is exactly the one that orders them. With LIMIT 1 the query returns 5630 instead of 56300000.

Change

equals no longer marks the column as fixed when the column is a String and the constant is a FixedString, also under Nullable and LowCardinality. Read-in-order then uses the key prefix before s and sorts s as usual.

Tuple values are compared element by element with equals, so the same applies inside a Tuple: t = tuple(toFixedString('V0', 3)) holds for tuple('V0'), tuple('V0\0') and tuple('V0\0\0'). The check recurses into Tuple elements and does not mark t as fixed if any String element is compared with a FixedString element. Array and Map values are cast to a common type and compared byte by byte, so they are not affected.

The check is deliberately narrow. A FixedString column compared with a String constant (fs = 'abc', the usual way to filter a FixedString key) still counts as fixed. All values of a FixedString(N) column have the same length, so at most one of them equals the padded constant. A String column compared with a String constant is a byte comparison and is not affected either. For both shapes EXPLAIN still shows the full k ASC, s DESC prefix, and the test checks it.

Test

05321_read_in_order_string_vs_fixed_string_constant covers String, Nullable(String) and LowCardinality(String) key columns with a FixedString constant, a String key column with Nullable(FixedString) and LowCardinality(FixedString) constants, a Tuple(String) key column with a Tuple(FixedString) constant, the LIMIT 1 case, and the Prefix sort description from EXPLAIN for three shapes: String vs FixedString (now k ASC), String vs String and FixedString vs String (both still k ASC, s DESC). On an unfixed master build the String and LowCardinality(String) results come back in ascending order, LIMIT 1 returns the wrong row and EXPLAIN shows k ASC, s DESC. With the fix every result matches optimize_read_in_order = 0.

Locally the test passes in every run under randomized settings, except the runs where the randomizer enabled parallel replicas: my single local server does not define the parallel_replicas cluster (CLUSTER_DOESNT_EXIST), which CI has. The 263 existing stateless tests matching read_in_order, in_order, fixed_string or fixedstring show no wrong-result diff; the ones that do not pass locally need clusters, datasets, system log tables or Python modules that my local server does not have.

Variant and Dynamic columns holding a FixedString, which 04674_key_condition_erased_fixed_string_constant from the issue also covers, are not handled here.

Benchmark

The change only affects query planning. The one shape it changes now sorts the rows that match the condition, which is what makes the result correct, so the cost is bounded by the number of matching rows.

clickhouse local, local release build, i5-1135G7. The table has 50M rows, ORDER BY (k, s), one part, and every seventh value has a trailing \0. Median of 11 interleaved runs, including about 70 ms of process startup. master is an unfixed build.

Query master this PR
WHERE s = toFixedString('12345', 6) ORDER BY k, s DESC (the fixed shape) 315 ms 311 ms
same with LIMIT 1 294 ms 319 ms
WHERE s = '12345' ORDER BY k, s DESC (String vs String) 82 ms 82 ms
FixedString(8) column, WHERE s = '12345' ORDER BY k, s DESC 77 ms 79 ms
WHERE k = 3 AND s = toFixedString('1', 2) ORDER BY k, s DESC 119 ms 124 ms

The LIMIT 1 row is the largest difference: the matching rows are sorted before the limit instead of being read in order. The two shapes that stay fixed are unchanged. On the same data, master returns the first four rows of the fixed shape as ['3132333435', '3132333435', '3132333435', '3132333435'], while this PR returns ['313233343500', '313233343500', '313233343500', '3132333435'], which is the requested DESC order.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a wrong ORDER BY result with optimize_read_in_order when a String key column is compared with a FixedString constant, for example WHERE s = toFixedString('a', 2). The comparison matches several values that differ only in trailing zero bytes, but the optimization treated the column as having one value and skipped sorting on it.


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

Version info

  • Merged into: 26.10.1.2116-master (included in 26.10 and later)

`appendFixedColumnsFromFilterExpression` treated every `column = constant`
as fixing the column to one value, so read-in-order skipped sorting on it.
`equals` compares a `String` with a `FixedString` zero-padded, so
`s = toFixedString('V0', 3)` matches `'V0'`, `'V0\0'` and `'V0\0\0'`, which
sort differently, and `ORDER BY k, s DESC` returned them in the wrong order.

Skip such a condition when the column is a `String` (also under `Nullable`
and `LowCardinality`) and the constant is a `FixedString`. A `FixedString`
column compared with a `String` constant still counts as fixed, since all
its values have the same length and at most one of them matches.

Closes: ClickHouse#123669
@clickhouse-gh clickhouse-gh Bot added comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... external Author is not a member of the ClickHouse organization labels Oct 3, 2026
@Ergus Ergus added the can be tested Allows running workflows for external contributors label Oct 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6adda56]

Summary: ✅


AI Review

Summary

This PR narrows optimize_read_in_order so a column = constant filter no longer treats a String-typed key as fixed when the constant is a FixedString and the comparison can match multiple distinct values. The added coverage for Nullable, LowCardinality, and Tuple-wrapped cases matches the scoped contract in the PR description, and I did not find any new correctness, safety, or performance issues in the current diff.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 5, 2026
Merge upstream commit 756552d,
including the `no-parallel-replicas` exclusion for
`05218_timeseries_alp_codec`. Preserve the existing read-in-order fix
and its regression test unchanged.

Related: ClickHouse#123677
Related: ClickHouse#123763
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123677&sha=20d3846994236af48dd6c0d7de94c83ba66be82a&name_0=PR

Co-authored-by: Copilot <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6adda566e with master 2e77cbc01 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 18b5a991f; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 778.13 MiB 778.83 MiB +720.47 KiB (+0.09%)

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

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

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

Job report

@NIKTONIKTO717 NIKTONIKTO717 self-assigned this Oct 8, 2026

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

First of all, thank you @aschoube for a great PR. I'd like to add a couple of words.
In general PR as it is right now, is fixing subset of potential queries with wrong results. I think contracts you provide in PR title/description hold and it closes the direct form. However, I don't think it closes the issue #123669 . That issue mentions test 04674_key_condition_erased_fixed_string_constant which includes cases with Variant(FixedString(3)) or Dynamic holding FixedString(3) which are not covered by this PR. Therefore I'd suggest 2 options, feel free to pick one of them:

  1. Relax "Closes: " to "Related: ", address comments and then I'll suggest to merge it as it is right now. Then I'll continue with a separate PR addressing other.
  2. Implement support for Variant/Dynamic as well. I did some draft and I think it should be manageable to cover following cases: read_in_order_string_vs_fixed_string_cases.sql . In case you pick this path, please ping me and I'll be happy to review it :) .

aschoube and others added 2 commits October 9, 2026 08:17
… check

Rename the check to `comparesStringWithFixedString`, use `removeLowCardinalityAndNullable`
and recurse into `Tuple` elements, which `equals` compares element by element. Test
`Nullable` and `LowCardinality` `FixedString` constants and a `Tuple(String)` key column.

Co-authored-by: Copilot <[email protected]>
@aschoube

aschoube commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

@NIKTONIKTO717 I went with option 1: the description now has Related: for #123669, and the comments are addressed. Variant/Dynamic are left to your separate PR.

@NIKTONIKTO717

Copy link
Copy Markdown
Member

I went with option 1: the description now has Related: for #123669, and the comments are addressed. Variant/Dynamic are left to your separate PR.

Thank you @aschoube for a nice fix!

@aschoube

Copy link
Copy Markdown
Contributor Author

Merged master to pick up the fix for 05316_secret_arguments_declared_by_engines, which was the only CI failure.

@aschoube

Copy link
Copy Markdown
Contributor Author

@NIKTONIKTO717 The test is flaky, can we do something about this ?

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-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... external Author is not a member of the ClickHouse organization 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

Development

Successfully merging this pull request may close these issues.

4 participants