Skip to content

Include the formatdatetime_* settings in the query condition cache key - #117803

Merged
alexey-milovidov merged 18 commits into
masterfrom
query-condition-cache-formatdatetime-settings-117308
Sep 14, 2026
Merged

alexey-milovidov merged 18 commits into
masterfrom
query-condition-cache-formatdatetime-settings-117308

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

The query condition cache key is the table UUID, the part name and a hash of the condition's ActionsDAG. The formatdatetime_* and parsedatetime_* settings change how formatDateTime and parseDateTime evaluate and leave no trace in the DAG, so two queries with the same condition text but different values of such a setting shared one entry:

-- primes the cache with "no marks match" (the condition matches no row under this value)
SELECT count() FROM t WHERE formatDateTime(d, '%f') = '0' SETTINGS formatdatetime_f_prints_single_zero = 0;  -- 0
-- served that verdict, although every row matches under this value
SELECT count() FROM t WHERE formatDateTime(d, '%f') = '0' SETTINGS formatdatetime_f_prints_single_zero = 1;  -- 0, should be 1000000

The settings are now folded into the condition hash by queryConditionCacheSettingsSalt. Every producer of the key has to apply it, or a verdict written by one query is never found by the next one (the existing 03229_query_condition_cache_profile_events catches exactly that), so the salt goes through the shared queryConditionCacheHash at all five of them: the WHERE plan tag, the PREWHERE writer, the index-analysis exclusion writer, the read side, and the file/object storage path.

The salt is the single registration point for every setting of this class, so it also covers the other settings that a function captures at build time, that change the returned value, and that ActionsDAG::Node::updateHash never sees: function_locate_has_mysql_compatible_argument_order (locate swaps its arguments, same two-query shape as above), least_greatest_legacy_null_behavior, h3togeo_lon_lat_result_order, geotoh3_argument_order, splitby_max_substrings_includes_remaining_string, count_matches_stop_at_empty_match, function_visible_width_behavior, function_json_value_return_type_allow_complex, functions_h3_default_if_invalid and cast_ipv4_ipv6_default_on_conversion_error. The registration rule is stated next to the list. The comparison family belongs to the same class and is registered too: FunctionComparison freezes decimal_check_overflow, validate_enum_literals_in_operators, use_variant_default_implementation_for_comparisons and cast_string_to_date_time_mode in ComparisonParams when it is built, and that frozen state decides how a string literal compared to a DateTime / Enum / Decimal column is parsed and whether an invalid literal compares or throws. The conversion functions (toString, toDateTime, CAST, ...) freeze a whole FormatSettings in FunctionConvertSettings, and the text serializations they call read it (toString of a DateTime64(1) is '…00.0' or '…00' depending on date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands, toString of a Bool is whatever bool_true_representation says, toString of an Array(DateTime) renders Unix timestamps under date_time_output_format = 'unix_timestamp'), so every value-changing or throw-vs-default field of that snapshot is registered too. Settings that change the result type are already covered by the type name in the DAG hash.

Tests: 05099_query_condition_cache_formatdatetime_settings covers MergeTree for formatDateTime, locate, cast_string_to_date_time_mode, the Variant / Dynamic strictness, JSONExtract, and the toString conversion of a DateTime64 and a Bool ('05/06/2024 00:00:00' is 2024-06-05 with best_effort and 2024-05-06 with best_effort_us); 05099_query_condition_cache_formatdatetime_settings_parquet covers the FormatFilterInfo path with a multi-row-group Parquet File table. Both were verified to fail (0 rows served instead of 1000000) against a build with the salt stubbed to zero.

The same mechanism is where the resolved session time zone of #117186 belongs; the pending #117302 adds it separately.

Closes: #117186
Closes: #117308

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 to CHANGELOG.md):

Fixed the query condition cache serving a "no matching rows" verdict to a query that differs from the cached one only in a setting that changes how a function evaluates, such as the formatdatetime_* / parsedatetime_* settings or function_locate_has_mysql_compatible_argument_order, which silently dropped all matching rows.


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

The query condition cache key is the table UUID, the part name and a hash of the
condition's `ActionsDAG`. The `formatdatetime_*` and `parsedatetime_*` settings change how
`formatDateTime` and `parseDateTime` evaluate and leave no trace in the DAG, so two queries
with the same condition text but different values of such a setting shared one entry: the
first query's "no marks match" verdict was served to the second one, which silently
returned no rows although every row matched.

