Skip to content

Backport #113291 to 26.5: Fix for virtual row is not being applied in some cases - #114219

Merged
vdimir merged 7 commits into
26.5from
backport/26.5/113291
Aug 14, 2026
Merged

vdimir merged 7 commits into
26.5from
backport/26.5/113291

Conversation

@robot-clickhouse-ci-2

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Original pull-request #113291

This pull-request is a last step of an automated backporting.
Treat it as a standard pull-request: look at the checks and resolve conflicts.
Merge it only if you intend to backport changes to the target branch, otherwise just close it.

The PR source

The PR is created in the CI job

Version info

  • Merged into: 26.5.7.49

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added pr-backport Changes, backported to release branch. Do not use manually - automated use only! pr-bugfix Pull request with bugfix, not backported by default labels Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [BackportPR], commit [050b8a6]

Summary: ✅

Comment thread src/Functions/FunctionsConversion.h Resolved
@vdimir

vdimir commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

@groeneai could you please apply the relevant fixes to this branch? I applied these changes to a single branch, and now we need to reapply them to other versions:

Adapting the backport of "Fix for virtual row is not being applied in some cases" (upstream #113291)

The automated cherry-pick applies the hunks whose context matches and silently drops the rest — no conflict markers,
so the loss only shows up as a build or test failure. Work through the steps below.

0. Find the dropped hunks

For every file in the backport commit:

git show <backport-commit> --stat            # file list
git diff master -- <each source file>        # anything from the PR missing here was dropped

master is the source of truth for the files the PR owns. Large diffs in FunctionsConversion.h and
optimizeReadInOrder.cpp are pre-existing divergence — only check that the PR's own hunks are present there.

1. Restore the MergingSortedAlgorithm bookkeeping

Symptoms: use of undeclared identifier 'FieldVisitorDump', use of undeclared identifier 'is_virtual_row',
-Wpointer-bool-conversion on isVirtualRow. The two virtual_row_boundary sizing lines do not break the build
but make the debug checks index an empty vector.

--- a/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.h
+++ b/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.h
@@ -75,6 +75,9 @@ private:
     void insertRow(const SortCursorImpl & current);
     void insertRows(const SortCursorImpl & current, size_t num_rows);
     void insertChunk(size_t source_num);
+
+    /// Per-input pending virtual-row boundary (empty when none), used for debug checks to ensure virtual rows are placed correctly.
+    std::vector<Columns> virtual_row_boundary;
 };
--- a/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp
+++ b/src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp
@@ -1,6 +1,8 @@
 #include <Processors/Merges/Algorithms/MergeTreeReadInfo.h>
 #include <Processors/Merges/Algorithms/MergingSortedAlgorithm.h>
 #include <Processors/Transforms/ColumnGathererTransform.h>
+#include <Columns/IColumn.h>
+#include <Common/FieldVisitorDump.h>
 #include <IO/WriteBuffer.h>
 #include <IO/WriteHelpers.h>
 #include <IO/WriteBufferFromString.h>
@@ -14,6 +16,7 @@ namespace DB
 namespace ErrorCodes
 {
     extern const int ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER;
+    extern const int LOGICAL_ERROR;
 }
@@ -130,6 +132,7 @@ void MergingSortedAlgorithm::addInput()
 {
     current_inputs.emplace_back();
     cursors.emplace_back();
+    virtual_row_boundary.emplace_back();
 }
@@ -149,6 +152,7 @@ void MergingSortedAlgorithm::initialize(Inputs inputs)
     removeConstAndSparse(inputs);
     merged_data.initialize(*header, inputs);
     current_inputs = std::move(inputs);
