Repository navigation
Make storage key and skip-index expression types independent of type-affecting session settings - #109196
Make storage key and skip-index expression types independent of type-affecting session settings#109196groeneai wants to merge 45 commits into
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-6:20260702-141200 |
|
cc @CurtizJ @yariks5s — could you review this? It makes the MergeTree key expression type independent of |
|
Workflow [PR], commit [fd4a563] Summary: ❌
AI ReviewSummaryThe PR resolves storage key, skip-index and implicit-projection types against the server settings baseline, prevents unsafe read optimizations when session semantics differ, and aligns Missing context / blind spots
Final VerdictStatus: ✅ Approve No additional code changes requested. |
0b19eca to
5125ffa
Compare
|
Updated pre-PR validation gate after extending the fix to Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260702-204200 |
5125ffa to
00dd943
Compare
|
Extended the fix to secondary (skip) index expressions per the review (00dd943). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260702-221000 |
00dd943 to
16ff3a1
Compare
|
Follow-up on the query-time key-type validation review (16ff3a1). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-5:20260702-235500 |
16ff3a1 to
611c328
Compare
Pre-PR validation gate (bot CR 4/4: custom_key_sampling nullability hole, 611c328)Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260703-013800 |
611c328 to
436eb66
Compare
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260703-031100 |
436eb66 to
96690e4
Compare
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-7:20260703-044900 |
96690e4 to
223d9aa
Compare
223d9aa to
ac97cb0
Compare
ac97cb0 to
865bbb1
Compare
|
Pre-PR validation gate for the object-storage partition-strategy opt-out (commit 865bbb1, review comment r3518915690): Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260703-100600 |
…ession The read-side guard refused the whole implicit `minmax_count` projection as soon as the first primary key column or any partition key column depended on a deviating session setting, even when the query needed none of them. For `PARTITION BY p ORDER BY tupleElement(h3ToGeo(h), 1)`, a session with `h3togeo_lon_lat_result_order = 1` read every row for `SELECT p, count() FROM t GROUP BY p` instead of one row per part. Refuse the projection only when the candidate reads a projection column answered from stored key values that the session computes differently: a partition value whose partition key column is session-dependent, or min/max of a session-dependent first primary key column. The filter is folded into the candidate DAG, so its inputs are covered too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 5fe14afEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261029-073003 |
|
🕵 Merged current The only red on Nothing changed on the three open review threads (nullable divergence on the read side, in |
The setting decides whether `toStartOfInterval` returns the type of its argument or a type chosen by the interval unit. A metadata-changing ALTER run with it off recorded `DateTime` for an `ORDER BY toStartOfInterval(dt64, INTERVAL 1 HOUR)` key while the writer kept producing `DateTime64(3)`, so the next INSERT aborted with `Bad cast from type DB::ColumnDecimal<DB::DateTime64> to DB::ColumnVector<unsigned int>` in the primary index writer (release builds write an index that fails to load after reattach with `CANNOT_READ_ALL_DATA`). The same ALTER on a `PARTITION BY toStartOfInterval(dt64, INTERVAL 1 DAY)` table made the next start detach the part written after it as broken. The setting arrived with the master merge, after the list in `createKeyExpressionContext` was written; pin it with the others. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An `ALTER` that changes columns rebuilds the implicit `minmax_count` projection in the session that runs it (`AlterCommands::apply`), so a type-affecting setting flipped on that `ALTER` gave its aggregate states the session type, while the states are filled from the key values the parts store under the baseline type. With `geo_distance_returns_float64_on_float64_arguments = 0` on `ALTER ... ADD COLUMN`, `min`/`max` of an `ORDER BY geoDistance(...)` key returned `0, 0`; with `enable_extended_results_for_datetime_functions = 1` a `toStartOfDay(DateTime64)` key or partition key failed with `BAD_GET`, and with `cast_keep_nullable = 1` a `CAST` key returned `0, 0`. A DETACH/ATTACH repaired it. Resolve the projection with `createKeyExpressionContext`, like the keys and skip indexes, inside `getMinMaxCountProjection`, which covers every caller (CREATE, ALTER, the replicated metadata path). The replicated path already used the storage context and was not affected. `04401` gains the reported case: on the previous head the optimized query returns `0, 0` while a scan returns the real values. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/MergeTree/KeyCondition.cpp
|
🕵 Merged Ergus's Three review threads are still open: the nullable read-side divergence, |
…401` Master now re-derives the sampling key in the global context after an `ALTER` (9bb2fc8, ClickHouse#130154), like the other keys. A session `cast_keep_nullable = 1` therefore no longer makes `CAST(x AS UInt32)` over a `Nullable` column a `Nullable(UInt32)` sampling key, and `ALTER TABLE ... MODIFY SAMPLE BY` is accepted instead of failing with `ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER`. That made `04401` fail in Fast test after the last master merge. Update the test case to the new behaviour: the `ALTER` succeeds and `SAMPLE` keeps working afterwards. Update the comment in `AlterCommand::apply` to match. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109196&sha=35f0e6feeff926f8957a9d1a9cdc72405bc472e6&name_0=PR&name_1=Fast%20test PR: ClickHouse#109196 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged current The red on The three open review threads (nullable divergence on the read side, in |
…n setting A session setting that changes the result type of a key function changes the value the same expression has for some rows. With `ORDER BY toUInt32OrDefault(x)` over `x Nullable(UInt32)` the stored key is `UInt32` and holds 0 for a NULL row, while under `cast_keep_nullable = 1` the query's expression is NULL for it, so `WHERE toUInt32OrDefault(x) IS NULL` was pruned to nothing by the primary key and by skip indexes. `JSON_VALUE` under `function_json_value_return_type_allow_nullable` behaved the same way. Such functions cannot be listed by name, so `getKeySubexpressionsWithSessionDependentValues` now resolves every function of the key again in the query session over the stored argument types, and returns the subexpressions whose type differs from the stored one. It does that only when the session sets one of the type-affecting settings differently from the server. The filter of `SAMPLE` is now analyzed with `createKeyExpressionContext`, like the sampling key itself, which is canonicalized again. Before, under `cast_keep_nullable = 1` the filter was nullable, and a NULL row fell out of every sample. In `04401`, one read used a skip index over `toStartOfTenMinutes` of a `DateTime64` column in a session with `enable_extended_results_for_datetime_functions = 1`. That index is not used in such a session anymore, so the query reads under the server settings. ClickHouse#109196 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged current
One behaviour change to be aware of: a session that changes the type of a key or index expression no longer uses that key or index. One query in
@Ergus, the |
`least_greatest_legacy_null_behavior` does not change the result type of `least`/`greatest` over two `Nullable` columns, only whether a NULL argument makes the result NULL or is skipped. The type comparison in `getKeySubexpressionsWithSessionDependentValues` therefore left such a key usable when the query set the setting differently from the server: with `ORDER BY greatest(x, y)`, `WHERE greatest(x, y) IS NULL` under the legacy behavior was pruned to nothing by the primary key and by a `set` skip index, the implicit `minmax_count` projection returned the stored min/max, and read-in-order returned NULL before the other rows. Name `least`/`greatest` as value carriers while the setting deviates and an argument can contain NULL. With non-nullable arguments the setting changes nothing, so such keys stay usable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`callsAnyOf` and `lambdaBodyTypeFollowsSession` walked the executable DAG of a lambda in the key. Once JIT compiles that body (`compile_expressions`, after `min_count_to_compile_expression` builds of the same expression), `greatest` and the arithmetic around it become one `LLVMFunction`, so a session with another `least_greatest_legacy_null_behavior` kept using a key whose stored values it computes differently. `greatest` over a nullable argument is compilable only with the legacy behaviour, so this needs a server baseline with `least_greatest_legacy_null_behavior = 1`. Walk `getActionsDAGForSemanticAnalysis()`, which keeps the body as it was built. The new test runs `clickhouse-local` with that baseline and JIT forced, for a constant-folded lambda and for one that captures a column. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - fd4a563Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The four Session id: cron:our-pr-ci-monitor:20261121-220024 |
|
Fixing PR for |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
Bad castlogical error (for exampleBad cast from ColumnVector<UInt32> to ColumnDecimal<DateTime64>) that broke the nextINSERTor mutation on aMergeTreetable whoseORDER BY,PRIMARY KEY,PARTITION BYor skip index uses a function whose result type depends on a session setting (enable_extended_results_for_datetime_functions,cast_keep_nullable,function_date_trunc_return_type_behavior,geo_distance_returns_float64_on_float64_arguments,function_json_value_return_type_allow_nullable,least_greatest_legacy_null_behavior,allow_lossy_numeric_supertype,use_variant_as_common_type,array_count_legacy_uint32_result,to_start_of_interval_preserves_argument_type), after any metadata-changingALTERran with that setting at a different value. After such anALTERthat changes columns,min/maxof the key answered by the implicitminmax_countprojection no longer return wrong values. Also fixed anORDER BY h3ToGeo(...)key silently exchanging its two tuple elements after such anALTERran with a differenth3togeo_lon_lat_result_order(the key type staysTuple(Float64, Float64), so nothing throws, but the on-disk primary index is then reloaded with latitude and longitude swapped), and the same for ageoToH3(...)key under a differentgeotoh3_argument_order. On the read side, a query that setsh3togeo_lon_lat_result_order,geotoh3_argument_order,geo_distance_returns_float64_on_float64_argumentsorleast_greatest_legacy_null_behaviordifferently from the server no longer uses a primary key, partition key, skip index, read-in-order or the implicitminmax_countprojection overh3ToGeo,geoToH3,geoDistance,greatCircleDistance,greatCircleAngle, orleast/greatestwith a nullable argument, which previously silently pruned away the matching rows, returned mis-ordered rows or returned the stored values instead of the session's. The same applies to a key function whose result type the query changes with one of the type-affecting settings above, for exampleWHERE toUInt32OrDefault(x) IS NULLundercast_keep_nullable = 1no longer loses the row withNULL, andSAMPLEno longer loses it either.FINALover such a key is not covered here; #120058 fixes it.Closes: #109181
Description
KeyDescription::data_typesis recomputed in whatever context runsCREATE/ALTER, so a metadata-changingALTER(evenMODIFY COMMENT) run with a type-affecting setting flipped changes the in-memory key type, while the storage keeps producing the key column in its own context. The primary-index writer then aborts withBad cast ...on the nextINSERTor mutation, and the table stays broken until a metadata reload:Fix: analyze key and skip-index expressions with every enumerated type-affecting setting pinned to the server settings baseline, via the new
createKeyExpressionContextat the four key and skip-index derivations and in the implicitminmax_countprojection, so the key type matches what a metadata reload resolves;toStartOf*Extended(#108002) still declares an intentionally extended key. A key re-analyzed in the query context at read time must not be canonicalized, or validation accepts what the runtime filter breaks, sogetKeyFromASTtakescanonicalize_key_types, false for theparallel_replicas_custom_keyvalidator and hive-style partitioning. The sampling key is canonicalized, and theSAMPLEfilter is analyzed withcreateKeyExpressionContextas well, so aNULLrow no longer falls out of every sample undercast_keep_nullable = 1.Four settings change a key function's value rather than its type (
h3togeo_lon_lat_result_order,geotoh3_argument_order,geo_distance_returns_float64_on_float64_arguments, andleast_greatest_legacy_null_behaviorforleast/greatestover a nullable argument): a query that set one differently from the server pruned rows the runtime filter keeps (measured).getKeySubexpressionsWithSessionDependentValuesnames the key subexpressions computed from them, also through lambda bodies;KeyConditionhides them (soforce_primary_keyraisesINDEX_NOT_USED),buildIndexesrefuses a skip index of any family over them,requestReadingInOrderrefuses such a prefix, and the implicitminmax_countprojection is skipped when the query needs min/max of its first primary key column or a partition value that is one of them.The settings that change a key function's type diverge at read time too, since another type means another value for some rows: under
cast_keep_nullable = 1,WHERE toUInt32OrDefault(x) IS NULLoverORDER BY toUInt32OrDefault(x)was pruned to nothing. Such functions cannot be listed by name, so when the session sets a type-affecting setting differently from the server,getKeySubexpressionsWithSessionDependentValuesresolves every function of the key again in the session over the stored argument types and also names the subexpressions whose type differs from the stored one.Not covered: the
FINALlayer split rebuilds its range filter from the key AST in the query session; #120058 fixes that at the source. Also not covered: a qualified nullableparallel_replicas_custom_keyloses theNULLrow with no session setting involved, which is tracked in #133393.Notes for reviewers: compatibility, and the
cast_keep_nullablecarrier fromBuzzHouseA table declared with e.g.
ORDER BY toStartOfTenMinutes(dt64)underenable_extended_results_for_datetime_functions = 1never had a persistableDateTime64key anyway: the type reverts toDateTimeon restart, and the on-disk primary index is always written with the baseline type. So this makes an already-inconsistent state consistent rather than removing a working configuration.MasterCIBuzzHouse (amd_debug)hits the same divergence throughcast_keep_nullable: STID 3520-704a,Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnNullable, report.toUInt64OrDefaultis aFunctionCastOrDefault, so its return type followscast_keep_nullable; BuzzHouse reaches the metadata recompute throughALTER TABLE ... MODIFY COLUMN ... MODIFY SETTINGand needsallow_nullable_key = 1, which its fuzzer server config sets.Workflow [PR]
Sync PR [sync-upstream/pr/109196]