The settings are now folded into the condition hash by `queryConditionCacheSettingsSalt`.
Every producer of the key has to apply it, or a verdict written by one query is never found
by the next one, so the salt is applied through the shared `queryConditionCacheHash` at all
five of them: the `WHERE` plan tag, the `PREWHERE` writer, the index-analysis exclusion
writer, the read side, and the file/object storage path.

Closes: #117308
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fcba835]

Summary: ✅


AI Review

Summary

This PR extends queryConditionCacheSettingsSalt and threads that salt through the query-condition-cache read/write paths so filters that depend on formatdatetime_*, JSON/conversion, short-circuit, and session_timezone settings stop colliding. The remaining gap is that deterministic LANGUAGE WASM UDF predicates still depend on per-query webassembly_udf_* limits that are not part of the cache key, so the cache can still reuse a stale "no marks match" verdict across queries that should instead raise a WebAssembly exception. Verdict: request changes.

Findings

❌ Blockers

  • [src/Interpreters/Cache/QueryConditionCache.cpp:81] The new registration rule still misses deterministic WebAssembly UDF settings. FunctionUserDefinedWasm participates in deterministic filters (UserDefinedWebAssembly.cpp:519-524), snapshots webassembly_udf_max_fuel and webassembly_udf_max_memory when it is built (UserDefinedWebAssembly.cpp:475-506), and also consults webassembly_udf_max_input_block_size / webassembly_udf_input_split_memory_ratio while executing (UserDefinedWebAssembly.cpp:630-679, 766-767). None of those settings reaches ActionsDAG::Node::updateHash, which still hashes only the function names, result type, children, and constants (ActionsDAG.cpp:287-326), and none is added to queryConditionCacheSettingsSalt. A lenient query can therefore cache "no marks match" for WHERE wasm_det(col) = ..., and a stricter query can hit that entry instead of seeing its expected WASM_ERROR / BAD_ARGUMENTS. Suggested fix: either include the semantics-affecting webassembly_udf_* settings in the QCC salt, or conservatively exclude deterministic Wasm UDF predicates from QCC. Add a focused regression that primes QCC under one Wasm setting profile and reruns the same predicate under a stricter one.
Final Verdict
  • Status: ⚠️ Request changes
  • Partition query-condition-cache entries for deterministic WebAssembly UDF predicates by the semantics-affecting webassembly_udf_* settings, or stop caching those predicates.
  • Add a regression test showing the cache does not suppress the expected WebAssembly exception when the settings change.

LLVM Coverage Report

Measured on commit fcba835.

Metric Baseline Current Δ
Lines 89.00% 89.10% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 127/127 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 3, 2026
Comment thread src/Formats/FormatFilterInfo.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fcba83579 with master cc102704b (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

69 object files changed (+96.56 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryConditionCache.cpp.o 202.99 KiB 296.77 KiB +93.78 KiB (+46.20%)

716 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

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

Median compile-time ratio to the baselines is ×1.10 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +347.3 s (+10%) in total before that adjustment.

Job report

@zlareb1

zlareb1 commented Sep 3, 2026

Copy link
Copy Markdown
Member

Verified the plumbing end to end at the current head (0c85d4b): every producer applies the salt — the WHERE plan tag (updateQueryConditionCache.cpp:119, the sole feeder of both FilterTransform writes), the PREWHERE writer via reader_settings.query_condition_cache_settings_salt, the index-analysis exclusion writer including its skip-index-profile derivation, and both FormatFilterInfo consumers — and all four reader probes in MergeTreeDataSelectExecutor derive from the same salted queryConditionCacheHash, including the TopK stripped-predicate reuse hash with matching hash_combine order on both sides. The salt hashes the setting values and is computed purely from Settings with no DAG inspection, so there is nothing for aliases, lambdas, or views to bypass. The fix is complete for the settings it covers.

The gap is that queryConditionCacheSettingsSalt is a blacklist of seven bools, while the soundness condition it stands in for is "any setting captured by a function at build time that changes the evaluated value while ActionsDAG::Node::updateHash sees nothing (result name, type name, function name, constant values)". At the current head at least eight more settings satisfy it. The headline, function_locate_has_mysql_compatible_argument_order, defaults to true and reproduces the exact two-query shape from the PR body — verified on a 26.9 build both ways:

CREATE TABLE t_loc (n UInt64, s String) ENGINE = MergeTree ORDER BY n;
INSERT INTO t_loc SELECT number, 'abc' FROM numbers(1000000);
-- primes "no marks match" (locate('abc' IN 'b') = 0 under the MySQL argument order):
SELECT count() FROM t_loc WHERE locate(s, 'b') = 2 SETTINGS function_locate_has_mysql_compatible_argument_order = 1;  -- 0, correct
-- served the poisoned verdict (position of 'b' in 'abc' = 2 should match every row):
SELECT count() FROM t_loc WHERE locate(s, 'b') = 2 SETTINGS function_locate_has_mysql_compatible_argument_order = 0;  -- 0, should be 1000000

Controls: the same second query with use_query_condition_cache = 0 returns 1000000, and a fresh condition under the legacy order returns 1000000 with the cache on. The setting is captured in the FunctionsStringSearch constructor (it swaps haystack/needle), so name, argument constants and the UInt64 result type are identical either way and the salted key still collides because the setting is not in the list.

The other build-time-captured, value-changing, DAG-invisible settings found by the same census: least_greatest_legacy_null_behavior (LeastGreatestGeneric.h; legacy NULL propagation vs new skip-NULL, result type Nullable either way), h3togeo_lon_lat_result_order (flips the tuple element order, same type name), geotoh3_argument_order, splitby_max_substrings_includes_remaining_string (changes Array(String) contents), count_matches_stop_at_empty_match, function_visible_width_behavior, and function_json_value_return_type_allow_complex (JSON_VALUE returns the complex value vs empty, same return type — its _allow_nullable sibling is safe because the type name changes). There is also a weaker throw-vs-default class (functions_h3_default_if_invalid, cast_ipv4_ipv6_default_on_conversion_error) where a default-on-error session primes verdicts that a throwing-profile session is served instead of its exception.

Since queryConditionCacheSettingsSalt is now the single chokepoint every key producer flows through, it is the natural registration point: adding these to the same list closes them all, and a comment on the helper stating the registration rule ("captured at function build time + changes the value + invisible to the DAG hash → add it here") would keep future compatibility settings from re-opening the class. For completeness: the FunctionConvertSettings capture family (cast_string_to_date_time_mode, date_time_overflow_behavior, precise_float_parsing, cast_keep_nullable on the value side) is tracked separately in #117203 and the resolved session timezone in #117186 — both fixes belong in this same salt.

Settings verified safe (type name reaches the hash, so no action needed): enable_extended_results_for_datetime_functions, function_date_trunc_return_type_behavior, geo_distance_returns_float64_on_float64_arguments, enable_named_columns_in_function_tuple.

@clickhouse-gh clickhouse-gh Bot added the comp-filesystem-cache Filesystem cache for remote/object storage, page cache, and read caching infrastructure. label Sep 4, 2026
alexey-milovidov and others added 3 commits September 6, 2026 09:42
…che salt

Address review: `function_locate_has_mysql_compatible_argument_order` swaps the
arguments of `locate` in the function's constructor, so `WHERE locate(s, 'b') = 2`
hashes identically under both values and a "no marks match" verdict written by one
session was served to the other. Register it in `queryConditionCacheSettingsSalt`
together with the other settings that meet the same rule (captured at build time,
change the value, invisible to `ActionsDAG::Node::updateHash`):
`least_greatest_legacy_null_behavior`, `h3togeo_lon_lat_result_order`,
`geotoh3_argument_order`, `splitby_max_substrings_includes_remaining_string`,
`count_matches_stop_at_empty_match`, `function_visible_width_behavior`,
`function_json_value_return_type_allow_complex`, `functions_h3_default_if_invalid`
and `cast_ipv4_ipv6_default_on_conversion_error`, and state the registration rule
in a comment so future compatibility settings land there too.

The test now also covers `locate`, sets `enable_analyzer = 1` explicitly because the
query condition cache is only used with the analyzer (the old-analyzer CI job saw no
cache hit), and is renumbered from 05070 to 05099.

Verified locally: with the salt stubbed to zero both the `formatDateTime` and the
`locate` pairs return 0 rows instead of 1000000.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117803&sha=606ca2f465a1d7c6a27731a951f1e54e2b03899b&name_0=PR
PR: #117803

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Address review: the `File` and object storage readers build their query condition
cache key in `FormatFilterInfo`, separately from `MergeTree`, and the existing tests
only check repeat hits for identical predicates. The new test flips
`formatdatetime_f_prints_single_zero` between two otherwise identical queries over a
multi-row-group Parquet file and checks that the second one does not reuse the first
one's "no row groups match" verdict, and that the cache really engaged (miss, then hit).

The table has two columns because the Parquet reader only reports matched row groups
for a condition it evaluates itself, and the optimizer only moves the condition to
`PREWHERE` when the query reads more columns than the condition uses.

Verified locally: with the salt stubbed to zero the flipped query returns 0.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @zlareb1 thanks for the census. All of the value-changing settings you listed are now registered in queryConditionCacheSettingsSalt (9c4dd5f), including the throw-vs-default pair functions_h3_default_if_invalid and cast_ipv4_ipv6_default_on_conversion_error, and the registration rule is written above the list so future compatibility settings land there. The FunctionConvertSettings family and the session time zone stay with #117203 and #117186 as you noted.

`FunctionComparison` freezes `decimal_check_overflow`,
`validate_enum_literals_in_operators`,
`use_variant_default_implementation_for_comparisons` and
`cast_string_to_date_time_mode` in `ComparisonParams` when it is built, and
uses that frozen state to decide how a string literal compared to a
`DateTime` / `Enum` / `Decimal` column is parsed and whether an invalid
literal compares or throws. None of it reaches
`ActionsDAG::Node::updateHash`, so two queries that differ only in one of
those settings hashed the same condition and shared one query condition
cache verdict.

`05099_query_condition_cache_formatdatetime_settings` now also covers
`cast_string_to_date_time_mode`: `'05/06/2024 00:00:00'` is 2024-06-05 with
`best_effort` (no row matches, so a "no marks match" verdict is stored) and
2024-05-06 with `best_effort_us` (11 rows match). Verified to return `0`
instead of `11` against a build with the salt stubbed to zero.
The `File` reader only evaluates the condition itself, and therefore only
records a verdict for the query condition cache, when the optimizer moves
the condition to `PREWHERE`. The stateless tests randomize
`optimize_move_to_prewhere` and `query_plan_optimize_prewhere`, and a run
with either of them off wrote nothing, so the final `QueryConditionCacheHits`
assertion of
`05099_query_condition_cache_formatdatetime_settings_parquet` returned `0`
in the flaky check. Pin both settings, and `enable_analyzer` which the cache
needs. Verified with `--client-option optimize_move_to_prewhere=0
query_plan_optimize_prewhere=0`.
alexey-milovidov and others added 2 commits September 12, 2026 00:45
…y condition cache salt

The `Variant` / `Dynamic` function adaptors resolve `variant_throw_on_type_mismatch` /
`dynamic_throw_on_type_mismatch` when the function is built and then use that frozen flag to decide whether
an alternative that is incompatible with the function throws or evaluates to `NULL`. The result type is the
same in both modes, so `ActionsDAG::Node::updateHash` sees nothing: a lenient session could prime a
"no marks match" verdict for `WHERE v + 1 = 2` over a `Variant(UInt64, String)` / `Dynamic` column, and a
strict session would then be served `0` rows instead of its exception.

Both settings are now registered in `queryConditionCacheSettingsSalt`, and
`05099_query_condition_cache_formatdatetime_settings` gets one focused regression per type. Checked against
a control binary with the two new salt entries neutralized: there both strict queries return `0` instead of
throwing `ILLEGAL_TYPE_OF_ARGUMENT`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate these two failures and provide a fix in a separate PR (or link the fix if it is already in progress) — they are unrelated to this PR, which only touches the query condition cache key:

  • 04648_distributed_plan_task_error_propagation
  • 04340_distributed_plan_status_reenqueue_fault

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117803&sha=b383378ba5c3820cc1708396e3e7fa64d8e1d819&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29

Over the last 14 days they failed 127 times across 84 pull requests (20 of them on master) and 99 times across 72 pull requests (11 on master) respectively, so they are broken independently of any single branch. I could not find an existing issue for either.

@groeneai

Copy link
Copy Markdown
Collaborator

No separate PR is needed: both failures are the same already-merged bug, and the fix is already in this PR's current head.

The linked report predates the fix. It is sha b383378b (2026-09-07 10:15Z). The fix is #118390, merged 2026-09-09 05:40Z as 129e4b59; b383378b sits 1090 commits behind that merge point. The current head here, 8d69e2a3 (pushed 01:30Z today), does contain it, so the report is five days stale relative to the branch.

These are one bug, not two. Over the last 15 days, 98 of the 124 jobs in which either test failed had both failing, and in the three most recent such jobs 04648 ran about 8.5 minutes before 04340 inside the same sequential job. Both tests are no-parallel. 04648 arms distributed_plan_record_failure_while_starting_tasks and disables it seven lines later, and the pre-#118390 bug delivered POCO_EXCEPTION (1000) instead of CANNOT_SCHEDULE_TASK (439), so the client aborted (return code 232) before reaching SYSTEM DISABLE FAILPOINT and left a REGULAR failpoint armed for the rest of the job. 04340 then never reaches its own re-enqueue fault path and prints reenqueue fault handled: 0. #118390 closes both arms: the error propagation itself, and making that failpoint ONCE so it cannot outlive its own query.

The 14-day counts are entirely pre-fix. Your 127 and 99 line up with the signature counts I measure (126 for but got: 1000, 99 for reenqueue fault handled), and the last of each is 2026-09-09 13:34Z and 2026-09-09 06:39Z respectively. Since the merge the two tests are at 10433 OK / 5 FAIL and 9738 OK / 3 FAIL. All eight of those failures are on heads behind the fix, and two of the five are not this class at all: one passed 43 out of 43 reruns under the same randomized settings, and the other is Code: 552 Unrecognized option '--query_plan_derive_not_null_filters_from_joins' from that PR's own diff. That last one is also the only failure either test has had in the past 48 hours.

Why the issue search came up empty: three exist and all are closed. #118626 (yours, closed as completed 2026-09-08 10:00Z, roughly 20 hours before the fix actually merged), plus #118831 and #118832, both closed as not planned. Closing #118626 ahead of the merge is why the counts kept climbing for another day.

The only work still open in this area is generic hardening rather than anything these two tests need: #105942 resets enabled failpoints after no-parallel tests, which would contain this leak class independently of the propagation fix.

… salt

`JSONOverloadResolver` snapshots a whole `FormatSettings` in its constructor and hands it to
`FunctionBaseFunctionJSON`, and `JSONExtractTree` then consults it to turn a JSON scalar into the
result type. None of that state reaches `ActionsDAG::Node::updateHash`, which sees only the function
name, the result type name, the children and the constant values, so two otherwise identical
predicates that differ only in one of those settings hash identically and a lenient session can prime
a "no marks match" verdict that a differently configured session reuses.

Register the `FormatSettings` fields that `JSONExtractTree` actually reads and that change the value
rather than the type - `precise_float_parsing`, `input_format_read_datetime_number_as_raw_value`,
`input_format_json_try_infer_numbers_from_strings`, `input_format_try_infer_dates`,
`input_format_try_infer_datetimes`, `input_format_try_infer_datetimes_only_datetime64`,
`schema_inference_make_columns_nullable`, `type_json_skip_duplicated_paths`,
`type_json_skip_null_typed_paths` and
`type_json_allow_duplicated_key_with_literal_and_nested_object` - plus `allow_simdjson`, which picks
the parser implementation in both `JSONOverloadResolver` and `FunctionSQLJSON`.
`cast_string_to_date_time_mode`, which `JSONOverloadResolver` latches into
`format_settings.date_time_input_format`, was already registered with the comparison family.

The JSONPath parser limits `max_parser_depth` / `max_parser_backtracks`, which `FunctionSQLJSON` also
snapshots, are deliberately left out and the reason is written next to the list: exceeding them
raises `TOO_DEEP_RECURSION` while the path expression is parsed, before any mark is read. Measured on
a server: after a permissive session writes a "no marks match" verdict, the restricted session still
throws, and it throws just the same with `use_query_condition_cache = 0`, so the cache cannot carry
that difference. Registering two such generic settings would split the cache for no gain.

Regression added to `05099_query_condition_cache_formatdatetime_settings`: an unquoted JSON number
extracted into `DateTime64(3)` is 1000 seconds by default and 1000 ticks (one second) with
`input_format_read_datetime_number_as_raw_value`, while the result type is `DateTime64(3)` either
way. A control binary with only the new salt entries neutralized (`& 0`) returns 0 instead of 1000000
for the second query, so the test fails without this fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai thanks — that settles it, and the fault is mine for linking a stale report: I quoted the b383378b run rather than re-checking against the current head. #118390 (129e4b59, 2026-09-09) is indeed already in this branch, and the shared-no-parallel-job failpoint leak explains why the two tests always failed together. No separate PR needed, and nothing here to act on; I will watch the fresh run on the new head instead of the old report.

alexey-milovidov and others added 2 commits September 12, 2026 19:01
The `JSONExtract` regression added in the previous commit compared against
`toDateTime64('1970-01-01 00:00:01', 3)`, which is parsed in the session time
zone. `tests/clickhouse-test` randomizes `session_timezone`, and its choice
list is deliberately stocked with zones that are ill-defined around 1970
(`America/Mazatlan`, `America/Hermosillo`, `Mexico/BajaSur`, ...), so the
literal drifted off the epoch second while the extracted value - a raw tick
count, and therefore absolute - did not. Both of the last two lines returned
`0` instead of `1000000`, including the `use_query_condition_cache = 0` one,
which shows it was never about the cache.

Pinning the literal to `UTC` makes the comparison absolute on both sides. The
`input_format_read_datetime_number_as_raw_value = 0` branch still returns `0`,
so the regression keeps its discriminating power.

Verified against a local server on the fresh binary: the test passes under
`America/Mazatlan`, `America/Hermosillo`, `Africa/Khartoum` and
`Mexico/BajaSur`, and the unpinned expression reproduces the exact CI result
(`0`) under `America/Mazatlan`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ry condition cache salt

`FunctionConvertSettings` snapshots a whole `FormatSettings` and a few more settings when a conversion function (`toString`, `toDateTime`, `CAST`, ...) is built, and the text serializations it calls read them without any trace in the condition's `ActionsDAG`: `toString` of a `DateTime64(1)` column is `'2024-05-05 10:00:00.0'` or `'2024-05-05 10:00:00'` depending on `date_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands`, `toString` of a `Bool` is whatever `bool_true_representation` says, `toString` of an `Array(DateTime)` renders the elements as Unix timestamps under `date_time_output_format = 'unix_timestamp'`, and so on. All value-changing (or throw-vs-default) fields of that snapshot are now hashed into `queryConditionCacheSettingsSalt`.

The `.sql` test gets two regressions on `MergeTree`: the `DateTime64` trailing-zeros cut and the `Bool` representation. Both return the poisoned `0` instead of `12` on a binary without the salt.

Addresses the review thread on `QueryConditionCache.cpp:62`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 2 commits September 13, 2026 23:29
…functions in the query condition cache salt

`toTypeName` latches `print_pretty_type_names`, and `formatQuery` / `formatQuerySingleLine` (and the `OrNull`
variants) snapshot `implicit_select`, `max_query_size`, `max_parser_depth` and `max_parser_backtracks` when they
are built. `range`, `highlight`, `extractAllGroups*`, `extractKeyValuePairs`, `readWKB*`, `base58Decode` and
`pointInPolygon` capture `function_range_max_elements_in_block`, `highlight_max_matches_per_row`,
`regexp_max_matches_per_row`, `extract_key_value_pairs_max_pairs_per_row`, `max_wkb_geometry_elements`,
`function_base58_max_input_size` and `validate_polygons` the same way. None of it reaches the DAG hash, so a
lenient session could prime a "no marks match" verdict that a stricter session was served instead of its rows
or its exception. All of them are now in `queryConditionCacheSettingsSalt`.

Regressions in the test: `formatQueryOrNull(q) IS NULL` flips from no row to every row with `implicit_select`
(the result type is `Nullable(String)` either way), and the strict `range` query must raise
`ARGUMENT_OUT_OF_BOUND` instead of reading the lenient session's verdict. Both fail on a binary without the
new entries and pass with them.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 2 commits September 14, 2026 06:52
… cache salt and shrink the `formatQuery` regression

`short_circuit_function_evaluation` is read by `ExpressionActions`, not by any function, so it never reaches
`ActionsDAG::Node::updateHash`: `if(flag, intDiv(42, x), 0) = 1` over rows with `flag = 0, x = 0` matches no
row under `'enable'` and throws under `'disable'` with an identical DAG. `IExecutableFunction` snapshots
`short_circuit_function_evaluation_for_nulls` and its threshold in its constructor and decides whether a
function is evaluated on the values stored behind `NULL`s. All three are now part of the salt, with an `if`
regression in `05099_query_condition_cache_formatdatetime_settings`.

The `formatQueryOrNull` regression raised and caught a parse error for each of its 1000000 rows, which took
longer than `max_execution_time` under the sanitizers (`TOO_SLOW` in the flaky checks, `Timeout!` in the
sequential run). The table now has 2048 rows with `index_granularity = 128`, so it still spans 17 marks.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117803&sha=706927e47165f559c919b1adae349decf0e36033&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: #117803

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`session_timezone` is not captured by any function when it is built: `DateLUT::instance()` reads it from the query
context whenever a function needs the implicit time zone, which is what `toDateTime(s)`, `parseDateTime(s, format)`
and their relatives do for a `String` argument without an explicit time zone. The result type is the plain
`DateTime` without a time zone in its name, so two sessions that differ only in `session_timezone` hash the same
filter DAG and the second one was served the first one's "no marks match" verdict. Reproduced on a binary without
this change: `toUnixTimestamp(toDateTime(s)) = 1714953600` returns 0 under `session_timezone = 'UTC'` right after
the same query ran under `'Asia/Tokyo'`, and 1000000 with the cache disabled.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The AI Review Blocker on session_timezone is confirmed and adopted in fcba835.

  • Confirmed with a measurement on a binary without the change: after SELECT count() FROM t WHERE toUnixTimestamp(toDateTime(s)) = 1714953600 SETTINGS session_timezone = 'Asia/Tokyo' primed a "no marks match" verdict (0 rows, 1 cache entry), the same query under session_timezone = 'UTC' returned 0 instead of 1000000 (and 1000000 with use_query_condition_cache = 0). The class is different from everything else in the salt: no function captures session_timezone when it is built, DateLUT::instance() reads it from the query context on every call, and the result type is the plain DateTime, so the DAG hash is identical.
  • Fix: queryConditionCacheSettingsSalt now hashes session_timezone, with the reason written next to it. I kept the string-parsing predicates in the cache rather than excluding them: with the time zone in the key, the verdicts are correct per session, and excluding them would need a DAG walk for every function that may fall back to the implicit zone.
  • Regression added to 05099_query_condition_cache_formatdatetime_settings.sql: a String column with '2024-05-06 00:00:00', toUnixTimestamp(toDateTime(s)) = 1714953600 under Asia/Tokyo (no DST, 0 rows), then under UTC (1000000 rows), then the same without the cache. The comparison side is an absolute Unix timestamp, so only the parsing side moves. Fails on the control binary, passes with the fix.


UInt64 queryConditionCacheSettingsSalt(const Settings & settings)
{
/// Registration rule: a setting belongs here when a function captures it at build time (in its constructor

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.

Deterministic LANGUAGE WASM UDFs still satisfy the registration rule but are not salted here. FunctionUserDefinedWasm returns getIsDeterministic() from isDeterministic() and snapshots webassembly_udf_max_fuel / webassembly_udf_max_memory when it is built (src/Functions/UserDefined/UserDefinedWebAssembly.cpp:475-506, 519-524); during execution it also consults webassembly_udf_max_input_block_size and webassembly_udf_input_split_memory_ratio (630-679, 766-767). None of that reaches ActionsDAG::Node::updateHash, which still only hashes names, types, children, and constants (src/Interpreters/ActionsDAG.cpp:287-326).

That means WHERE wasm_det(col) = ... can prime a QCC entry under a lenient Wasm budget, and the same predicate under a stricter budget can hit that cached "no rows match" verdict instead of raising its expected WASM_ERROR / BAD_ARGUMENTS. Please either fold the semantics-affecting webassembly_udf_* settings into the QCC salt as well, or conservatively exclude deterministic Wasm UDF predicates from QCC.

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.

🕵 Confirmed and adopted, but in a follow-up since this PR was merged before the finding landed: #120050 registers webassembly_udf_max_fuel, webassembly_udf_max_memory, webassembly_udf_max_input_block_size and webassembly_udf_input_split_memory_ratio in queryConditionCacheSettingsSalt under the same rule as the rest of the salt. The regression test there primes the cache with an unlimited budget and checks that one unit of fuel, a memory cap below the module minimum and an out-of-range split ratio still raise on the same predicate; on a binary without the fix the fuel line is served the cached verdict (succeeded but the server error 770 was expected).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 14, 2026
Merged via the queue into master with commit 6941684 Sep 14, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-condition-cache-formatdatetime-settings-117308 branch September 14, 2026 16:25
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @yariks5s — ClickGap found the following in this PR:

Could you review the test PR and add the can be tested label if it looks good?
Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

6 participants