Skip to content

Forbid lazy JSON type-hint ALTER that would corrupt primary key or index - #112302

Merged
Avogar merged 17 commits into
masterfrom
json-lazy-type-hints-key-safety
Aug 10, 2026
Merged

Avogar merged 17 commits into
masterfrom
json-lazy-type-hints-key-safety

Conversation

@Avogar

@Avogar Avogar commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

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 into CHANGELOG.md):

Fixed a bug where ALTER TABLE ... MODIFY COLUMN that changes a JSON type hint (with allow_experimental_json_lazy_type_hints enabled) 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 with CANNOT_READ_ALL_DATA or returned wrong results. Such ALTERs 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

  • Merged into: 26.8.1.1097 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [50f6501]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
04561_ie_join_storage_join FAIL cidb IGNORED
Stress test (arm_asan_ubsan, s3) FAIL
Sanitizer (STID: 2064-22d0) FAIL cidb IGNORED

AI Review

Summary

This PR hardens lazy JSON type-hint ALTER ... MODIFY COLUMN by rejecting cases that would leave persisted MergeTree artifacts stale instead of rebuilt. The direction is correct, but one correctness hole remains: stored DEFAULT columns are still unprotected, so the lazy path can leave wrong on-disk values behind. I also found one previously discussed conservative check that still contradicts the PR's stated "unchanged on-disk type stays metadata-only" contract.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:5637] The new guard still ignores dependent DEFAULT columns even though ClickHouse treats DEFAULT the same as MATERIALIZED for insert-time storage. ColumnsDescription::getDefaultExpressionInfoInto explicitly classifies both kinds as stored values, but MutationsInterpreter only recalculates ColumnDefaultKind::Materialized, so k String DEFAULT reinterpretAsString(j.a) keeps stale bytes after MODIFY COLUMN j JSON(...) and even the suggested "disable allow_experimental_json_lazy_type_hints" fallback does not repair it. The fix needs either to reject dependent DEFAULT columns here too, or to extend the mutation path to rebuild them before recommending the non-lazy path.

⚠️ Majors

  • [dismissed by author -- https://github.com/Forbid lazy JSON type-hint ALTER that would corrupt primary key or index #112302#discussion_r3692398022] [src/Storages/MergeTree/MergeTreeData.cpp:5594] The guard still uses getName() equality as the proxy for "on-disk type changed", so byte-identical JSON hint changes such as UInt16 ↔ Date or UInt32 ↔ DateTime are rejected even though the PR description and docs say unchanged on-disk encodings remain metadata-only. I still consider this real because it narrows a documented safe path without any corruption risk; either the check should use the byte-identical conversion predicate, or the user-facing contract should be tightened to match the implementation.
Final Verdict

❌ Changes required before merge.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.60% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 153/170 (90.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 28, 2026
…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]>
@mintlify

mintlify Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 30, 2026, 4:07 PM

@mintlify

mintlify Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟡 Building – Jul 30, 2026, 3:45 PM

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]>
@Avogar
Avogar requested a review from a team as a code owner July 31, 2026 14:32
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]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.60% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 84/102 (82.35%) · Uncovered code

Full report · Diff report

`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`
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

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]>
@novikd novikd self-assigned this Aug 6, 2026
Avogar and others added 2 commits August 6, 2026 10:10
…: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]>
Avogar and others added 3 commits August 6, 2026 18:06
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]>

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@Avogar
Avogar added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit fa827a8 Aug 10, 2026
177 of 180 checks passed
@Avogar
Avogar deleted the json-lazy-type-hints-key-safety branch August 10, 2026 12:50
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
Avogar added a commit to Avogar/ClickHouse that referenced this pull request Aug 13, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Development

Successfully merging this pull request may close these issues.

4 participants