Repository navigation
Forbid lazy JSON type-hint ALTER that would corrupt primary key or index - #112302
Conversation
A JSON type-hint change (`ALTER TABLE ... MODIFY COLUMN ... JSON(...)` with `allow_experimental_json_lazy_type_hints`) is a metadata-only conversion: the on-disk serialization changes, but it is applied lazily (old parts are read with their old type and CAST, and merges rewrite them over time) instead of via a data mutation. Because it skips the mutation branch in `checkAlterIsPossible`, it also skipped the key/index immutability checks that live there. As a result, changing the type of a JSON typed path that is used (via a subcolumn) in the primary/sorting key, partition key, or an explicit skip index left the on-disk `primary.idx` / partition files / `skp_idx_*` serialized with the old type but read back with the new one. Ordinary column reads reconcile this per part with a CAST, but those structures are read positionally without reconciliation, so after the in-memory index cache is dropped (e.g. a restart) queries failed with `CANNOT_READ_ALL_DATA` or returned wrong results. Split `isMetadataOnlyConversion` into two categories: - `isTrueMetadataOnlyConversion`: byte-identical changes (e.g. `Date` <-> `UInt16`, enum widening), safe everywhere. - `isLazyMetadataConversion`: serialization changes applied lazily (currently the JSON type-hint change), which are not safe for positionally-persisted structures. `checkAlterIsPossible` now has a dedicated branch for lazy conversions that rejects the ALTER when it changes the result type of the primary/sorting key, partition key, or an explicit skip index that depends on the column. The check compares the recomputed key/index result types (not mere participation), so stable-result-type expressions such as `ORDER BY toString(j.a)` remain metadata-only. Lossy changes on plain columns are still accepted and fail on read; projections are safe for JSON (subcolumns cannot appear in a projection and whole JSON cannot be a projection key). Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [50f6501] Summary: ❌
AI ReviewSummaryThis PR hardens lazy JSON type-hint Findings❌ Blockers
Final Verdict❌ Changes required before merge. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 153/170 (90.00%) · Uncovered code |
…uard The previous guard compared the *result type* of the primary/sorting key, partition key, or skip-index expression before and after a lazy JSON type-hint `ALTER`. That is insufficient: a type-sensitive expression can keep the same result type while the bytes it persists change. For example `reinterpretAsString(j.a)` stays `String` when `j.a` goes from `Int32` to `Int64`, but writes 4 bytes vs 8 (and a different string for negatives) into `primary.idx` / partition files / `skp_idx_*`. The old check let such an `ALTER` through, so after the in-memory index was dropped (e.g. a restart) the stale on-disk bytes were misread with the new type. Compare instead the on-disk types of the subcolumns the expression reads. The new helper `expression_uses_changed_subcolumn` walks `getRequiredColumns`, keeps only the (sub)columns belonging to the altered column, and rejects the `ALTER` when any such (sub)column is removed or resolves to a different type in the post-`ALTER` schema. This is conservative: it also rejects value-preserving wrappers such as `toString(j.a)`, since losslessness of the persisted value cannot be proven statically. Changes that leave the on-disk type of every fed subcolumn unchanged (e.g. adding an unrelated typed path) stay metadata-only. Extend the test with the type-sensitive `reinterpretAsString(j.a)` scenario in both `ORDER BY` and a skip index, and flip the two `toString(j.a)` cases to the new (rejecting) behavior. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The "Lazy Type Hints" section presented every add/modify type-hint `ALTER` as metadata-only, which no longer holds after the guard added in this PR. Add a Limitations bullet listing the rejected cases (a typed-path subcolumn used in the primary/sorting key, partition key, or an explicit data skipping index) with the remediation for each, and note under "Verifying No Mutation Occurred" that it applies only to the allowed changes. Mirror the same text in the embedded documentation string in `DataTypeObject.cpp`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
The docs check failed with `markdownlint` `MD007/ul-indent` on the nested bullets under the lazy type-hint limitations list in `newjson.md`: they were indented 4 spaces where the linter expects 2. Reduce them to 2 spaces, and apply the same fix to the mirrored documentation string in `DataTypeObject.cpp` so the two stay in sync. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The lazy-JSON guard in `MergeTreeData::checkAlterIsPossible` rejected a metadata-only type-hint change only when a changed subcolumn feeds the primary/sorting key, partition key, or a skip index. It skipped projections, on the assumption that a projection cannot reference a JSON subcolumn at all. That assumption is wrong: a projection can sort on a subcolumn when the whole parent column is also selected, e.g. `ADD PROJECTION p (SELECT id, j ORDER BY j.a)`. Its `ORDER BY` builds the projection's own `primary.idx`, serialized positionally just like the main sorting key. A metadata-only `ALTER ... MODIFY COLUMN j JSON(a Int64)` then leaves that index holding `Int32` bytes read back as `Int64`, so a range query through the projection fails with `CANNOT_READ_ALL_DATA`. Extend the guard to also check each projection's sort-key expression with the existing `expression_uses_changed_subcolumn` helper (with a dropped-in-the-same-ALTER exemption), and reject the change, pointing the user to drop the projection first. A projection that merely stores the whole JSON column without sorting on the subcolumn stays metadata-only (read back with per-part CAST like any column). Co-Authored-By: Claude Opus 4.8 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 84/102 (82.35%) · Uncovered code |
`master` moved the documentation from the Docusaurus tree under `docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every file this branch edits. The edits are replayed at the new paths: - `docs/en/sql-reference/data-types/newjson.md` -> `docs/reference/data-types/newjson.mdx`
Build profile diff (arm_release)No arm_release build profile data for commit 50f6501 - the build was skipped, reused from cache, or predates profile upload. |
…ource The Mintlify docs migration made `docs/reference/data-types/newjson.mdx` a generated file whose body is fenced by `AUTOGENERATED` markers; the docs `check_autogenerated_regions` guard rejects direct edits to it. The lazy JSON type-hint limitations added by this PR already live in the generator source (the embedded documentation in `src/DataTypes/DataTypeObject.cpp`), so revert the hand-edit to the generated `.mdx`. The nightly autogenerated-docs job regenerates it from the source. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Condense the comments added by this PR in the lazy-conversion guard and the metadata-only-conversion helpers: drop the over-long rationale and the `reinterpretAsString`/`toString` examples, keeping only the non-obvious points. No behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…:ClickHouse/ClickHouse into json-lazy-type-hints-key-safety
…dices and projection group keys The lazy-conversion guard in checkAlterIsPossible only covered the primary/sorting key, partition key, explicit skip indexes and projection sort keys. Reviewers pointed out three more positionally-persisted structures a changed subcolumn can corrupt when the ALTER is metadata-only: - Stored MATERIALIZED columns: computed at insert and stored; the lazy branch skips the mutation that would recompute them, so `SELECT k` returns stale bytes with no error. Reject such changes (a full mutation recomputes the column). - Implicit indices: the check skipped `isImplicitlyCreated()` indexes, but an auto-minmax index on an ALIAS backed by a subcolumn resolves its required columns to that subcolumn and goes stale the same way. Check them like explicit indexes. - Aggregate projection group keys: an expression group key is stored under the group expression's output name, so `getSortingKey()` misses it; analyze the GROUP BY against the base columns too (defensive; not reachable until projections can ingest subcolumns, but harmless and conservative). Refactor the subcolumn-change check into a name-based helper reused by all cases. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A filtered projection's WHERE decides which rows are materialized at insert. A
lazy JSON type-hint change that flips the predicate result (e.g. Int32 -> Bool
changes `toString(j)` from `{"a":0}` to `{"a":false}`) leaves the stored row set
wrong, and a query routed to the projection returns too few rows. The projection
guard only checked the sort/group key, so extend it to also reject when the
changed subcolumn feeds `projection.where_clause_ast`.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
The guard rejected a lazy hint change feeding a MATERIALIZED column only when the column's expression referenced the subcolumn directly. A MATERIALIZED column can reach the subcolumn through an ALIAS (e.g. `a_alias ALIAS reinterpretAsString(j.a)`, `k MATERIALIZED a_alias`); its default expression is just the alias identifier, which does not resolve against physical columns, so the dependency was missed and `k` kept stale bytes after the change. Expand table ALIAS columns (as index expressions already do) before analyzing, so alias chains resolve to the base subcolumn. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… TreeRewriter The guard's subcolumn-dependency check for MATERIALIZED columns and projection group/WHERE keys used TreeRewriter + ExpressionAnalyzer (old-analyzer infra that is being removed) plus a manual ALIAS-expansion visitor. Replace that with a helper that resolves the expression via the query analyzer over a fake StorageDummy table (mirroring MutationsInterpreter's analyzer path): buildQueryTree -> QueryAnalyzer(only_analyze) -> collectSetsAndSourceColumns (keep_alias_columns=false) -> TableExpressionData::getSelectedColumnsNames(). The analyzer resolves ALIAS chains natively (dropping the manual visitor) and also resolves projection group-by SELECT aliases, so the aliased group-key case is now caught too. No manual ASTExpressionList and no exception-swallowing try/catch are needed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Improve the lazy JSON type-hint TTL rejection to quote the specific TTL expression that reads the changed subcolumn (its `expression_ast` or, when the subcolumn only appears in the WHERE, its `where_expression_ast`) instead of a generic "a TTL expression". Add ALLOW test cases proving the guard stays metadata-only when a *different* existing subcolumn's type changes while the guarded structure references an untouched one, for `ORDER BY`, `PARTITION BY`, a skip index, a `MATERIALIZED` column, and a TTL. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The lazy TTL guard only inspected a TTL's time expression and WHERE, missing GROUP BY assignments: those live in `TTLDescription::set_parts` as prebuilt `ExpressionActions`, not in an AST. A change like `TTL d GROUP BY id SET v = argMax(reinterpretAsString(j.a), d)` was accepted, leaving stale aggregated bytes in already-aggregated parts. Also soften the TTL rejection message to advise dropping the TTL instead of suggesting a full mutation: `getColumnDependencies` does not propagate a TTL's `where_expression_columns` or `set_parts` sources, so the full-mutation path would not reliably recompute `ttl_infos` for those cases either. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Dependencies of an index, a projection, a TTL or a MATERIALIZED column were resolved by comparing raw names, so an expression reading an ALIAS column was keyed under the alias instead of the columns it reads. ALTER MODIFY COLUMN of such a column then failed the mutation with UNKNOWN_IDENTIFIER, because an ALIAS cannot be read from a part, and an ALTER of a MATERIALIZED key column derived through an ALIAS was not rejected. Resolve every one of those expressions with the query analyzer instead, moving the resolver ClickHouse#112302 already had in MergeTreeData into a shared unit. It returns the columns an expression reads, not getSelectedColumnsNames(), which reports an ALIAS column under its own name; subcolumns come back as columns of their own, so callers fold them into the column they are stored in. This drops the TreeRewriter usage added for these checks and two more that master had. The same accessor fixes the lazy JSON type hint guard: it consulted the analyzer for MATERIALIZED expressions and so missed a column reading a changed JSON path, accepting a metadata-only ALTER that leaves that column stale with no mutation able to recompute it. A MATERIALIZED column is also recomputed in a stage that runs after the columns are read at their new type, with ALIAS columns substituted, so it does not depend on which analyzer builds the stage expression. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a bug where
ALTER TABLE ... MODIFY COLUMNthat changes a JSON type hint (withallow_experimental_json_lazy_type_hintsenabled) on a column whose subcolumn is used in the primary/sorting key, partition key, or an explicit skip index could corrupt the on-disk key or index. Ordinary reads masked it via the cached structure, but after it was reloaded (e.g. a server restart) queries failed withCANNOT_READ_ALL_DATAor returned wrong results. SuchALTERs are now rejected whenever they change the on-disk type of a referenced JSON subcolumn. Type-hint changes on columns outside those structures, or changes that leave the on-disk type of the referenced subcolumns unchanged (for example adding an unrelated typed path), remain metadata-only.Version info
26.8.1.1097(included in26.8and later)