Skip to content

Fix wrong results of IN (subquery) and has for Interval values of different units - #126290

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:interval-units-in-subquery-and-has
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:interval-units-in-subquery-and-has

Conversation

@groeneai

@groeneai groeneai commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #126218
Related: #126263

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 wrong results of IN (subquery), has, indexOf, countEqual and related functions when the two sides are Interval values of different units: toIntervalSecond(90) IN (SELECT INTERVAL 1 MINUTE) returned 1 and has([INTERVAL 1 MINUTE], toIntervalSecond(60)) returned 0, also for Interval values inside the Tuple or Array elements of a constant array. accurateCast, accurateCastOrNull and accurateCastOrDefault between Interval units now reject a value the target unit cannot hold exactly (a remainder, an overflow, or months versus days and weeks) instead of truncating it; plain CAST still truncates. An IN (subquery) whose set column is a Tuple, Array or Map converts strictly, so such a value there now raises CANNOT_CONVERT_TYPE.

Description

On 26.8.18.2, over an IntervalNanosecond column holding one value per second, WHERE time IN (SELECT INTERVAL 510 MINUTE) returns 60 rows instead of 1, and WHERE has([INTERVAL 510 MINUTE], time) returns 0. WHERE time = INTERVAL 510 MINUTE returns 1.

Root cause:

  • IN: Set::execute casts the probe column to the set's type with castColumnAccurateOrNull, and a NULL means "not a member". For an Interval target the cast ignored the accurate mode: 90 seconds became 1 minute, an overflowing multiply wrapped, and 28 days became 1 month.
  • has family: the raw counts of the two units were compared, so 60 seconds never equalled 1 minute. Over a constant array this also happened inside Tuple and Array elements.

Change:

  • An accurate Interval to Interval cast between different units now rejects a value that has a remainder, overflows, or crosses the month boundary: accurateCast throws, accurateCastOrNull returns NULL. This fixes every IN variant and keeps the primary key analysis of the same set consistent with the runtime. A Tuple, Array or Map set column is converted strictly, as for other types (IN with a Tuple/Array set key rejects unparsable text at default settings #121232), so there such a value raises CANNOT_CONVERT_TYPE instead of matching.
  • has, notHas, indexOf, indexOfAssumeSorted, countEqual, mapContainsKey and mapContainsValue convert the needle to the element's unit with that cast, so a needle the unit cannot hold is not found. Over a constant array, a Tuple or Array element holding an Interval is compared in the common type, as over a non-constant array and by =.

Validation: the new test fails on master and passes with the fix.

🤖 Generated with Claude Code


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

groeneai and others added 5 commits October 16, 2026 09:40
`accurateCast` and `accurateCastOrNull` between two Interval kinds ignored
the cast type: finer to coarser truncated (90 seconds became 1 minute),
coarser to finer multiplied without an overflow check, and Day/Week to
Month/Quarter/Year used the approximate factor 4 weeks per month.

`Set::execute` casts the probe column to the set's element type with
`castColumnAccurateOrNull` and treats a NULL as "not a member", so every
`IN (subquery)` across Interval kinds matched values that are not equal:
`time IN (SELECT INTERVAL 510 MINUTE)` over an `IntervalNanosecond` column
counted all 60 values inside that minute. The same cast translates set
elements for the primary key in `KeyCondition`, so the index and the
runtime keep agreeing.

Now the accurate modes reject a value the target kind does not hold
exactly: a remainder, a multiplication overflow, or a pair of kinds across
the month boundary. `accurateCast` throws, `accurateCastOrNull` returns NULL.
Plain `CAST` keeps its truncating conversion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionArrayIndex` compared the raw counts of two Interval kinds, so
`has([INTERVAL 1 MINUTE], toIntervalSecond(60))` returned 0. This covers
`has`, `notHas`, `indexOf`, `indexOfAssumeSorted`, `countEqual`,
`mapContainsKey` and `mapContainsValue`.

Convert the needle to the element kind with the accurate cast; a needle the
element kind cannot hold exactly (a remainder or an overflow) is not found.
The array itself is not converted: converting a coarser array to a finer
kind can overflow, which would break the sorted order `indexOfAssumeSorted`
relies on. The `Array(LowCardinality(Interval))` path with a constant needle
already resolves the needle with the same cast, so both encodings now agree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the executeDifferentIntervalKinds header into two lines and drop the comment restating the not_representable mask.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
# Finding Verdict
⚠️ Keyed IN lines did not prove that the primary key analysis still applies the converted set (a silent decline would also return 1) AGREE, fixed: force_primary_key = 1 on those lines
⚠️ The strict conversion of a single Tuple / Array / Map set column was described but not tested AGREE, fixed: exact and inexact cases added for all three
💡 accurateCastOrNull(INTERVAL 0 DAY, 'IntervalMonth') is NULL DISAGREE: = refuses that pair (NO_COMMON_TYPE), so no membership answer can differ from it

Re-review of the fix commit: no findings.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test fails on every run on master (also 26.8.18.2): time IN (SELECT INTERVAL 510 MINUTE) counts 60, has([INTERVAL 510 MINUTE], time) 0, and both accurateCast error lines succeed.
b Root cause explained? Set::execute casts the probe to the set type with castColumnAccurateOrNull; the Interval cast ignored the accurate mode (truncating divide, unchecked multiply, 4 weeks per month), so it never returned NULL. FunctionArrayIndex compared raw counts of two units.
c Fix matches root cause? Yes. The accurate cast now rejects a remainder, an overflow and a month-boundary pair, which fixes every consumer of that cast at once (all IN variants, Set tables, primary key analysis of the set). The has family converts the needle with the same cast.
d Test intent preserved / new tests added? New 05407_interval_units_in_subquery_and_has.sql, with guard lines that must not change (exact matches, plain CAST, NO_COMMON_TYPE).
e Both directions demonstrated? Runner: FAIL on the master binary, OK on the fix. 50/50 randomized runs, parallel replicas (local plan 0 and 1) and Replicated database all OK. Removing each of the 7 checks turns the test red.
f Fix is general across code paths? One site per family: the shared accurate cast (Set, KeyCondition, KV-storage key lookups, shard pruning, accurateCast*), and executeArrayImpl, the funnel for constant, materialized, Map and stripped-LowCardinality haystacks.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked: Nullable, LowCardinality, Dynamic/Variant sources, Array(Nullable), Map keys/values, constant and non-constant needles, negative values, Int64 boundaries, every unit from nanosecond to year.
h Backward compatible? (maintainer-approved exception only) No setting or format change. Only accurateCast* between different Interval units changes (stated in the changelog entry); plain CAST, toInterval* and INSERT keep truncating. 455 related tests show no new failures against master.
i Invariants and contracts preserved? The cast returns input_rows_count rows (constness kept), Nullable only for accurateCastOrNull; rejected rows hold 0 under the null bit. The array is never converted, so indexOfAssumeSorted still gets sorted input; a genuine NULL needle keeps its null map.

Session id: cron:clickhouse-impl-self-slot-57:20261016-092600

@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6831a70]

Summary: ✅


AI Review

Summary

Makes accurate casts between Interval units reject inexact values and corrects interval membership comparisons in IN, has, and related functions, including composite elements. Reviewed head 6831a70afecc34a1cc51d94aba90d12c38b3c3ae; both prior findings are fixed, with no outstanding actionable findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nihalzp @CurtizJ, could you review this, and add can be tested (I currently cannot apply labels)? The accurate Interval to Interval cast that Set::execute uses for IN truncated instead of returning NULL, so x IN (SELECT INTERVAL 510 MINUTE) over nanoseconds matched 60 rows; has compared raw counts of different units.

@yariks5s yariks5s self-assigned this Oct 16, 2026
@yariks5s yariks5s added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Oct 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a0b651e

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 3/4) / Build ClickHouse master build break since af19343b2516, not from this PR (it does not touch the file): unit_tests_dbms does not compile, gtest_functions_stress.cpp:2367: error: value of type 'const ResolvedAddress' is not contextually convertible to 'bool'; no diagnostic in the files of this PR #126269 (external, open)
Finish Workflow / new_tests_check.py both functional Bugfix validation jobs were dropped because of the build failure above #126269 (the owner of the first row)
CH Inc sync - CH Inc sync (private, not actionable by me)
Mergeable Check, PR praktika rollups of the rows above #126269 (the owner of the first row)

The build failure dropped 106 dependent jobs, so no functional test has run on this head yet.

Session id: cron:our-pr-ci-monitor:20261016-133003

…ubquery-and-has

# Conflicts:
#	src/Functions/array/arrayIndex.h
Comment thread src/Functions/array/arrayIndex.h Resolved
…ts in the common type

A constant array is searched by comparing `Field`s, and the `Field` of an
`Interval` is the bare count of its own unit, so `has`, `indexOf`,
`indexOfAssumeSorted`, `countEqual` and `mapContainsKey` over a constant
array of `Tuple` or `Array` values compared the raw counts of two kinds:
`has([(INTERVAL 1 MINUTE, 7)], (toIntervalSecond(1), 7))` returned 1 and
the same search for `toIntervalSecond(60)` returned 0, while the
non-constant array (`materialize`) and `=` return 0 and 1.

Such a pair is now brought to its common type first, which is what the
non-constant path does, so both encodings of the haystack agree. The
top-level `Interval` element keeps its exact needle conversion.

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

clickhouse-gh Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6831a70af with master 4c45be687 (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.

Object file sizes

10 object files changed (+171.03 KiB total), 0 added.

Object file Master PR Δ
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/FunctionsMapMiscellaneous.cpp.o 5.16 MiB 5.19 MiB +37.18 KiB (+0.70%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/indexOfAssumeSorted.cpp.o 2.16 MiB 2.19 MiB +33.41 KiB (+1.51%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/countEqual.cpp.o 2.14 MiB 2.17 MiB +29.34 KiB (+1.34%)
src/Functions/array/CMakeFiles/clickhouse_functions_array.dir/indexOf.cpp.o 2.28 MiB 2.31 MiB +29.10 KiB (+1.25%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 24.64 MiB 24.66 MiB +24.64 KiB (+0.10%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

Comment thread src/Functions/array/arrayIndex.h Resolved
…rted

The previous commit compares a constant array of composite values that
hold an Interval in the common type of the array elements and the needle.
That cast multiplies a coarser Interval into the finer unit and can wrap
on overflow, so the cast array may no longer be sorted, while
`executeConst` binary-searches a constant needle for `indexOfAssumeSorted`:

    indexOfAssumeSorted([(toIntervalWeek(0), 7), (toIntervalWeek(20000), 7)],
                        (toIntervalNanosecond(0), 7))

returned 0 instead of 1 (the cast array is [(0,7),(-6350744073709551616,7)]).
`indexOf`, a materialized haystack and scalar Interval elements returned 1.

For `indexOfAssumeSorted` with a constant needle, search the single row of
the two constants as non-constant columns, which is a linear search, and
return the result as a constant (so constant folding is kept). A
non-constant needle is already searched linearly by `executeConst`.

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

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Dear @yariks5s, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@yariks5s yariks5s self-assigned this Nov 16, 2026

This branch has not been deployed

No deployments
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants