Repository navigation
Include the formatdatetime_* settings in the query condition cache key - #117803
alexey-milovidov merged 18 commits into
Conversation
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
|
Workflow [PR], commit [fcba835] Summary: ✅
AI ReviewSummaryThis PR extends Findings❌ Blockers
Final Verdict
LLVM Coverage ReportMeasured on commit fcba835.
Changed lines: Changed C/C++ lines covered: 127/127 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes69 object files changed (+96.56 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units382 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. |
|
Verified the plumbing end to end at the current head (0c85d4b): every producer applies the salt — the The gap is that 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 1000000Controls: the same second query with The other build-time-captured, value-changing, DAG-invisible settings found by the same census: Since Settings verified safe (type name reaches the hash, so no action needed): |
…he-formatdatetime-settings-117308
…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]>
|
🕵 @zlareb1 thanks for the census. All of the value-changing settings you listed are now registered in |
`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`.
…he-formatdatetime-settings-117308
…he-formatdatetime-settings-117308
…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]>
|
🕵 @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:
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. |
|
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 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 The 14-day counts are entirely pre-fix. Your 127 and 99 line up with the signature counts I measure (126 for 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 |
… 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]>
|
🕵 @groeneai thanks — that settles it, and the fault is mine for linking a stale report: I quoted the |
…he-formatdatetime-settings-117308
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]>
…he-formatdatetime-settings-117308
…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]>
… 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]>
|
🕵 The AI Review Blocker on
|
|
|
||
| UInt64 queryConditionCacheSettingsSalt(const Settings & settings) | ||
| { | ||
| /// Registration rule: a setting belongs here when a function captures it at build time (in its constructor |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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 @yariks5s — ClickGap found the following in this PR:
Could you review the test PR and add the |
The query condition cache key is the table UUID, the part name and a hash of the condition's
ActionsDAG. Theformatdatetime_*andparsedatetime_*settings change howformatDateTimeandparseDateTimeevaluate 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 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 existing03229_query_condition_cache_profile_eventscatches exactly that), so the salt goes through the sharedqueryConditionCacheHashat all five of them: theWHEREplan tag, thePREWHEREwriter, 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::updateHashnever sees:function_locate_has_mysql_compatible_argument_order(locateswaps 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_invalidandcast_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:FunctionComparisonfreezesdecimal_check_overflow,validate_enum_literals_in_operators,use_variant_default_implementation_for_comparisonsandcast_string_to_date_time_modeinComparisonParamswhen it is built, and that frozen state decides how a string literal compared to aDateTime/Enum/Decimalcolumn is parsed and whether an invalid literal compares or throws. The conversion functions (toString,toDateTime,CAST, ...) freeze a wholeFormatSettingsinFunctionConvertSettings, and the text serializations they call read it (toStringof aDateTime64(1)is'…00.0'or'…00'depending ondate_time_64_output_format_cut_trailing_zeros_align_to_groups_of_thousands,toStringof aBoolis whateverbool_true_representationsays,toStringof anArray(DateTime)renders Unix timestamps underdate_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_settingscoversMergeTreeforformatDateTime,locate,cast_string_to_date_time_mode, theVariant/Dynamicstrictness,JSONExtract, and thetoStringconversion of aDateTime64and aBool('05/06/2024 00:00:00'is 2024-06-05 withbest_effortand 2024-05-06 withbest_effort_us);05099_query_condition_cache_formatdatetime_settings_parquetcovers theFormatFilterInfopath with a multi-row-group ParquetFiletable. 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):
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 orfunction_locate_has_mysql_compatible_argument_order, which silently dropped all matching rows.Workflow [PR]
Sync PR [sync-upstream/pr/117803]