Repository navigation
Reject ALTER MODIFY COLUMN that changes the values of a key subcolumn without changing its type - #129287
Reject ALTER MODIFY COLUMN that changes the values of a key subcolumn without changing its type#129287groeneai wants to merge 12 commits into
ALTER MODIFY COLUMN that changes the values of a key subcolumn without changing its type#129287Conversation
…to defaults ClickHouse#113862 allows MODIFY COLUMN of a column whose subcolumn is in the sorting or partition key when the key subcolumn type converts safely. Below a Nullable level a subcolumn is Nullable either way, so `JSON(a Nullable(Int64))` -> `Nullable(JSON(a Int64))` keeps `data.a` a `Nullable(Int64)` while the CAST turns every NULL of it into 0. The mutation does not re-sort, so the part and its rebuilt primary index end up unsorted: primary key analysis returns wrong results (count 11 instead of 7 on 26.8) and a debug build aborts in DistinctSortedStreamTransform with "Equal values are not contiguous within the range assumed to be sorted" (AST fuzzer, STID 2508-3b73). The same happens when a leaf loses its own Nullable under a kept Nullable level, under a Tuple element, Array or Map value, when a Nullable level is removed with DEFAULT, and on the lazy `enable_json_lazy_type_hints` path, where the next merge of such a part aborts in CheckSortedTransform. The check now walks every level on the way to the key subcolumn (`conversionKeepsSubcolumnValues`): a Nullable level must stay Nullable, Array levels and named levels are compared recursively. It is used in the mutation path and in the lazy metadata-only path (sorting and partition key, skip indices, projections, MATERIALIZED columns, TTL). Replays on secondary replicas of a Replicated database are not refused, the same as the other initiator-only checks of checkAlterEligibility, so a queue entry an older initiator committed does not retry forever. The test cases are ordered so that no key lookup runs after an ALTER that master wrongly accepts: the client continues after an unmet serverError hint, and a primary key lookup on such a part aborts a debug server with "Inconsistent KeyCondition behavior". Co-Authored-By: Claude Opus 5.5 <[email protected]>
…LUMN Subcolumn names are flat, so a name can be answered by a different substream after the type change: dropping the element `j.a` of Tuple(`j.a` Int64, j JSON(a Int64)) makes `c.j.a` resolve to the path `a` of the element `j`, with the same type. The ALTER was accepted and the parts were left unsorted by the key (found by the second-model review). conversionKeepsSubcolumnValues now compares the value-selecting steps of the key subcolumn's substreams path before and after (Nullable and LowCardinality levels are checked separately; a JSON path is the same path whether it is typed, in the shared data or dynamic), the same idea as isSameSubstream in FunctionToSubcolumnsPass. A dotted level is recursed into only when the rest of the name is its subcolumn and the key's substreams path goes through it. The first part stops the false reject of an unrelated sibling: changing the JSON path `j.a` while the element `j.a` is kept is allowed again. The textual part keeps a key on a dynamic path with a type hint (`data.b.:Int64`) from recursing into `Dynamic` with the name `:Int64`, which it does not have. 04811 gains the shadowed-element rejection and two positive controls: the kept element with a changed sibling path, and the dynamic path with a type hint. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`key_<k>` of a Map is resolved by parsing `<k>` as the current key type, and its substream step records only the text. So Map(String, Int64) -> Map(Int64, Int64) keeps both the subcolumn type and the step of `m.key_1`, the ALTER was accepted, and since '01' and '1' both become the key 1, `m.key_1` read another entry and the parts were left unsorted by the key. A MapKeyValue level now requires an identical key type. The substream comparison refused Variant -> Dynamic, which keeps every variant as it is: a variant subcolumn is [VariantElements, VariantElement(T)] in Variant and [DynamicData, VariantElement(T)] in Dynamic. VariantElements may now become DynamicData. Only in that direction: a Dynamic -> Variant CAST parses a String value by inference when the target has several variants, which can move a row into another variant. 04811 gains the Map rejection and two positive controls: a Map key type change under an `m.values` key, and Variant -> Dynamic. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A JSON -> JSON CAST with different parameters serializes every row and parses it again with the target type, which drops every path that its SKIP / SKIP REGEXP rules match: the parser tests the root and every prefix of a path, and matches a regexp partially by default. Subcolumn resolution ignores the skip rules, so JSON -> JSON(SKIP b) kept the type and the substream of the key subcolumn `data.b.:Int64`, the ALTER was accepted, every key value turned NULL and the part was left unsorted by the key. A JSON level that changes now refuses the conversion when the new type skips the key subcolumn's path or a prefix of it. A sub-object (`^`) or combined (`@`) JSON subcolumn cannot be a sorting key column (DATA_TYPE_CANNOT_BE_USED_IN_KEY), so it needs no case of its own. 04811 gains three rejections (SKIP of the path, of a prefix, and a SKIP REGEXP matching the prefix) and a SKIP rule for another path as a positive control. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A JSON -> JSON CAST with different parameters writes every row as text and parses it again with the target type. Besides the SKIP rules, that re-parse puts the whole object at a typed path `b` into that path, so a dynamic path `b.c` below it loses its values when `b` is added and gets values when it is removed, and it infers the type of every Dynamic value again (2.0 is written as 2 and comes back as Int64). A combined `@` subcolumn has an empty object path, so the SKIP check saw only the root. Subcolumn resolution keeps the type and the substream in all of these cases, so the ALTER was accepted and the part was left unsorted by the key. Below a JSON level that changes, the key subcolumn must now read a typed path in both types, its type in the new JSON must have no Dynamic or JSON inside, and the new type must not skip it. Typed paths of fixed types stay allowed; a key on a dynamic path can still change only levels that do not re-parse the data, such as an added Nullable. 04811: the dynamic path control becomes a Float64 rejection plus a Nullable(JSON)-only allowed control; the SKIP block is re-keyed to the typed path `b.c`; new rejections for a typed prefix added and removed, a combined `@` subcolumn in a key expression and a typed Dynamic path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A JSON -> JSON CAST writes every row as text and parses it again with the target type, which can change a typed key path that r5 still let through: - a typed path above it takes the whole object, so the key path below gets its default (with type_json_allow_duplicated_key_with_literal_and_nested_object off); - a Variant value has its variant chosen again (a String '1' comes back as Int64 1); - inf and nan are written as null and come back as 0; - a Decimal with a fraction is a JSON double and is parsed through Float64. Below a changed JSON level the key subcolumn's typed path in the new type must now have no Variant, Dynamic, JSON, floating-point or Decimal type inside, and no proper dotted prefix of it may be a typed path of either type. 04811: rejections for a typed path above a typed key path and for typed Variant, Float64 and Decimal key paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop comments that narrate the new code; keep the type and parser semantics as one-line invariants. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review (rounds r0-r6)Bounce cap reached: the final round (r6) is published as-is, without a further second-model review of it. The residual findings below are noted, not blocking.
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20261104-131600 |
|
Workflow [PR], commit [4ab3118] Summary: ❌
AI ReviewSummaryThis PR tightens Findings
Final Verdict
|
|
cc @Avogar @tiandiwonder, could you review this and add the |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes3 object files changed (+48.88 KiB total), 0 added.
719 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 units7 translation units recompiled, 44 s compile time in total, 7 of them have a recent master baseline. |
… changed JSON level
A JSON -> JSON conversion serializes the column to JSON text and parses it
again with the new type. The previous check only denied a few types of the
typed path in the new type, so two more accepted ALTERs changed key values and
left parts unsorted (reported by the AI review on this PR, both reproduced):
- `JSON(a Enum8('2' = 0, '0' = 1, '1' = 2))` -> `JSON(a Int8)`: the Enum is
written as its names and the integer type parses the names, [0,1,2] becomes
[2,0,1]. isSafeForKeyConversion allows Enum8 -> Int8, but only for the
binary representation.
- `JSON(a DateTime('Europe/Berlin'))` with another typed path added: DateTime
text is local time, so the two instants of the repeated hour of a DST change
read back as one; the debug build then aborts on a keyed lookup.
Now the typed path must keep its type (LowCardinality aside) and every type in
it must be one of integers except Bool, String, FixedString, Enum, UUID, IPv4,
IPv6, Date, Nullable, LowCardinality, Array. Bool and Date32 are left out because
a value out of range, read from a binary format, is clamped by the round trip
(raw Bool 2 -> 1, Date32 2147483647 -> 2932896; with PARTITION BY data.a a keyed
count then misses the row). Measured to round trip exactly:
Int128/Int256/UInt256 limits, UInt64 max, String with invalid UTF-8 and escapes,
FixedString with zero bytes, LowCardinality(String) -> String. Newly refused
(values were kept, but nothing guarantees it under all format settings):
DateTime/DateTime64 in UTC, Time, typed Tuple paths, Enum widening below a
changed JSON level, in-range Bool and Date32.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`conversionKeepsSubcolumnValues` recursed into the rest of the subcolumn name at every dotted prefix, and each recursion visited the deeper prefixes again, so the check took time exponential in the nesting depth: for `c Tuple(a Tuple(a ...), b UInt32)` with the key `c.a.a...` the ALTER that only changes `b` took 18 s at depth 20 on a debug build (0.03 s on master). The result for a level depends only on the two types and the remaining name, so it is now computed once per level and reused. No accept/reject decision changes: 04811 and the JSON probe matrix give identical output. At depth 20 the check takes 0.02 s, at depth 50 0.3-0.5 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y stream Two gaps in `conversionKeepsSubcolumnValues`: 1. Below a changed JSON level the allow-list excluded `Bool` by its name. `SimpleAggregateFunction(any, Bool)` has another name but keeps the `Bool` serialization of its storage type, so a binary value 2 was written as `true` and read back as 1 while the part stayed in the partition of 2 (`countIf(data.a = 1)` 2, `WHERE data.a = 1` 1). A type with a custom serialization is now refused, whatever its name. 2. At an array level the check descended into the elements whenever they had a subcolumn of the key's name. `JSON` has a subcolumn of every name and a `Tuple` can have an element `size0`, so `ORDER BY a.size0` with `a Array(JSON(x Int64))` refused an ALTER of the JSON that master accepts. The resolved substream path now decides: a key that reads only array sizes is kept by any array to array conversion. 04811: a reject block for the `SimpleAggregateFunction(any, Bool)` partition key, and allow blocks for `Array(JSON)` `size0`, `Array(Tuple(size0 ...))` `size0` and `Array(Array(JSON))` `size1`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ollection `CAST` keeps the offsets of an array at every level, except that a geometry converted to its collection type becomes a collection of one (`FunctionCast::createArrayWrapper`): `LineString` -> `MultiLineString` and `Polygon` -> `MultiPolygon` add an array level, so `a.size0` of a `LineString` becomes 1 for every row. The `sizeN` shortcut accepted any pair of arrays, so `PARTITION BY a.size0` with `ALTER ... MODIFY COLUMN a MultiLineString` left the rows in the partitions of the old sizes (`countIf(a.size0 = 1)` 2, keyed `count()` 0); the same for `Array(LineString)` -> `Array(MultiLineString)` with `a.size1`, a `Tuple` element (`c.g.size0`) and `Map` values (`m.values.size1`). Walk the array levels the key reads and refuse a level whose type has a custom name and changes the number of dimensions. Outer sizes of an array of geometries (`Array(LineString)` -> `Array(MultiLineString)` with `a.size0`, `Array(Point)` -> `Array(MultiPoint)`) are kept by the conversion and stay allowed, as do `Ring` -> `LineString` and the plain array cases. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rs under a changed JSON Below an `Array` level the element type names the same sizes `size<N-1>`, because `sizeN` counts the array levels from the root. The check passed the original `sizeN` name down, which the element type resolves to another stream or to nothing: with `a Array(Tuple(arr Array(JSON(x Int64)), b UInt8))` and `ORDER BY a.arr.size1`, adding a path to the JSON was refused because `arr.size1` resolved to the JSON path `size1`, while master accepts it and keeps the sizes; the same for `Array(JSON(x Array(Int64)))` with `a.x.size1`. Now the key's own sizes are checked at their level, and a key below the level is renamed for the element type and must resolve to the same stream there, else the ALTER is refused. RapidJSON (`allow_simdjson = 0`, or a build without simdjson) parses an integer outside the 64-bit range as `Float64`, so a `JSON -> JSON` conversion with a typed `UInt128` key path turned `18446744073709551617` and `18446744073709551618` into `18446744073709551616` and left the rows in their old partitions. Only integers of at most 64 bits are now kept below a changed JSON level. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| if (re2::RE2::PartialMatch(prefix, compiled)) | ||
| return true; | ||
| } | ||
| return false; |
There was a problem hiding this comment.
skipsJSONPath hard-codes RE2::PartialMatch, but the JSON reparse path used by the mutation does not: SerializationJSON::deserializeObject forwards settings.json.type_json_use_partial_match_to_skip_paths_by_regexp, and JSONExtractTree switches between PartialMatch and FullMatch based on that setting.
With type_json_use_partial_match_to_skip_paths_by_regexp = 0, an ALTER like JSON(b.c Int64) -> JSON(b.c Int64, SKIP REGEXP 'c') keeps data.b.c unchanged, yet this eligibility check still rejects it. That makes the gate diverge from the actual mutation semantics for a supported setting. Please thread the setting into skipsJSONPath (or reuse the same helper the parser uses) instead of assuming partial-match mode here.
CI finish ledger - 4ab3118Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261105-033004 |
|
Fixing PR for the La Casa Del Dolor (amd_tsan) / Server shutdown failure created: #129440 |
|
@Avogar would you please review this? |
`StorageKeeperMap::dropTableData` removed the keys with `ZooKeeper::removeChildrenRecursive`, which calls `getChildren` on every child before removing it. KeeperMap keys are always leaf nodes (`data/<url-safe base64 key>`), so a drop of N keys cost N empty `List` round trips plus N/100 multi requests, serialized on one session. Use `tryRemoveChildrenRecursive(path, /*probably_flat=*/ true)`, which TRUNCATE already uses for the same `data/` node: one `List` of `data/`, then removals in batches of 100. If a batch fails with a user error it falls back to per-node removal and removes a non-empty child recursively; hardware errors still throw. The final multi that removes `data/` and the metadata still reports leftovers as before. The drop runs in the background drop task, and server shutdown waits for it, so a large KeeperMap drop in flight held shutdown: La Casa Del Dolor (amd_tsan) force-killed the server after 30 s while a dropped table's keys were still being walked, ~1000 batches of 100 into the drop (Keeper commit log of PR ClickHouse#129287's run). Measured on a debug build with the embedded Keeper, 200000 keys: DROP TABLE ... SYNC 133.6/141.4/176.0 s -> 11.3/11.3/11.3 s; SIGTERM right after a non-SYNC DROP until exit 194.3/161.5/153.8 s -> 13.8/14.4/13.9 s; per-key List requests 200000 -> 0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ALTER TABLE ... MODIFY COLUMNaccepting a change that keeps the type of a key subcolumn but changes its values, for example turning itsNULLs into defaults (JSON(a Nullable(Int64))->Nullable(JSON(a Int64))withORDER BY data.a) or aJSON->JSONchange that reads the key path differently after parsing the data again. The parts were left unsorted by the key, so queries filtering by the key returned wrong results. Such anALTERis now rejected.Description
On 26.8.18.2, with
data JSON(a Nullable(Int64)),ORDER BY data.aandallow_nullable_key = 1,ALTER TABLE t MODIFY COLUMN data Nullable(JSON(a Int64))is accepted andSELECT count() FROM t WHERE data.a = 0returns 11 instead of 7. Debug builds abort withEqual values are not contiguous within the range assumed to be sorted; the AST fuzzer found it on master: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=0d05beed67cdf5fb3a3beefe96c41f95d86c0ddb&name_0=MasterCI&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29#113862 allows such an
ALTERwhen the key subcolumn type converts safely. Below aNullablelevel a subcolumn isNullableeither way, sodata.astaysNullable(Int64)while the conversion turns everyNULLof it into0. The mutation does not re-sort, so the part ends up unsorted.The check compares every level on the way to the key subcolumn (
Nullable,Array, named elements) in the mutation and lazy metadata-only paths. The same substream must answer the key subcolumn name, aMapkey subcolumn needs the same key type, and no key may read the sizes of a geometry turned into a collection of one (LineString->MultiLineString). AJSON->JSONconversion writes the data as text and parses it with the new types, so below a changedJSONlevel the key must read a typed path that keeps its type, is notSKIPped, has no typed path above it, and whose type reads its text back unchanged: integers up to 64 bits without a custom serialization,String,FixedString,Enum,UUID,IPv4,IPv6,Date, inNullable,LowCardinalityorArray. Others do not: an integer type parsesEnumnames,DateTimetext is local time. Dynamic and combined@key paths are rejected; declaring the key path with such a type allows theALTER. Value-keeping changes (aNullablelevel above aNullableleaf,Variant->Dynamic, other paths) stay allowed.04811_alter_column_type_with_key_subcolumnsis extended with the rejected shapes and fails on master.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/129287]