Skip to content

Key an expression by the settings a conversion captured - #119168

Merged
alexey-milovidov merged 12 commits into
masterfrom
conversion-settings-in-dag-hash-117203
Oct 4, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
conversion-settings-in-dag-hash-117203

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

The query condition cache keys a granule-skip verdict by a hash of the filter expression, which names the function and its result type but says nothing about the settings a conversion captured when it was built. Two sessions that differ only in precise_float_parsing therefore shared one key, and the session running at pure defaults was served the other's "no matching rows" verdict:

CREATE TABLE t (id UInt64, s String) ENGINE = MergeTree ORDER BY id;
INSERT INTO t SELECT number, '1.1e-300' FROM numbers(200000);

SYSTEM DROP QUERY CONDITION CACHE;
SELECT count() FROM t WHERE toFloat64(s) = 1.1e-300 SETTINGS precise_float_parsing = 0;  -- 0, correct there
SELECT count() FROM t WHERE toFloat64(s) = 1.1e-300;                                    -- 0, wrong: 200000 rows match

FunctionConvertSettings captures precise_float_parsing, cast_string_to_date_time_mode, date_time_overflow_behavior, cast_keep_nullable and the format settings from the building session, while the function reports a fixed name and a stable result type, so the divergence never reached the key.

IFunctionBase::updateHash (forwarded by the adaptor from IFunction) lets a function contribute what decides the values it produces beyond its name and types, and both places that key an expression by a hash ask for it: ActionsDAG::Node::updateHash (the query condition cache) and the for_cache_key serialization in ActionsDAG::serialize (the hash-table statistics cache, which used to write a function node by its name alone). The key stays shared between sessions that agree on those settings: a repeat of the same query still reuses its own entry, and only a session with a different setting adds one of its own.

The conversions hash the settings they captured one by one, and their captured FormatSettings through getFormatSettingsHash: it hashes the session settings getFormatSettings derives the struct from whose effective values differ from the declared defaults (so spelling a default explicitly does not split the key), generated from the FORMAT_FACTORY_SETTINGS list itself, so a setting added there is covered without anyone remembering the hash. The other functions that capture a setting contribute it the same way: the comparisons (ComparisonParams, which reads a string literal by the captured settings), the JSON* functions, the functions that capture type_json_skip_null_typed_paths (JSONAllPaths*, JSONAllValues, has / indexOf / countEqual and empty / notEmpty on JSON), countMatches, formatQuery, toJSONString and visibleWidth.

Closes: #117203

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 one session's granule verdicts to another when the two differ only in a setting a conversion function captured, such as precise_float_parsing, which silently dropped matching rows from the second session's result.


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

Version info

  • Merged into: 26.10.1.1515-master (included in 26.10 and later)

The hash of a filter expression named the function and its result type,
neither of which mentions the settings a conversion captured when it was
built. Two sessions that differ only in `precise_float_parsing` (or
another of them) therefore produced the same query condition cache key,
and the one at pure defaults was served the other's "no matching rows"
verdict: every row of a matching granule silently vanished from its
result.

A function can now contribute to the hash what decides the values it
produces beyond its name and types, which is what the conversion
functions do with their settings. Sessions that agree on them still
share the key.

Closes: #117203
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6706e55]

Summary: ✅


AI Review

Summary

This PR correctly routes captured conversion and JSON settings into expression hashing and extends that hash into both the query condition cache and the hash-table statistics cache. The unresolved problem is that the new statistics-cache path still assumes IFunctionBase::updateHash coverage is complete, but several other setting-capturing functions already special-cased in queryConditionCacheSettingsSalt still do not override it, so sessions with different settings can still share one aggregation-statistics entry.