+    virtual_row_boundary.assign(current_inputs.size(), {});
 
     for (size_t source_num = 0; source_num < current_inputs.size(); ++source_num)
     {
@@ -188,7 +192,8 @@ void MergingSortedAlgorithm::initialize(Inputs inputs)
 
 void MergingSortedAlgorithm::consume(Input & input, size_t source_num)
 {
-    if (isVirtualRow(input.chunk))
+    bool is_virtual_row = isVirtualRow(input.chunk);
+    if (is_virtual_row)
     {
         auto pk_block = setVirtualRow(input.chunk, *header, apply_virtual_row_conversions);

Verify with git diff master -- src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp — it must come out
empty — rather than by trusting the hunks to apply cleanly.

2. If DateLUTImpl::hasFixedOffset is missing

grep -rn "hasFixedOffset" src/Common/DateLUTImpl.h

If absent, ToStringMonotonicity cannot detect a fixed-offset time zone, so report DateTime as non-monotonic:

--- a/src/Functions/FunctionsConversion.h
+++ b/src/Functions/FunctionsConversion.h
@@ -3985,11 +3985,9 @@ struct ToStringMonotonicity
         /// `DateTime` is formatted in the time zone of the type, and local time decreases when the clocks are
         /// turned back, so the order is preserved only if the time zone never changes its offset.
-        if (const auto * date_time_type = checkAndGetDataType<DataTypeDateTime>(type_ptr))
+        if (checkAndGetDataType<DataTypeDateTime>(type_ptr))
         {
-            if (!date_time_type->getTimeZone().hasFixedOffset())
-                return not_monotonic;
-            return {.is_monotonic = true, .is_always_monotonic = true, .is_strict = true};
+            return not_monotonic;
         }

Then drop the t_utc part of 04695_to_string_monotonicity, which covers exactly the fixed-offset case — the
DROP TABLE and the expected output included:

--- a/tests/queries/0_stateless/04695_to_string_monotonicity.sql
+++ b/tests/queries/0_stateless/04695_to_string_monotonicity.sql
@@ -20,16 +20,6 @@ SELECT toString(toDateTime(1636264799, 'America/New_York')), ...
 SELECT toString(x) FROM t_dst ORDER BY toString(x) SETTINGS optimize_read_in_order = 1;
 
--- A fixed-offset time zone preserves order, and `toString` is strict there, so `y` stays in the prefix.
-DROP TABLE IF EXISTS t_utc;
-CREATE TABLE t_utc (x DateTime('UTC'), y UInt32) ENGINE = MergeTree ORDER BY (x, y);
-INSERT INTO t_utc SELECT toDateTime(1636264798 + intDiv(number, 4), 'UTC'), number % 4 FROM numbers(20);
-
-SELECT count() FROM t_utc WHERE toString(x) >= '2021-11-07 06:00:00';
-SELECT trimLeft(explain) FROM (
-    EXPLAIN PLAN SELECT * FROM t_utc ORDER BY toString(x), y SETTINGS optimize_read_in_order = 1
-) WHERE explain LIKE '%sort description%';
-
 DROP TABLE IF EXISTS t_date;
@@ -31,5 +21,4 @@
 DROP TABLE t_time;
 DROP TABLE t_dst;
-DROP TABLE t_utc;
 DROP TABLE t_date;
--- a/tests/queries/0_stateless/04695_to_string_monotonicity.reference
+++ b/tests/queries/0_stateless/04695_to_string_monotonicity.reference
@@ -15,8 +15,5 @@
 2021-11-07 01:59:59
-12
-│  Prefix sort description: toString(x) ASC, y ASC
-│  Result sort description: toString(x) ASC, y ASC
 │  Prefix sort description: toString(d) ASC, y ASC
 │  Result sort description: toString(d) ASC, y ASC

3. Drop settings the tests use that do not exist yet

grep -c max_bytes_ratio_before_external_join src/Core/Settings.cpp
grep -c join_runtime_filter_min_probe_rows   src/Core/Settings.cpp

A missing setting fails the whole test with UNKNOWN_SETTING (code 115) at the SET. Two tests are affected:

--- a/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql
+++ b/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql
@@ -20,3 +20,3 @@
-SET max_bytes_ratio_before_external_join = 0, max_bytes_before_external_join = 0, query_plan_read_in_order_through_join = 1, join_runtime_filter_min_probe_rows = 0;
+SET max_bytes_before_external_join = 0, query_plan_read_in_order_through_join = 1;
--- a/tests/queries/0_stateless/04029_join_convert_to_fixed_hash_table.sql
+++ b/tests/queries/0_stateless/04029_join_convert_to_fixed_hash_table.sql
@@ -19,3 +19,3 @@
-SET max_bytes_before_external_join = 0, max_bytes_ratio_before_external_join = 0; -- Disable automatic spilling for this test
+SET max_bytes_before_external_join = 0; -- Disable automatic spilling for this test

4. If EXPLAIN PLAN does not default to pretty output

grep -c explain_query_plan_default src/Core/Settings.cpp

If the setting is absent, EXPLAIN PLAN defaults actions, compact and pretty to false, while on master
checkAndGetSettings in src/Interpreters/InterpreterExplainQuery.cpp forces all three on. The reference files were
generated in the pretty format, so the same query otherwise yields analyzer-qualified names (__table1.name),
CAST(__table1.name, \'Nullable(String)\'_String) instead of CAST(name AS Nullable(String)), and the label
ReadType: instead of Read type: (ReadFromMergeTree.cpp keys it on format_settings.pretty); a plain
EXPLAIN PLAN prints no sort descriptions at all.

Request the options explicitly instead of regenerating the references, so the references stay byte-identical to
master. All nine EXPLAINs in 04672_read_in_order_virtual_row_sort_prefix.sql:

-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT ...
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT ...

and the option-less EXPLAIN in 04695_to_string_monotonicity.sql:

-    EXPLAIN PLAN SELECT * FROM t_date ORDER BY toString(d), y SETTINGS optimize_read_in_order = 1
+    EXPLAIN PLAN actions = 1, compact = 1, pretty = 1 SELECT * FROM t_date ORDER BY toString(d), y SETTINGS optimize_read_in_order = 1

If the pretty/compact options themselves do not exist (grep -n "bool pretty" src/Processors/QueryPlan/QueryPlan.h),
this is unavailable and the references have to be regenerated for the old format — note that in the commit message,
since the references then no longer match master.

5. If Monotonicity.ToNullable fails

./src/unit_tests_dbms --gtest_filter='*Monotonicity*:*ConversionMonotonic*'
gtest_monotonic.cpp:100: Value of: function_base->hasInformationAboutMonotonicity()  Actual: false  Expected: true

The gtest comes with this PR, but the overrides it asserts on were added to master by an unrelated commit,
"Fix expression check in convertOuterJoinToInnerJoin"
(git log -S getMonotonicityForRange master -- src/Functions/toNullable.cpp). The other three cases
(assumeNotNull, ifNull, coalesce) pass. Either delete the ToNullable case, or forward-port the hunk:

--- a/src/Functions/toNullable.cpp
+++ b/src/Functions/toNullable.cpp
@@ -53,6 +53,13 @@ public:
         return makeNullableOrLowCardinalityNullable(arguments[0].column);
     }
 
+    bool hasInformationAboutMonotonicity() const override { return true; }
+
+    Monotonicity getMonotonicityForRange(const IDataType &, const Field &, const Field &) const override
+    {
+        return { .is_monotonic = true, .is_positive = true, .is_always_monotonic = true, .is_strict = true };
+    }
+
 #if USE_EMBEDDED_COMPILER

Take only this hunk; the same commit also drops final from FunctionToNullable and adds a join test, both out of
scope. Forward-porting lets index analysis and read-in-order see through toNullable, which the rest of the
backport does not rely on — 04672 writes its Nullable cases as ::Nullable(String), which resolves to CAST.

Verification

./tests/clickhouse-test -b ./clickhouse --test-runs=1 \
  02149_read_in_order_fixed_prefix 03257_reverse_sorting_key \
  03262_common_expression_optimization 04029_join_convert_to_fixed_hash_table \
  04058_explain_pretty_aggregation_sorting \
  04672_read_in_order_virtual_row_sort_prefix 04695_to_string_monotonicity

./src/unit_tests_dbms --gtest_filter='*Monotonicity*:*ConversionMonotonic*'   # 12/12

ninja unit_tests_dbms clickhouse covers both the gtest and the server. if constexpr (do_debug_checks) bodies are
type-checked even in release builds, so a release compile is enough to catch step 1, but the gtest needs a build with
tests enabled.

If you sweep for fallout from step 5, read_in_order nullable monotonic index_analysis is a useful selector set.
Discount local failures caused by the environment rather than the change: missing stateful datasets (test.hits,
test.visits, code 60), no cluster for the distributed index analysis tests, file and object storage inputs for the
format tests, and replicated engines that need a disk with keeper metadata type (code 36).

@groeneai

Copy link
Copy Markdown
Collaborator

I cannot push to backport/26.5/113291 (it lives in ClickHouse/ClickHouse and I have no push bit, maintainerCanModify=false), so the adapted patch is below for you to apply.

Two things first, because they change what steps 1-5 are needed for.

Step 1 is already fully applied on this branch. Your section-0 check comes out clean for it: git diff master -- src/Processors/Merges/Algorithms/MergingSortedAlgorithm.cpp is empty, and so are MergeTreeReadInfo.h, gtest_monotonic.cpp, gtest_conversion_monotonic.cpp, 04672 (both files) and the 04695 reference.

The current build break is not a dropped hunk, it is the shape of your own step-2 hunk. All 7 builds fail with 18 errors, one signature:

src/Functions/FunctionsConversion.h:3987:26: error: variable 'date_time_type' set but not used
  [-Werror,-Wunused-but-set-variable]

ddfbef7e63feb55 kept if (const auto * date_time_type = checkAndGetDataType<...>) while your write-up and 12f5e2feee2a903 on 26.6 use the variable-free form. 26.6 builds 7/7 with that form, which isolates it.

04695's t_utc removal is incomplete here. ddfbef7 dropped the comment, DROP IF EXISTS, CREATE and INSERT, but left the two t_utc queries and DROP TABLE t_utc, so the test dies with Code: 60 ... 't_utc'. The reference still carries the three t_utc lines too. 26.6 has the same remnant (DROP TABLE t_utc), which is its 04695 CI failure.

Two corrections to the procedure for these branches:

  • Step 3: max_bytes_ratio_before_external_join does exist on 26.5 and 26.6 (DECLARE(Double, max_bytes_ratio_before_external_join, 0.5, ...), and SET succeeds on stock 26.5.7.46). Only join_runtime_filter_min_probe_rows is missing. So 04672 needs just that one setting dropped, which makes its SET line byte-identical to merged 26.7, and 04029 needs no change at all.
  • Step 4: compact and pretty do exist on 26.5 (QueryPlan.h:75,77), so the explicit-options route works and the references stay byte-identical to master. Confirmed on stock 26.5: a plain EXPLAIN PLAN yields 0 sort-description rows, actions = 1, compact = 1, pretty = 1 yields them.

For step 5 I took the delete-the-case option rather than forward-porting, because #110121 is labelled pr-performance with no backport label, and 26.7 has that hunk only because f5b78f99d9179ae predates its branch point (it is not an ancestor of 26.5 or 26.6). Forward-porting a monotonicity override into two release branches looked like your call rather than mine, so say the word and I will send that variant instead.

Patch against e1e0b1be (5 files, +12/-47):

265-adaptation.patch
diff --git a/src/Functions/FunctionsConversion.h b/src/Functions/FunctionsConversion.h
index 9c1707c9cf9d387..d40f3cf5f54e393 100644
--- a/src/Functions/FunctionsConversion.h
+++ b/src/Functions/FunctionsConversion.h
@@ -3984,7 +3984,7 @@ struct ToStringMonotonicity
 
         /// `DateTime` is formatted in the time zone of the type, and local time decreases when the clocks are
         /// turned back, so the order is preserved only if the time zone never changes its offset.
-        if (const auto * date_time_type = checkAndGetDataType<DataTypeDateTime>(type_ptr))
+        if (checkAndGetDataType<DataTypeDateTime>(type_ptr))
         {
             return not_monotonic;
         }
diff --git a/src/Functions/tests/gtest_monotonic.cpp b/src/Functions/tests/gtest_monotonic.cpp
index 1cfc29c769081fa..6d2e8883a9d8122 100644
--- a/src/Functions/tests/gtest_monotonic.cpp
+++ b/src/Functions/tests/gtest_monotonic.cpp
@@ -81,29 +81,3 @@ TEST(Monotonicity, Coalesce)
 {
     testNullWrapperMonotonicity("coalesce", {std::make_shared<DataTypeUInt8>(), std::make_shared<DataTypeUInt8>()});
 }
-
-TEST(Monotonicity, ToNullable)
-{
-    /// `toNullable` only wraps the value, so it is strictly increasing on the whole range of any argument type.
-    const DataTypes argument_types = {
-        std::make_shared<DataTypeUInt8>(),
-        std::make_shared<DataTypeString>(),
-        makeNullable(std::make_shared<DataTypeString>()),
-        std::make_shared<DataTypeLowCardinality>(std::make_shared<DataTypeString>()),
-    };
-
-    for (const auto & argument_type : argument_types)
-    {
-        SCOPED_TRACE(argument_type->getName());
-
-        auto function_base = buildFunction("toNullable", {argument_type});
-        ASSERT_TRUE(function_base->hasInformationAboutMonotonicity());
-
-        const auto monotonicity = function_base->getMonotonicityForRange(*argument_type, Field{}, Field{});
-
-        ASSERT_TRUE(monotonicity.is_monotonic);
-        ASSERT_TRUE(monotonicity.is_positive);
-        ASSERT_TRUE(monotonicity.is_always_monotonic);
-        ASSERT_TRUE(monotonicity.is_strict);
-    }
-}
diff --git a/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql b/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql
index 3ca17919507bee4..da290bc2e149ba5 100644
--- a/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql
+++ b/tests/queries/0_stateless/04672_read_in_order_virtual_row_sort_prefix.sql
@@ -18,50 +18,50 @@ INSERT INTO dict VALUES ('r1', 'l1'), ('r2', 'l2'), ('r3', 'l3');
 INSERT INTO by_day VALUES ('2020-01-01', 1), ('2020-01-01', 2), ('2020-01-02', 1);
 
 SET optimize_read_in_order = 1, read_in_order_use_virtual_row = 1;
-SET max_bytes_ratio_before_external_join = 0, max_bytes_before_external_join = 0, query_plan_read_in_order_through_join = 1, join_runtime_filter_min_probe_rows = 0;
+SET max_bytes_ratio_before_external_join = 0, max_bytes_before_external_join = 0, query_plan_read_in_order_through_join = 1;
 SET query_plan_optimize_join_order_limit = 1, query_plan_optimize_join_order_randomize = 0, query_plan_join_swap_table = 0;
 
 SELECT '--- single table: sorting key (name, code)';
 
 SELECT '-- plain key';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY name, code LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY name, code LIMIT 5) WHERE e != '';
 
 SELECT '-- cast on the only column';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY name::Nullable(String) LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY name::Nullable(String) LIMIT 5) WHERE e != '';
 
 SELECT '-- cast on the first of two columns';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY name::Nullable(String), code LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY name::Nullable(String), code LIMIT 5) WHERE e != '';
 
 SELECT '-- cast on the last of two columns';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY name, code::Nullable(String) LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY name, code::Nullable(String) LIMIT 5) WHERE e != '';
 
 SELECT '-- toString on the first of two columns';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY toString(name), code LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY toString(name), code LIMIT 5) WHERE e != '';
 
 SELECT '-- non-key column last';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM ev ORDER BY name, code, ref LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM ev ORDER BY name, code, ref LIMIT 5) WHERE e != '';
 
 SELECT '--- non-strictly monotonic function: the prefix is cut after it';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0 SELECT * FROM by_day ORDER BY toStartOfMonth(d), num LIMIT 5) WHERE e != '';
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1 SELECT * FROM by_day ORDER BY toStartOfMonth(d), num LIMIT 5) WHERE e != '';
 
 SELECT '--- INNER JOIN: read-in-order needs the virtual row';
 
 SELECT '-- cast on the first of two key columns';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1
     SELECT ev.name, ev.code, dict.label FROM ev INNER JOIN dict ON ev.ref = dict.ref
     ORDER BY ev.name::Nullable(String), ev.code LIMIT 5) WHERE e != '';
 
 SELECT '-- right table column last';
 SELECT extract(explain, '(?:Prefix sort description|Read type|Virtual row conversions).*') AS e
-FROM (EXPLAIN PLAN actions = 1, indexes = 0
+FROM (EXPLAIN PLAN actions = 1, indexes = 0, compact = 1, pretty = 1
     SELECT ev.name, ev.code, dict.label FROM ev INNER JOIN dict ON ev.ref = dict.ref
     ORDER BY ev.name, ev.code, dict.label LIMIT 5) WHERE e != '';
 
diff --git a/tests/queries/0_stateless/04695_to_string_monotonicity.reference b/tests/queries/0_stateless/04695_to_string_monotonicity.reference
index 6b482e0810e554d..4b818857bcd8709 100644
--- a/tests/queries/0_stateless/04695_to_string_monotonicity.reference
+++ b/tests/queries/0_stateless/04695_to_string_monotonicity.reference
@@ -15,8 +15,5 @@
 2021-11-07 01:59:57
 2021-11-07 01:59:58
 2021-11-07 01:59:59
-12
-│  Prefix sort description: toString(x) ASC, y ASC
-│  Result sort description: toString(x) ASC, y ASC
 │  Prefix sort description: toString(d) ASC, y ASC
 │  Result sort description: toString(d) ASC, y ASC
diff --git a/tests/queries/0_stateless/04695_to_string_monotonicity.sql b/tests/queries/0_stateless/04695_to_string_monotonicity.sql
index 4d255e070adf058..1bf4d6c0f27ff81 100644
--- a/tests/queries/0_stateless/04695_to_string_monotonicity.sql
+++ b/tests/queries/0_stateless/04695_to_string_monotonicity.sql
@@ -20,21 +20,14 @@ SELECT toString(toDateTime(1636264799, 'America/New_York')), toString(toDateTime
 SELECT count() FROM t_dst WHERE toString(x) >= '2021-11-07 01:59:00';
 SELECT toString(x) FROM t_dst ORDER BY toString(x) SETTINGS optimize_read_in_order = 1;
 
-
-SELECT count() FROM t_utc WHERE toString(x) >= '2021-11-07 06:00:00';
-SELECT trimLeft(explain) FROM (
-    EXPLAIN PLAN SELECT * FROM t_utc ORDER BY toString(x), y SETTINGS optimize_read_in_order = 1
-) WHERE explain LIKE '%sort description%';
-
 DROP TABLE IF EXISTS t_date;
 CREATE TABLE t_date (d Date, y UInt32) ENGINE = MergeTree ORDER BY (d, y);
 INSERT INTO t_date SELECT toDate('2021-01-01') + intDiv(number, 4), number % 4 FROM numbers(20);
 
 SELECT trimLeft(explain) FROM (
-    EXPLAIN PLAN SELECT * FROM t_date ORDER BY toString(d), y SETTINGS optimize_read_in_order = 1
+    EXPLAIN PLAN actions = 1, compact = 1, pretty = 1 SELECT * FROM t_date ORDER BY toString(d), y SETTINGS optimize_read_in_order = 1
 ) WHERE explain LIKE '%sort description%';
 
 DROP TABLE t_time;
 DROP TABLE t_dst;
-DROP TABLE t_utc;
 DROP TABLE t_date;

Validated on stock release binaries, using 26.7.4.25 as the fix-present arm (positive control: 26.7's own 04695 passes byte-exactly on it):

04672 04695
branch files as-is Code: 115, 46 ref-diff lines Code: 60, 8 ref-diff lines
patched 0 errors, ref diff empty 0 errors, ref diff empty

For the compile fix I reproduced both shapes with clang-21 under -Weverything -Werror: the variable form errors, the variable-free form is clean, and the resulting block is byte-identical to 26.6's.

The same patch applies to #114220, with two differences in 04695: its .sql needs only the DROP TABLE t_utc line removed (the queries were already taken there), and its .reference still carries the same three t_utc lines, so that trim is needed on 26.6 as well. Its FunctionsConversion.h is already in the variable-free form, so it does not need the compile fix.

@vdimir

vdimir commented Aug 13, 2026

Copy link
Copy Markdown
Member

@groeneai can you create your branch on top of this in your fork, I'll cherry pick form there then

Three things the automated cherry-pick left in a state that does not build or
pass on 26.5.

FunctionsConversion.h: the DateTime branch of ToStringMonotonicity binds a
variable it never reads, which is -Wunused-but-set-variable and therefore an
error under -Weverything -Werror. All 7 Build (*) jobs fail with this one
signature, 18 times. Dropping the binding makes the block byte-identical to
the same block on 26.6.

04695_to_string_monotonicity: the t_utc table was removed from the setup but
two queries against it and its DROP were left behind, so the test aborts with
UNKNOWN_TABLE. Its .reference still carried the three corresponding lines.

04672 and 04695: join_runtime_filter_min_probe_rows does not exist on 26.5, so
the SET raises UNKNOWN_SETTING before any assertion runs. Only that one clause
is removed; max_bytes_ratio_before_external_join does exist here, so the
resulting SET line is byte-identical to the merged 26.7 backport, and
04029_join_convert_to_fixed_hash_table needs no change at all.
explain_query_plan_default is also absent on 26.5, so instead of pinning it the
EXPLAIN PLAN calls pass compact = 1, pretty = 1 explicitly, which keeps the
expected output byte-identical to master.
The case asserts hasInformationAboutMonotonicity() on toNullable, but that
monotonicity was not added by #113291. It came from #110121, which is labelled
pr-performance and carries no backport label, so 26.5 does not have it and the
assertion fails under asan_ubsan and tsan.

Deleting the one case is the smaller change. Forward-porting the toNullable
monotonicity to 26.5 instead is the alternative; that is a call for the release
owner, so this is a separate commit and can be dropped on its own.
@groeneai

Copy link
Copy Markdown
Collaborator

Pushed: groeneai:groeneai/backport-26.5-113291-adaptation

Two commits on top of e1e0b1bebcf7341, 5 files, +12/-48. Split so you can drop the second one on its own.

1. Adapt the backport (1c3baa0)

  • FunctionsConversion.h: the DateTime branch binds date_time_type and never reads it, which is -Wunused-but-set-variable under -Weverything -Werror. That is the only reason all 7 Build (*) jobs fail, 18 times, one signature. Dropping the binding makes the block byte-identical to 26.6's. Verified both directions in a real 26.5 build here: pre-fix form rc=1 with that exact error, this form rc=0.
  • 04695: the t_utc setup was removed but two queries against it and its DROP were left, so the test aborts with UNKNOWN_TABLE. Its .reference still carried the 3 matching lines.
  • 04672: only join_runtime_filter_min_probe_rows comes out. max_bytes_ratio_before_external_join does exist on 26.5, so the resulting SET line is byte-identical to the merged 26.7 backport, and 04029 needs no change at all.
  • explain_query_plan_default is absent on 26.5, so instead of pinning it the EXPLAIN PLAN calls pass compact = 1, pretty = 1 explicitly. ExplainPlanOptions has both on 26.5, so the references stay byte-identical to master.

2. Monotonicity.ToNullable (e21d172): deleted, as the smaller change. The case asserts monotonicity that came from #110121, not from #113291, and #110121 is pr-performance with no backport label and is not an ancestor of 26.5. If you would rather forward-port that monotonicity to toNullable.cpp, say so and I will replace this commit; that is your call and it is the one thing here I did not decide.

A/B on stock per-branch binaries, 26.7.4.25 as the fix-present arm: unpatched, 04672 aborts with Code 115 and 04695 with Code 60, so neither reaches its assertions; patched, both run clean with an empty reference diff.

Unrelated to this branch, but found while checking it and worth your judgement since it is your code: toString reports isInjective() = true unconditionally for NameToString (FunctionsConversion.h:2952), so read-in-order treats a DateTime sorting-key column as fixed under a toString equality even when two distinct instants share one formatted string.

CREATE TABLE t_dst (x DateTime('America/New_York'), y UInt32) ENGINE = MergeTree ORDER BY (x, y);
INSERT INTO t_dst VALUES (toDateTime(1636261200,'America/New_York'), 7), (toDateTime(1636264800,'America/New_York'), 3);
SELECT y FROM t_dst WHERE toString(x) = '2021-11-07 01:00:00' ORDER BY y SETTINGS optimize_read_in_order = 1;

Both rows format as 2021-11-07 01:00:00. That returns 7, 3; with optimize_read_in_order = 0 it returns 3, 7. Identical on stock 26.5.7.46 (pre-fix), stock 26.7.4.25 and master (both post-fix), so #113291 did not introduce it and I left it alone rather than change behaviour inside a backport.

@vdimir
vdimir merged commit 7b1d9bb into 26.5 Aug 14, 2026
35 checks passed
@vdimir
vdimir deleted the backport/26.5/113291 branch August 14, 2026 10:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backport Changes, backported to release branch. Do not use manually - automated use only! pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants