Skip to content

Fix bloom_filter index skipping rows for a Date32 constant compared with a DateTime column in another time zone - #128052

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:bloom-filter-date32-session-time-zone
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:bloom-filter-date32-session-time-zone

Conversation

@groeneai

@groeneai groeneai commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117318

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 bloom_filter skip index dropping rows when a Date32 constant is compared with an indexed DateTime column whose time zone differs from session_timezone (in =, has, hasAny, hasAll, indexOf, mapContains* and m['key'] = ...). Also fixed a missing map key equal to a date constant in m['key'] = ... making a mapKeys or mapValues index skip the row, a BAD_GET exception for a DateTime64 constant over a mapValues index, and wrong results or a TYPE_MISMATCH exception for a Variant or Dynamic constant holding a date.

Description

On 26.9.19.9, SELECT count() FROM t WHERE hasAny(arr, [toDate32('2024-01-02')]) over arr Array(DateTime('Europe/Moscow')) with INDEX bf arr TYPE bloom_filter and session_timezone = 'UTC' returns 0, while use_skip_indexes = 0 returns 1. Found by the TLP oracle of AST fuzzer (amd_release, oracle).

Root cause: the search functions compare a Date32 with a DateTime('tz') in their least supertype, DateTime64(0) without a time zone, i.e. in the session time zone. The index converted the constant straight to the element type with convertFieldToType (the column's time zone) and pruned the matching granule. For m['key'] = <date> it did not convert the constant for mapValues, and its missing-key check used the default of the constant's type. A Variant or Dynamic constant arrives as its member's value without the member's type, so a day number was read as seconds or the conversion threw TYPE_MISMATCH.

Change: convertConstantLikeSearchFunction converts a Date32 constant against a DateTime element through the same getLeastSupertype, then exactly back to DateTime (out of range: the index declines), at every probe site. For m['key'] = <date> both map indexes decline when a missing key's value equals the constant in that supertype. A Variant or Dynamic constant makes it decline for a date or time element. Pruning for typed constants is kept (1 of 10 granules read, not 0).

Validation: the new test fails on master (fifteen predicates return 0, three throw) and passes with the fix; 50/50 randomized runs; the bloom_filter stateless tests pass.

Not changed: dt IN (SELECT toDate32(...)) and a non-date constant equal to a missing key on the mapKeys path, both checked by #117318. Part pruning by statistics, the primary key and minmax still drop the row for a Dynamic(Date32) constant (KeyCondition, like #125914); the test turns statistics off for those two queries.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 28, 2026 11:18
…functions compare it

`equals`, `hasAny`/`hasAll`, and `has`/`indexOf`/`mapContains*` over a
non-LowCardinality element compare a `Date32` with a `DateTime('tz')` in
their least supertype, `DateTime64(0)` without a time zone, i.e. in the
session time zone. The `bloom_filter` index converted the constant straight
to the element type, and the `Date32 -> DateTime` conversion reads the date
in the column's time zone. With `session_timezone = 'UTC'` and a
`DateTime('Europe/Moscow')` column the index hashed midnight MSK while the
function compared midnight UTC, so the granule holding the match was pruned
(found by the AST fuzzer's TLP oracle on PR ClickHouse#112650).

Convert such a constant through the same `getLeastSupertype`, then strictly
back to `DateTime`; a date outside the `DateTime` range yields Null and the
index declines. The helper is used at every probe site that compares like
the search functions, with the same LowCardinality rule as the string
coercion. The `m['k'] = const` branch over `mapValues` hashed the constant
unconverted; a date constant is now converted there too, which also fixes
`BAD_GET` for a `DateTime64` constant, and the missing-key default is
re-checked on the converted value.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`mapContainsValue(mv, toDate32(..))` over a `mapValues` bloom_filter index
goes through the same `convertConstantForArrayIndexFunction` path as
`mapContainsKey`; on master it returns 0 instead of 1 here.

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

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

Pre-publication review by an independent model (engine: codex; 2 rounds, 1 finding) plus my own review (3 findings), at a8df0aa.

# Sev Finding Verdict Evidence / action
1 ⚠️ No mapContainsValue line; the test cannot tell pruning from a declined index AGREE in part, fixed @ a8df0aa mapContainsValue line added (0 on master, 1 with the fix). Declining is a correct outcome, so pruning was checked with EXPLAIN indexes = 1 per probe family locally (1 of 10 granules each), not asserted in the test
2 ⚠️ The mirror pair (a DateTime('tz') constant against a Date32 element) meets in the same supertype DROPPED unreachable: bloom_filter rejects a Date32 column, array element or map key/value on CREATE, ALTER ADD INDEX and ATTACH (assertIndexColumnsType)
3 ⚠️ The missing-key decline compares with getDefault(), which is 1900-01-01 for Date32 DROPPED same: no Date32 element; for the accepted types getDefault() is the column default

Not changed here: dt IN (SELECT toDate32(...)) is pruned through traverseTreeIn, where the set keeps its Date32 type; #117318's set type check makes the index decline there.

Severity: ❌ blocker / ⚠️ major / 💡 nit.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The new test (and the fuzzer's table) through clickhouse local: on master hasAny(arr, [toDate32('2024-01-02')]) returns 0 with the index and 1 without, every run.
b Root cause explained? The functions compare Date32 with DateTime('tz') in getLeastSupertype = DateTime64(0) in the session time zone; the index converted the constant directly to DateTime('tz'), reading the date in the column's time zone, so it hashed another instant and pruned the matching granule. The m['k'] = const values branch did not convert the constant at all.
c Fix matches root cause? Yes. The index now hashes the value the function compares, computed with the same getLeastSupertype; no guard, pruning kept (EXPLAIN indexes = 1: each changed probe family reads 1 of 10 granules instead of 0).
d Test intent preserved / new tests added? New test 05457_bloom_filter_date32_session_time_zone; no existing test changed.
e Both directions demonstrated? Master: one 1, eleven 0, then BAD_GET; with the fix: thirteen 1. With use_skip_indexes = 0 both builds print thirteen 1.
f Fix is general across code paths? All four probe sites that compare like the search functions use the helper; arrayJoin(col) = const declines this pair, literal IN and the mapKeys m[key] path were measured consistent, KeyCondition already converts through the supertype.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured Nullable/LowCardinality constants, LowCardinality(DateTime) columns, Map keys and values, tuple equality, reverse time-zone sign, dates outside the DateTime range (index declines), the missing map key default; Date, DateTime64 and Time pairs unchanged and consistent. The reverse pair (a Date32 element) is unreachable: bloom_filter rejects a Date32 column, array element or map key/value at DDL.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; a wrong probe becomes the right one or the index declines.
i Invariants and contracts preserved? The index contract (never prune a granule the predicate can match) now holds for this pair; the helper returns a null Field, the existing decline convention.

Session id: cron:clickhouse-impl-slot-4:20261028-114500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @shankar-iyer, could you review this and add the can be tested label so CI runs? The bloom_filter index converted a Date32 constant straight to the DateTime('tz') element type (the date read in the column's time zone), while =/has/hasAny compare in the DateTime64 supertype in the session time zone, so it hashed another instant and pruned matching granules; it overlaps the mapValues lines of #117318.

@clickhouse-gh

clickhouse-gh Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7965396]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Pipeline stuck. Current state: (STID: 4940-37c6) FAIL cidb

AI Review

Summary

The change fixes incorrect bloom_filter pruning when comparing Date32 constants with indexed DateTime values across time zones, including map defaults and Dynamic/Variant constants. Reviewed head 79653967b65f; both earlier findings are addressed, with no remaining actionable findings. The new regression test passes locally under ASan (19 expected results) and in 50 targeted CI runs. Broader CI remains in progress.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. labels Oct 28, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 28, 2026
…loom_filter index

The default check for `m['k'] = <date constant>` ran only on the `mapValues`
path, after the index was chosen, so a `mapKeys` index (alone or with a
`mapValues` index) still probed the absent key and pruned rows whose missing
key equals the constant, e.g. `m['missing'] = toDate32('1970-01-01')` over
`Map(String, DateTime('Europe/Moscow'))` under `session_timezone = 'UTC'`.

Run the check before the index is chosen and do it the way `equals` does:
the missing key's column default (zero, `1970-01-01`, also for `Date32`,
whose `getDefault` is `1900-01-01`) and the constant are compared in their
least supertype. The converted constant is still what the `mapValues` index
hashes. Only date-like constants over date-like map values are affected; a
non-date constant on the `mapKeys` path keeps the existing behaviour.

Reported by the automated review on the PR.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aed24fb

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
Stateless tests (arm_binary, parallel) / 05020_top_k_through_array_join_explain flaky, not from this PR (it changes only the bloom filter index and its own test): the EXPLAIN reference expects one granule, and the randomized index_granularity = 97 reads more. The runner's own diagnosis: 399/399 runs fail with these settings, 440/440 pass without them #128015 (mine, open)
Build profile diff infra, not from this PR: the read-only CI logs cluster never answered its readiness probe (LogClusterNotReady: the endpoint never became ready, raised in has_pr_data). The same error failed 569 runs on 330 PRs between 2026-10-26 18:19Z and 2026-10-28 18:02Z #126200 (mine, open)
Mergeable Check, PR praktika rollups of the 05020 row #128015 (the owner of the row above)

All 179 check runs completed and CH Inc sync passed. CIDB has exactly one FAIL test row on this head, the 05020 row above.

Session id: cron:our-pr-ci-monitor:20261028-203004

…-session-time-zone

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp
@clickhouse-gh

clickhouse-gh Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 79653967b with master b8fc8d44b (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

3 object files changed (+20.13 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp.o 512.41 KiB 532.52 KiB +20.12 KiB (+3.93%)

711 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

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

Job report

…stant

`RPNBuilderTreeNode::tryGetConstant` returns the `Field` of a `Variant` or
`Dynamic` constant's active member but keeps the wrapper as its type, so the
day number of a `Date`/`Date32` member (or the ticks of a `DateTime64` one)
reached `convertFieldToType` with no unit. Against a date-like index element
the index then either probed the day number as seconds and pruned matching
granules (`dt = CAST(toDate('2024-01-05') AS Dynamic)` returned 0 instead of
1, also through `m['k'] = ...`), or threw `TYPE_MISMATCH` while the condition
was prepared (`Date32` and `DateTime64` members, any `Variant(Date32, ...)`).
Both reproduce on master with default settings.

Decline the index for such a constant against a `Date`, `DateTime` or
`DateTime64` element in every path: the scalar and array conversions, a
`Variant`/`Dynamic` constant array, and the `m['k'] = ...` branch (both the
keys and the values index, since the missing-key check needs the constant's
type too). Pruning for typed date constants is unchanged.

Part pruning by statistics (and the primary key and `minmax` index) still drop
the row for a `Dynamic(Date32)` constant on master; that is `KeyCondition`'s
defect, tracked separately, so the two `Date32` test queries turn it off.

Reported by clickhouse-gh[bot] in
ClickHouse#128052 (comment)

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7965396

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Pipeline stuck (STID: 4940-37c6) fuzzer finding, not from this PR (it changes only the bloom_filter index's constant conversion, which is not on this path): the job's core dump shows MergingSortedTransform idle in NeedData after its always_read_till_end drain finished while another input still holds unpulled data. Same STID on 1 other PR in 30 days #116051 (mine, open)

Session id: cron:our-pr-ci-monitor:20261115-210011

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-skip-index Skipping indexes (minmax, set, bloom) and their evaluation. 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