Skip to content

Add tests for in-order optimizations and primary key analysis over a CAST into Bool - #129683

Merged
Manerone merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-cast-to-bool-monotonicity
Nov 18, 2026
Merged

Manerone merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-cast-to-bool-monotonicity

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129731
Related: #129642

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Test-only follow-up to #129731, which fixed the monotonicity of a CAST into Bool (Bool is a UInt8 with a custom name, so the cast reused the strictly monotonic UInt8 metadata, although it is x != 0).

The existing test covers ORDER BY ... LIMIT and DISTINCT over CAST(u, 'Bool'). This one adds GROUP BY and LIMIT BY in order, sorting by input stream properties, the fixed key from WHERE CAST(u, 'Bool') = true, a Bool ALIAS column, an EXPLAIN check that only the cast is used as a sort prefix, and a DateTime64 sorting key CAST(ts AS Bool) with a row before 1970, which is the only test of the cleared is_always_monotonic_where_defined (the primary key analysis skipped that row). The comment in createFunctionBaseCast now also says why that flag is cleared.

Validation (debug build): with the Bool branch of createFunctionBaseCast removed, the server aborts with Equal values are not contiguous within the range assumed to be sorted and the DateTime64 query loses the 1969 row; with this branch the test passes 50/50 with randomized settings.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2734-master (included in 26.11 and later)

`Bool` is a `UInt8` with a custom name, so `createFunctionBaseCast` gave a
CAST into `Bool` the monotonicity of the cast into `UInt8`. For a `UInt8`
source that is the identity (strictly monotonic), and for a `DateTime64`
source it is "monotonic where defined", which relies on the `UInt8`
conversion throwing outside of its range. The cast into `Bool` is `x != 0`:
it maps 1 and 2 to the same value, and it never throws, so it is not
monotonic across the epoch (-1 -> true, 0 -> false, 1 -> true).

The false `is_strict` let read in order, aggregation / DISTINCT / LIMIT BY in
order, sorting by input stream properties and fixed key columns from a
`CAST(u, 'Bool') = c` filter trust an order by the following keys that does
not hold, so `ORDER BY CAST(u AS Bool), k LIMIT 1` over a `(u, k)` key
returned a row with a wrong `k` (and DISTINCT / LIMIT BY hit the
"Equal values are not contiguous" assertion in debug builds). The false
`is_always_monotonic_where_defined` let the primary key analysis push
`ts <= c` through a `CAST(ts AS Bool)` sorting key and skip rows before 1970.

Clear both flags for a `Bool` target. Every remaining claim of the `UInt8`
metadata holds for `x != 0`, so the cast is still a non-strict sorting
prefix and is still used for primary key pruning.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ DateTime64 arm passes with primary-key analysis disabled; add EXPLAIN indexes = 1 granule assertions and a pruning positive control DISAGREE Red on master (1 row instead of 2, Granules: 1/3) and with the is_always_monotonic_where_defined line removed; passing with no index is the correct result. UInt8 to Bool pruning is unchanged (Granules: 1/4 before and after), and dropping the monotonicity fails the Prefix sort description arm.
2 💡 WHERE CAST(u, 'Bool') = true arm can be pruned wrongly by the separate skip-apply defect of #116656 at index_granularity 1 or 2 noted Not this code; about 3e-5 per randomized run; a failure there would be that real bug.
3 💡 A Bool to Bool cast loses its strict flag noted Correctness unaffected; no known query shape relies on it.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261106-054900

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT CAST(u, 'Bool') AS b, k ... ORDER BY b, k LIMIT 1 over a (u, k) sorting key with rows (1, 100), (2, 0) returns true 100 every run on master b51445e, 26.3.60.2 and 26.10.2.103; optimize_read_in_order = 0 gives true 0.
b Root cause explained? Bool is a UInt8 with a custom name, so createFunctionBaseCast installed ToNumberMonotonicity<UInt8>, which says identity (strict) for a UInt8 source and monotonic-where-defined for DateTime64. The cast into Bool is x != 0: not injective, never throws, not monotonic across the epoch.
c Fix matches root cause? Yes. The metadata is fixed where it is chosen (the only place that knows the target is Bool); the two false flags are cleared, nothing is added.
d Test intent preserved / new tests added? New 05556_cast_to_bool_is_not_injective_in_order: ORDER BY + LIMIT, Bool ALIAS, fixed key from WHERE, GROUP BY / DISTINCT / LIMIT BY in order, input stream sorting, DateTime64 primary key, and an EXPLAIN arm for the one-column sorting prefix.
e Both directions demonstrated? All 9 arms fail on master (DISTINCT and LIMIT BY hit the Equal values are not contiguous debug assertion) and pass with the fix. Mutations: no monotonicity reddens the prefix arm; keeping either flag reddens its own arms.
f Fix is general across code paths? createFunctionBaseCast is the only CAST constructor, so CAST, ::, _CAST (ALIAS, view, INSERT) and accurateCast are covered. toBool has no monotonicity; Bool is the only custom-named numeric type whose conversion changes values.
g Fix generalizes across inputs (params/datatypes/wrappers)? Nullable(Bool), LowCardinality(Bool), LowCardinality(Nullable(Bool)) targets, Nullable(UInt8) / LowCardinality(UInt8) sources and DESC were wrong on master and are fixed. accurateCastOrNull, Int8, UInt16, Bool sources were already correct; toUInt8 / CAST(u, 'UInt8') keep their strict prefix.
h Backward compatible? (maintainer-approved exception only) Yes. Planning metadata only: no setting, format or stored data. Read in order on the Bool prefix and pruning through it are kept (WHERE CAST(u, 'Bool') = false reads 1/4 granules).
i Invariants and contracts preserved? The monotonicity reported for a cast into Bool holds for x != 0 on the queried range, checked per source branch of ToNumberMonotonicity<UInt8>; the change only removes claims.

Session id: cron:clickhouse-impl-slot-4:20261106-045100

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @antaljanosbenjamin, could you review this and add the can be tested label so CI runs? Bool is a UInt8 with a custom name, so a cast into Bool reused the UInt8 cast monotonicity, which claims strictness for a UInt8 source although the cast is x != 0, so read in order kept the following sort keys and returned a wrong row; the fix clears is_strict and is_always_monotonic_where_defined for a Bool target.

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [535cc79]

Summary: ✅


AI Review

Summary

Reviewed PR head 535cc79778ea05d437c9eb14a352ebab4c48b471 and all prior discussion. This follow-up adds regression coverage for in-order optimizations over a CAST into Bool, including GROUP BY, DISTINCT, LIMIT BY, an ALIAS column, fixed filter keys, sorting-prefix propagation, and DateTime64 primary-key pruning before the epoch. The only C++ change explains the existing monotonicity flags. No actionable findings. The new stateless test passed in Fast test for this commit.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 535cc7977 with master 0bfadae35 (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

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

Job report

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

The fix is correct, but master already has it: #129731 (merged) added the same branch to createFunctionBaseCast, extended to SimpleAggregateFunction(f, Bool) (src/Functions/FunctionsConversion.cpp:3549 on master). That is why this PR now conflicts.

The test is still worth landing. Master's test only covers ORDER BY ... LIMIT and DISTINCT over CAST(u, 'Bool'). This one adds GROUP BY and LIMIT BY in order, sorting by input stream properties, the fixed key from WHERE, the ALIAS column, the EXPLAIN prefix check, and the DateTime64 pre-epoch pruning arm, which is the only coverage of is_always_monotonic_where_defined for Bool.

To land it as a test-only PR:

  1. Merge master and take master's side of createFunctionBaseCast. The DateTime64 sentence of your comment ("unlike the cast into UInt8 it does not throw for a DateTime64 outside of the UInt8 range") would be a good addition to master's comment, which only explains the non-injectivity, not why is_always_monotonic_where_defined is cleared.
  2. Renumber the test: 05556 is now taken by 05556_cast_to_simple_aggregate_function_bool.
  3. Change the category to Not for changelog and drop the entry. #129731's entry already covers the wrong rows from in-order optimizations over a CAST into Bool, and with a test-only diff the bug-fix validation would run the new test on a master build that already has the fix and go red.
  4. Retitle accordingly, e.g. "Add tests for in-order optimizations and primary key analysis over a CAST into Bool".

Happy to approve after that.

groeneai and others added 2 commits November 18, 2026 11:42
…notonicity

# Conflicts:
#	src/Functions/FunctionsConversion.cpp
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Fix wrong results of in-order optimizations and primary key analysis over a CAST into Bool Add tests for in-order optimizations and primary key analysis over a CAST into Bool Nov 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, done:

  1. Merged master and took master's createFunctionBaseCast; the only src/ change left is the DateTime64 sentence added to its comment: 59e2fb8
  2. Renumbered the test to 05829_cast_to_bool_is_not_injective_in_order: 535cc79
  3. Category is now Not for changelog, entry dropped.
  4. Retitled as suggested.

Checked on the new head (debug build): with the Bool branch of createFunctionBaseCast removed, the test still aborts the server on Equal values are not contiguous within the range assumed to be sorted and the DateTime64 query loses the 1969 row; with master's code it passes 50/50 with randomized settings.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Nov 18, 2026
@clickhouse-gh clickhouse-gh Bot added comp-testing Test content only (no production code). and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 18, 2026
@Manerone
Manerone added this pull request to the merge queue Nov 18, 2026
Merged via the queue into ClickHouse:master with commit 4026b8b Nov 18, 2026
201 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 18, 2026
@clickhouse-gh clickhouse-gh Bot added comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... and removed comp-testing Test content only (no production code). labels Nov 22, 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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... 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