Skip to content

Add optimize_row_order_if_no_order_by (reopen #103919) - #104591

Merged
alexey-milovidov merged 170 commits into
masterfrom
optimize_row_order_if_no_order_by_v2
Oct 9, 2026
Merged

alexey-milovidov merged 170 commits into
masterfrom
optimize_row_order_if_no_order_by_v2

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 11, 2026 •

Copy link
Copy Markdown
Member

Reopen of #103919.

Closes: #103839

Adds the opt-in MergeTree setting optimize_row_order_if_no_order_by (default 0). When enabled, it applies optimize_row_order automatically to inserts into ordinary MergeTree-family tables, including ReplicatedMergeTree, with an empty sorting key (ORDER BY () / ORDER BY tuple()).

Changelog category (leave one):

  • Improvement

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

Add the opt-in optimize_row_order_if_no_order_by MergeTree setting. When enabled, it applies row order optimization automatically to inserts into ordinary MergeTree-family tables with an empty sorting key (ORDER BY () / ORDER BY tuple()).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented May 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [debb0ba]

Summary: ✅


AI Review

Summary

This PR adds the opt-in MergeTree setting optimize_row_order_if_no_order_by, wires it into insert and projection writes for empty-sorting-key ordinary MergeTree tables, documents it, and adds focused coverage for default-off behavior, explicit opt-in/opt-out, unsupported nested types, and the server-config precedence case. I re-checked the current diff plus the full prior PR discussion on 2026-10-07, and I did not find any new correctness, compatibility, or performance issues that still apply on the current head.

Final Verdict

✅ No actionable findings on the current head.

LLVM Coverage Report

Measured on commit debb0ba.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 69/112 (61.61%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 11, 2026
alexey-milovidov and others added 3 commits May 11, 2026 17:19
When `optimize_row_order_if_no_order_by` enables row reordering for tables without an explicit `ORDER BY`, the optimizer is exercised on columns it never saw before — including `Nullable(Tuple)`, `Nullable(Object)`, and similar wrappers around types whose `getDataAt` is not implemented.

`ColumnNullable::estimateCardinalityInPermutedRange` calls `getDataAt` on the nested column, which throws `NOT_IMPLEMENTED` for `ColumnTuple`, `ColumnObject`, non-contiguous `ColumnArray`, `ColumnMap`, `ColumnVariant`, and `ColumnLazy`. The throw propagates out of `INSERT` and crashes the user's query.

`getCardinalitiesInPermutedRange` now catches the `NOT_IMPLEMENTED` exception and falls back to the upper-bound estimate (`equal_range.size()`). The column is then treated as having all-distinct values and sorts last in the column-order selection, which is correct (just suboptimal). `updatePermutation` already works for these column types, so no further changes are needed.

Reproduces with: `INSERT` into a `MergeTree ORDER BY ()` table that has a `Nullable(Tuple(...))`, `JSON`, or `Tuple(Array(...))` column.

See #104591

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Required by the `02995_new_settings_history` test, which compares the live MergeTree settings against the 26.4.1 baseline and asks every addition since then to be listed under the corresponding version block in `SettingsChangesHistory.cpp`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…r_by

The previous test only verified the case where the new setting is set to `True` explicitly, which does not exercise the actual change this PR makes — the new default-on behavior when the setting is omitted.

Three tables are now created from the same input rows:

- `tab_explicit_on`: setting set to `True` explicitly.
- `tab_default`: setting omitted, should still optimize because the default is `1`.
- `tab_disabled`: setting set to `False`, should preserve insertion order.

The test asserts that the default-on table matches the explicit-on table row-for-row, and that the disabled table differs from both. A regression in the default would then surface, which the original test missed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ault

Several pre-existing tests use `ORDER BY tuple()` or `ORDER BY ()` and then read the table without an explicit `ORDER BY` clause, relying implicitly on the on-disk row order to match what was inserted. Enabling `optimize_row_order_if_no_order_by` by default reshuffles those rows for compression, which makes those tests produce different (but equally correct) output.

Each affected `CREATE TABLE` is annotated with `SETTINGS optimize_row_order_if_no_order_by = 0` so the test's original ordering contract is preserved without disabling the new default globally. Two `echoOn` reference files (`03247_generic_arrayMin_arrayMax_fixes`, `03591_optimize_prewhere_row_policy`) are regenerated because the `CREATE TABLE` statement itself is part of the expected output.

This is intentionally narrow: each test that locks down a specific row ordering opts itself out, and any new test that doesn't care still gets the optimization by default.

See #104591

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits May 11, 2026 23:52
The previous commit accidentally listed `optimize_row_order_if_no_order_by = 0`
twice in the `SETTINGS` clause of `03928_json_advanced_shared_data_bug.sql`.
Duplicate setting names are rejected, so the test would fail before the JSON
assertions. Keep a single entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
With `optimize_row_order_if_no_order_by = 1` (the new default) the
`MergeTreeDataWriter` invokes `RowOrderOptimizer` for tables created with
`ORDER BY ()`. Some column types (e.g. `Nullable(Tuple(...))`, `JSON`)
do not implement `getDataAt`, so `estimateCardinalityInPermutedRange` throws
`NOT_IMPLEMENTED`. The optimizer now catches that case and falls back to
treating the column as all-distinct.

Add a stateless test that exercises the fallback by inserting into
`MergeTree` tables with `ORDER BY ()`, `optimize_row_order_if_no_order_by = 1`
and these unsupported nested column types, asserting that `INSERT` succeeds.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
These tests use `MergeTree ORDER BY tuple()` (or `ORDER BY ()`) and rely on
the on-disk row order matching insertion order — protobuf/avro/JSON
roundtrips, `JSON` shared-data layouts, and one parallel-replicas dataflow
cache test. With the new default `optimize_row_order_if_no_order_by = 1`
they were failing because rows are reordered by the optimizer.

Add `optimize_row_order_if_no_order_by = 0` to each affected `MergeTree`
table definition.

Failures observed in:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104591&sha=0a633b4dfe530b6ab4e00196e21c25e5eebf1eb5&name_0=PR

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
…order_by

The history entry should use `false -> true` (not `true -> true`) so that
`compatibility = '26.4'` restores the previous default of disabled
automatic row reordering for tables without an explicit `ORDER BY`.

`MergeTreeSettings::applyCompatibilitySetting` walks the version map from
newest to oldest and applies `previous_value` for entries above the
requested compatibility version. With the previous `true, true` pair the
setting stayed enabled when older compatibility was requested, breaking
the contract.
…able_json

The integration test mirrors `tests/queries/0_stateless/03290_nullable_json.sql.j2`,
which was already updated to set `optimize_row_order_if_no_order_by = 0` on
the `MergeTree ORDER BY tuple()` tables that compare extracted JSON tuple
subcolumns by insertion order. The integration copy was missed.

With the new default enabled, the row order optimizer reshuffles rows by
column cardinality, so `SELECT json.d FROM test` no longer matches the
reference. Add the setting to both `MergeTree` table definitions so the
test reads rows in insertion order again.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104591&sha=60631413d680241e45cf1e1211801984aa7082b8&name_0=PR
…red data tests

A prior commit added `optimize_row_order_if_no_order_by = 0` to a few of the
`03554_json_shared_data_*` tests but missed the rest. The unfixed ones
inserted 45000 rows into a `JSON` column on a `MergeTree ORDER BY tuple()`
table. With the new default the row order optimizer is invoked on the
`JSON` column for every insert, slowing the tests enough to hit MSan
timeouts.

Add the setting to the seven remaining files so they keep the original
insertion order and run within the time budget.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104591&sha=60631413d680241e45cf1e1211801984aa7082b8&name_0=PR
The test does several inserts of millions of rows with codec(Delta, ZSTD(3))
and similar codecs. Under random settings (e.g. `max_insert_threads = 1`,
`min_bytes_to_use_direct_io = 1`) on debug builds, the test can exceed the
180-second flaky-check budget. The test was modified in this PR only to
disable the new `optimize_row_order_if_no_order_by` setting on its tables,
so the underlying test behavior is unchanged; the flaky check tripped
because modified tests are re-run with random settings.

CI: #104591
The new default `optimize_row_order_if_no_order_by = 1` triggers row order
optimization on inserts into tables declared with `ORDER BY tuple()`,
substantially slowing down those inserts (up to ~15x in some codec tests)
and changing on-disk data layout, which affects downstream SELECT queries.

These perf tests measure raw insert / codec / format throughput and were
designed to use the "no sorting key" form, so disable the new optimization
at the table level to keep the measurements comparable to master.

CI: #104591
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The AST fuzzer failure (Inconsistent AST formatting between 'ExpressionList' and 'ExpressionList') is unrelated to this PR — it reproduces on a query that has optimize_row_order_if_no_order_by = 0 in its settings and is exercising a pre-existing AST formatting inconsistency around NOT (...) / tuple(...). This is tracked in #104605 ("More inconsistent AST formatting"). @groeneai, please investigate and provide a fix in a separate PR if needed.

alexey-milovidov and others added 2 commits May 13, 2026 07:07
…_no_order_by

Both tests were modified by this PR only to disable the new
`optimize_row_order_if_no_order_by` default at the table level. They
were not previously in the flaky check, but adding the `SETTINGS`
clause causes them to be picked up and re-run with random settings.

- `00825_protobuf_format_map.sh` fails under random
  `map_serialization_version=with_buckets` because that storage
  representation reorders Map keys on read. The expected reference
  encodes the original `{'x':5,'y':7}` key order.
- `03759_distinct_json_paths_optimization.sql.j2` already iterates over
  six `JSON` shared-data serializations and times out (~600s) under the
  random debug-build settings the flaky check applies on top of that.

CI: #104591

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
These tests create `MergeTree` tables with `ORDER BY tuple()`, then
populate them and benchmark `SELECT`s over the result. With the new
default `optimize_row_order_if_no_order_by = 1`, the row-order
optimizer reorders rows on insert, changing on-disk codec compression
ratios and the layout the join probe scans — substantially shifting
the measurements (`codecs_int_select` showed up to ~+318% on some
codecs in the PR's performance comparison) without measuring anything
the tests are designed to measure.

CI: #104591

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits September 25, 2026 16:44
…if_no_order_by_v2

# Conflicts:
#	tests/performance/text_index_build.xml
`create_query_engine` and `find_table_settings_keyword` scanned from the
start of the statement, so a table, database, or cluster name that reads
like a clause keyword (`CREATE TABLE engine ...`, `CREATE TABLE settings
... SETTINGS ...`, `CREATE TABLE comment.t ...`) was taken for syntax, and a
quoted engine name (`ENGINE = \`MergeTree\``) was not recognised.

Add `skip_create_table_head` (`CREATE [OR REPLACE] [TEMPORARY] TABLE
[IF NOT EXISTS] [db.]name [UUID '...'] [ON CLUSTER cluster]`, also with
`ATTACH` / `REPLACE`) and start both scans after it; parse the engine name
with `skip_identifier`, unquoting a quoted one.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…if_no_order_by_v2

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits October 3, 2026 07:25
…if_no_order_by_v2

Resolve modify/delete conflict on `tests/integration/test_nullable_tuple_subcolumns/queries/03290_nullable_json.sql`: master removed the whole integration test, so the PR's pin is dropped with it.
Comment thread tests/performance/scripts/perf.py Resolved
alexey-milovidov and others added 2 commits October 5, 2026 02:17
…` pins

The setting is opt-in now (default `0`) and is not randomized by
`clickhouse-test`, so the explicit `= 0` pins in unrelated performance and
stateless tests no longer change anything. Restore those tests to their
`master` versions.

Without the pins in performance tests, the reference server never sees the
unknown setting, so the `CREATE TABLE` rewriter that stripped it
(`perf_create_query_utils.py`, its unit test, and the retry in `perf.py`) is
no longer needed and is removed.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the review: dropped the no-op optimize_row_order_if_no_order_by = 0 pins and the perf DDL rewriter. The PR diff is now limited to the feature, its docs, and its own tests (35 files instead of 168). The 3 new stateless tests pass locally.

The earlier CI failures are not related to this change (the setting is off by default):

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104591&sha=latest&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 (TLP Aggregate oracle mismatch on quantileExactWeightedInterpolated(0.) over the decimal table; the same mismatch also shows up on master, e.g. 2026-09-23, and in PRs #116800, #117612, #118229) and provide a fix in a separate PR. If the fix is already in progress, link it here.

…row_order_if_no_order_by`

Regenerated with `ci/jobs/scripts/docs/autogenerate/autogenerate_docs.py --write`
from a binary built from this branch, keeping only the entries for the new
setting (the rest of the regenerated drift comes from master and is unrelated).

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

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

The cause is in the oracle, not in this PR. The TLP Aggregate rewrite builds <agg>Merge(_s_N) without the original aggregate's parameters (QueryOracleChecker.cpp#L2245). A -Merge function takes its parameters from its own call, not from the state type, so quantileExactWeightedInterpolatedMerge(_s_0) over a quantileExactWeightedInterpolatedState(0.) state returns the default level 0.5. Every other quantile* is on the oracle's deny-list, which hides this; quantileExactWeightedInterpolated is deliberately not listed (L149-L154).

On master 468fbe0b, with the decimal table from 03240_quantile_exact_weighted_interpolated: reference -16.66666666, -50, metamorphic 0, 0. The same metamorphic query with quantileExactWeightedInterpolatedMerge(0.)(...) returns -16.66666666, -50. All five sightings in CIDB over the last 60 days, including the master one, are this function at a level other than 0.5.

No fix is in progress. I'll open a separate PR that passes the original parameters to the -Merge call and link it here.

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Fix: #124149. It passes the aggregate's parameters to the -Merge call. With that, the oracle also compares parametric aggregates it used to skip (their parameterless -Merge threw), so the ones whose State/Merge result depends on row or tie order (groupArraySample, groupFormat, hierarchicalKMeans, MVTEncode, sequenceMatch/sequenceCount/sequenceMatchEvents/sequenceNextNode, argAndMin/argAndMax) go on the deny-list. quantileExactWeightedInterpolated stays checked.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai: the oracle fix is in #124149, so this PR needs no change for the TLP Aggregate mismatch. CI on the current head is otherwise green. I fixed the CH Inc sync failure by hand: I resolved the merge conflicts in the private sync branch and pushed it (the PR's diff there is the same as the public diff).

alexey-milovidov and others added 2 commits October 7, 2026 04:59
# Conflicts:
#	docs/_site/customizations/settings-legacy-routes/mergetree-settings.js
#	docs/snippets/components/MergeTreeSettingsExplorer/MergeTreeSettingsExplorer.jsx
The group lists 55 settings after `optimize_row_order_if_no_order_by` was added, but the count stayed at 54 after the master merge. This also made the `CH Inc sync` merge conflict.

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

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync failed because the incremental sync could not merge this PR: the conflict was in the generated MergeTreeSettingsExplorer.jsx. The Other group count had stayed at 54 after the last master merge, but the group lists 55 settings. I fixed the count here and merged both private master and this PR into the sync branch by hand. The sync PR is now being re-tested.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass of 2026-10-08 on head debb0ba69c6f: all public CI checks are green, and there are no unresolved review threads. The only red check is CH Inc sync (tests failed (1 new, 5 known)), and it is not caused by this PR:

Once #124580 is merged, merging master here should clear CH Inc sync.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The CH Inc sync failure (tests failed (1 new, 5 known)) does not come from this PR. The new failure is 05218_autopr_set_building_plan_is_left_alone: it hits TOO_MANY_ROWS when it reads system.text_log, and #124580 is open to fix it. The other failures are known flaky tests: mutation tests timing out under MSan, and 01168_mutations_isolation. I reran the failed jobs of the private sync run. Public CI is green and there are no unresolved review threads.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is really good. And thanks to attention to details!

This branch was successfully deployed

1 active deployment
staging - docs — debb0ba6 Deployed Oct 7, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-improvement Pull request with some product improvements pr-performance Pull request with some performance improvements 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.

When a table has no ORDER BY key, we should use optimize_row_order by default

5 participants