Findings
  • ⚠️ Majors
    • [src/Interpreters/ActionsDAG.cpp:5009] The statistics-cache key now relies entirely on IFunctionBase::updateHash, but that contract is still incomplete for functions such as least / greatest (src/Functions/LeastGreatestGeneric.h:44), formatDateTime / parseDateTime (src/Functions/formatDateTime.cpp:975, src/Functions/parseDateTime.cpp:606), and toTypeName (src/Functions/toTypeName.cpp:23). src/Interpreters/Cache/QueryConditionCache.cpp:81 still salts these settings explicitly for the query condition cache, which is strong evidence that the same surface remains open here. As a result, two sessions that differ only in one of those captured settings can still reuse the same hash-table statistics / preallocation entry.
    • Suggested fix: cover the remaining setting-capturing functions named in src/Interpreters/Cache/QueryConditionCache.cpp:81 with updateHash, or keep equivalent setting salt on the statistics-cache side until that coverage is complete.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Extend updateHash coverage to the remaining setting-capturing functions already tracked in queryConditionCacheSettingsSalt, or
    • Restrict the new statistics-cache key path so it does not assume that coverage is complete.

LLVM Coverage Report

Measured on commit 6706e55.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 140/149 (93.96%) · 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 10, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 10, 2026
Comment thread src/Functions/FunctionsConversion.h Resolved
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6706e55f9 with master b94acbe31 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 37a251ffa; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes, compile time of recompiled translation units, symbol sizes.

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 ⚠️

877 object files changed (+2.60 MiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/FormatFactory.cpp.o 524.05 KiB 1.71 MiB +1.20 MiB (+234.15%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsJSON.cpp.o 4.08 MiB 4.30 MiB +226.88 KiB (+5.44%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion.cpp.o 21.44 MiB 21.53 MiB +87.45 KiB (+0.40%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/FunctionsConversion_reg.cpp.o 6.78 MiB 6.82 MiB +39.53 KiB (+0.57%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl2.cpp.o 1.27 MiB 1.30 MiB +29.84 KiB (+2.30%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl1.cpp.o 1.08 MiB 1.11 MiB +29.84 KiB (+2.69%)
src/CMakeFiles/dbms.dir/Functions/FunctionsConversion_impl3.cpp.o 1.58 MiB 1.60 MiB +23.72 KiB (+1.47%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/JSONPaths.cpp.o 659.03 KiB 679.96 KiB +20.94 KiB (+3.18%)

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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.73 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse-keeper DB::getFormatSettingsHash(DB::Settings const&) new 5.5 s +5.5 s
programs/clickhouse DB::getFormatSettingsHash(DB::Settings const&) new 5.4 s +5.4 s
Compile time of recompiled translation units ⚠️

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

Translation unit Master PR Δ vs median
src/Formats/FormatFactory.cpp 7.2 s 38.8 s +31.6 s (+439%)
Symbol sizes ⚠️
Binary Symbol Master PR Δ
programs/clickhouse DB::getFormatSettingsHash(DB::Settings const&) new 525.52 KiB +525.52 KiB
programs/clickhouse-keeper DB::getFormatSettingsHash(DB::Settings const&) new 525.52 KiB +525.52 KiB

Job report

Comment thread src/Functions/IFunction.h Resolved
pull Bot pushed a commit to Dream-hu/ClickHouse that referenced this pull request Sep 12, 2026
A key expression is resolved twice: by the table, under its own settings,
which is what each part's physical row order follows, and by the query,
under the session's. Both matchers that decide read-in-order compared the
two derivations without comparing the types they resolve to.

matchTrees mapped them on structure alone, that is function name plus
arity, comparing result types only for constant children, while its
contract states that directly mapped nodes represent equal calculations.

When a setting changes the expression's result type the two derivations are
different functions with different NULL handling, so they are different
orders. With cast_keep_nullable = 1 a key of CAST(json.b, 'String') is
Nullable(String) in the query and String in the table, and read-in-order
then advertises an order the parts do not have: rows come back unsorted,
aggregation-in-order splits groups and reports wrong counts, and
read_in_order_use_virtual_row = 1 fails with "Virtual row has different
type", which is the only place the two types are compared and so the only
place that reports anything at all.

Requiring the mapped pair's result types to agree cannot lose a sound
match, because a deterministic function of equal-typed arguments has one
result type, so a disagreeing pair was never an equal calculation. It
extends the type identity already applied to constant children at the same
site. This tightens the matcher for all nine of its callers, which is
intended: each uses the same claim to substitute one expression for
another.

The check is applied at the FUNCTION mapping only. No reachable divergence
was found for the INPUT mapping: a Merge table unifying a UInt32 and a
Nullable(UInt32) column under one header, the most plausible shape, maps
consistently, so an INPUT check would have shipped without a test.

ReadInOrderOptimizer is the second matcher, selected under the old analyzer
when query_plan_read_in_order is off, and it compared the key by name
alone. It now also requires the storage key's type to equal the query
side's, at the exact-match branch and at the monotonic branch's argument.
That covers a divergence at the top of the key expression. It does not
cover one nested under an equal-typed parent, such as
ifNull(CAST(json.b, 'String'), 'zzz'), because this matcher tests a single
name and never walks the expression; walking is what the plan-based path
does, and that path is covered by the matchTrees change above.

Each test arm pins which matcher it exercises instead of inheriting the
session's, so neither runner injection nor a later default flip can move an
arm to the other matcher without the arm saying so.

Found on master by CI: Stress test (amd_tsan), sha ad8622e.

Related: ClickHouse#109196
Related: ClickHouse#119168

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov and others added 3 commits September 18, 2026 02:46
…cked subset

`FunctionConvertSettings::updateHash` salted the key with a hand-picked subset of
the `FormatSettings` it captured, while the generic conversion paths read members
it left out (`input_format_null_as_default` while parsing an array, for one), so
two sessions that differed in such a member still shared a query condition cache
key. `FormatSettings` has too many members to hash one by one without missing
one; `getFormatSettingsHash` hashes the session settings `getFormatSettings`
derives it from instead: every setting of `FORMAT_FACTORY_SETTINGS` as declared
plus the few core settings it reads, so a setting added there is covered without
anyone remembering the hash. Only changed settings are hashed, in declaration
order, so sessions at the defaults share the empty hash.

The `updateHash` contract in `IFunction.h` promised more than the tree delivered:
`countMatches` (`count_matches_stop_at_empty_match`), `toJSONString` (captured
`FormatSettings`) and the comparison functions (`ComparisonParams`, which reads a
string literal as the other side's type by the captured settings) all inherited
the empty default. They now contribute what they captured, and the comment names
them and says what a function that does not override it gets.

The test gains the strict-parsing session that must still get its exception
instead of the default session's "skip every granule" verdict, `countMatches`, a
comparison against a string literal under two `cast_string_to_date_time_mode`
values, and a check that an unrelated setting leaves the key alone. Renumbered to
05227 after master.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… cache key too

`ActionsDAG::Node::updateHash` asked the function for what it captured, but the
hash-table statistics cache keys an aggregation or join by the serialized plan
(`ActionsDAG::serialize` with `for_cache_key`), which still wrote a function
node by its name alone, so two sessions that differed only in a setting a
conversion captured shared one statistics entry and preallocated from each
other's numbers. The cache-key serialization now also writes the hash of
`IFunctionBase::updateHash`; the transmission path leaves it out, the receiver
rebuilds the function from its own settings.

The test runs the same `GROUP BY toFloat64(s)` in two sessions that differ in
`precise_float_parsing` in a fresh `clickhouse-local` process and checks that
the second session's first run preallocates nothing while its repeat does.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Interpreters/ActionsDAG.cpp Resolved
Comment thread src/Formats/FormatFactory.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Sep 18, 2026
alexey-milovidov and others added 3 commits October 2, 2026 06:52
…ormatSettingsHash`

Hashing `Settings::changes` split the key between a session that left a format setting at its default
and one that spelled the default explicitly, since an assignment marks a setting changed regardless of
its value. Now a format setting is hashed only when its effective value differs from the declared
default (the `changed` flag is checked first, so only the settings a session set are compared).

This also drops the static `unordered_set` of setting names: it was a live allocation of about 13 KB
that the "Storage memory check" reported, and its list of extra core settings had gone stale
(`allow_experimental_nullable_tuple_type` is now `enable_nullable_tuple_type`). The core settings
`getFormatSettings` reads besides the format settings are now hashed by their values directly,
including `http_write_exception_in_output_format`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119168&sha=4c371e59e958278b4a60fe51928cced3027aec92&name_0=PR
#119168

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…formatQuery` and `JSON*` to `updateHash`

These functions capture settings when they are built (`function_visible_width_behavior`, the parser
settings, `allow_simdjson` and a `FormatSettings`) that decide their result without changing their
name or result type. The query condition cache covers them through `queryConditionCacheSettingsSalt`,
but the hash-table statistics cache keys a plan only by its serialization, so they now hash what they
captured too. The new test checks that a different `function_visible_width_behavior` gets its own
statistics entry, and that spelling a format setting at its default shares the entry of the defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/IFunction.h Resolved
alexey-milovidov and others added 2 commits October 4, 2026 11:05
…ns that capture it

`JSONAllPaths*`, `JSONAllValues`, `has` / `indexOf` / `countEqual` and
`empty` / `notEmpty` on `JSON` capture `type_json_skip_null_typed_paths`
and change their result with it, so they contribute it to `updateHash`;
otherwise the hash-table statistics cache shares one entry between sessions
that differ in the setting.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119168&sha=39d344b70a3cd3857d754e8b16832e4ddbdb802f&name_0=PR&name_1=BuzzHouse%20%28amd_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

It is a MemorySanitizer: use-of-uninitialized-value in readEscapedStringIntoImpl while reading a TabSeparated header from StorageURLSource; the uninitialized memory comes from the buffer of ReadBufferFromIStream created by ReadBufferFromSessionResponse (ReadWriteBufferFromHTTP), which this PR does not touch.

…y `type_json_skip_null_typed_paths`

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// A cache key has to tell apart two functions of one name that captured different settings
/// (see `Node::updateHash`), so it also carries the hash of what the function captured. The
/// transmission path leaves it out: the receiver rebuilds the function from its own settings.
if (registry.for_cache_key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new statistics-cache key now trusts IFunctionBase::updateHash, but that contract is still incomplete for other functions that already needed special handling in queryConditionCacheSettingsSalt. For example, least / greatest still capture least_greatest_legacy_null_behavior in src/Functions/LeastGreatestGeneric.h:44, formatDateTime / parseDateTime still snapshot their formatdatetime_* settings in src/Functions/formatDateTime.cpp:975 and src/Functions/parseDateTime.cpp:606, and toTypeName still latches print_pretty_type_names in src/Functions/toTypeName.cpp:23, but none of them contributes that state through updateHash.

The query condition cache is still protected because src/Interpreters/Cache/QueryConditionCache.cpp:81 salts those settings explicitly, but the hash-table statistics cache now keys only on this serialized updateHash state. As written, two sessions that differ only in one of those settings can still share one preallocation entry. Please either cover the remaining setting-capturing functions named in queryConditionCacheSettingsSalt in this PR, or keep those settings on the statistics-cache side until updateHash coverage is complete.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm investigating the MemorySanitizer: use-of-uninitialized-value in readEscapedStringIntoImpl (TSV header from StorageURLSource, uninitialized bytes from the ReadBufferFromIStream buffer in ReadWriteBufferFromHTTP); I'll follow up here with a PR (or my findings) shortly.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

The fix is in #123861. With input_format_tsv_crlf_end_of_line = 1, readEscapedStringIntoImpl checked for \r right after an escape sequence without checking for pending data, so an escape ending at the buffer end read the byte past the working buffer (uninitialized for MSan; on released versions a stale \r there gives a segfault or std::length_error). ReadBufferFromIStream and ReadWriteBufferFromHTTP are not at fault: file() reaches the same path.

@alexey-milovidov alexey-milovidov left a comment

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.

To be honest, we didn't have to do this. It would be entirely alright if the query condition cache was inconsistent related to the formatting settings. So the change is too pedantic. But I have no objections against it.

@alexey-milovidov alexey-milovidov self-assigned this Oct 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into master with commit 62a9912 Oct 4, 2026
150 checks passed
@alexey-milovidov
alexey-milovidov deleted the conversion-settings-in-dag-hash-117203 branch October 4, 2026 18:01
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
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

3 participants