Repository navigation
Conversation
…ructure check The partition and sorting key checks in checkStructureAndGetMergeTreeData compared the raw definition AST as text, so a single-column key stored as 'a' on one table and 'tuple(a)' on another was rejected even though both describe the same key. The two forms are serialized differently across versions, so this broke partition manipulation across an upgrade boundary. Compare KeyDescription::expression_list_ast (which unwraps tuple(...)) as the primary-key check already does. Genuinely different keys are still rejected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-5:20260717-100900 |
|
cc @CurtizJ @alesapin — could you review? Small fix in |
|
It's wrong fix. |
Either "it's a wrong fix" or "it's wrong to fix". |
|
Could you please clarify why it's bad? I've made this fix for the primary key in tables. What you want to do is to compare AST, not the text representation. We can do it everywhere. |
|
Workflow [PR], commit [d78bdc6] Summary: ❌
AI ReviewSummaryThe PR replaces formatted-text comparisons of stored table definitions with AST comparisons, preserving compatibility serialization and strengthening AST hashing. One new JSON validation gap remains: an accepted normalized set operation can reach execution without satisfying its binary-input invariant. Request changes for this Major finding; the previously discussed findings are addressed or their explanations hold. Findings
The normalized representation was traced through cloning, formatting, hashing/cache-key construction, both normalization visitors, and query-tree construction/planning. Cloning and hashing preserve its state, formatting accepts the operand list, the visitors skip it, and execution imposes the missing binary-input requirement. Tests
Missing context / blind spots
Final VerdictStatus: Validate normalized set-operation arity at the JSON boundary and add the focused regression. |
|
Reference: #108590 |
The previous compare used KeyDescription::expression_list_ast, which drops the per-column sort direction stored in reverse_flags. ORDER BY a and ORDER BY a DESC therefore compared as equal, so REPLACE/MOVE/ATTACH PARTITION could accept parts laid out in the opposite sort direction, violating the target table ordering. Use getOriginalExpressionList() for the sorting key: it unwraps tuple(...) (so a vs tuple(a) still matches) and re-attaches the direction from reverse_flags (so a vs a DESC stays rejected). Partition key keeps the plain normalized compare since it has no direction. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed 47d0303 addressing the AI-review Block. The sorting-key compare now uses Added the requested reverse-key case to On the parse-then-reformat-then-compare approach: the concern was only that |
CI finish ledger - 47d0303CI fully finished on this head (Finish Workflow = SUCCESS 22:43 UTC). Every failure below has an owner.
Not PR-caused: this PR only changes the MergeTree partition/sorting-key AST comparison; the failing test exercises Replicated-database structure ALTER, an unrelated chronic flaky already owned by #110030. Session id: cron:our-pr-ci-monitor:20260718-000000 |
…on-tuple-key-normalization
CI finish ledger — 81f383dFresh CI (after the master merge into this branch) finished. The only red is a known unrelated flaky; the fix is not on
Everything else is green. This PR carries no CI regression; it remains blocked only on the design discussion (comparing normalized |
There was a problem hiding this comment.
@groeneai Please take all compatibility tests from this PR #110840 and make sure all them work. Please implement fix at the level of KeyDescription, TTLDescription and other structures in StorageInMemoryMetadata. Introduce a special method for them which format their AST into backward compatible way.
|
@alesapin Understood. I'll rework the fix: add a backward-compatible AST formatting method on the metadata structures (KeyDescription, TTLDescription, and the other keys in StorageInMemoryMetadata) that normalizes the single-element |
Move the a/(a)/tuple(a) key normalization into a reusable method on the metadata structure: KeyDescription::formatBackwardCompatibleOneLine() unwraps the single-column tuple, strips redundant parentheses, and keeps the per-column sort direction. checkStructureAndGetMergeTreeData now compares sorting, partition and primary keys through it, so tables whose keys were stored differently across versions (ClickHouse#92340 started preserving parentheses and the tuple(a) form) stay compatible for ATTACH/REPLACE/MOVE PARTITION, while genuinely different keys (a vs b, a vs a DESC) still differ. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 2 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-0:20260720-105100 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260720-105100 |
|
Moved the normalization onto the metadata structure as you asked: On #110840's tests: the comparison ones pass here. I brought in So the two PRs are complementary: #110840 canonicalizes at parse/format time, this one at compare time. Happy to fold the parser change in here instead if you would rather have a single self-contained PR. |
|
🕵 Pass on 2026-11-03.
|
`ASTIdentifier::updateTreeHashImpl` hashed only `full_name` (via `getID`), so ``db.`inner.t` `` and `` `db.inner`.t`` had the same tree hash although they refer to different tables. Since stored definitions are now compared with `sameAST`, a replica with a genuinely different constraint could join, and replacing such a constraint with `ALTER` was silently ignored. Hash the component count and the length-prefixed components when any component contains a dot (only then are the boundaries ambiguous), so the hash of ordinary identifiers does not change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pass on 2026-11-05.
|
…on-tuple-key-normalization Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Pass on 2026-11-10.
|
|
🕵 Pass on 2026-11-12.
|
# Conflicts: # src/Parsers/tests/gtest_tree_hash_completeness.cpp # src/Storages/MergeTree/ReplicatedMergeTreeTableMetadata.h # src/Storages/StatisticsDescription.h
|
🕵 Pass on 2026-11-18.
|
|
🕵 Pass on 2026-11-20.
|
|
🕵 Pass on 2026-11-20.
@groeneai, investigate the |
|
I looked at that run. The
The fix is already in progress: #133083 ( |
|
🕵 Pass on 2026-11-20.
|
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=4 K_base=11 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
|
🕵 Pass on 2026-11-20.
|
# Conflicts: # src/Storages/ProjectionsDescription.cpp
|
🕵 Pass on 2026-11-22.
|
…eeper `StorageReplicatedMergeTree::checkTableStructureAttempt` compared the in-memory columns with the columns parsed from ZooKeeper. Since `ColumnDefault::operator==` compares the expressions with `sameAST`, in-memory AST state that the serialized text does not carry made equal definitions differ: `AddDefaultDatabaseVisitor` turns the table of `ALIAS p IN some_table` into an `ASTTableIdentifier`, which is written as `p IN (db.some_table)` and parsed back as a plain `ASTIdentifier`. A replicated `CREATE` of such a table failed with `INCOMPATIBLE_COLUMNS` against the columns it had just written, although both sides print the same text. Serialize and parse the local columns first, so both sides are in the stored form. This fixes `05075_mutation_partition_pruning_table_in_set`, a test added on `master` after this branch, in Fast test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110833&sha=cc4ad2c25e9174fe0333b82563b2434f273229b3&name_0=PR&name_1=Fast%20test ClickHouse#110833 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Pass on 2026-11-23.
|
| JSONObjectReader r(json); | ||
|
|
||
| union_mode = parseSelectUnionMode(r.getString("union_mode", "UNION_DEFAULT")); | ||
| is_normalized = r.getBool("is_normalized"); |
There was a problem hiding this comment.
[Major] Validate the operand count before accepting a normalized INTERSECT/EXCEPT.
Setting is_normalized from JSON makes both SelectIntersectExceptQueryVisitor and NormalizeSelectWithUnionQueryVisitor skip this node, but the reader accepts an arbitrary number of operands with union_mode = EXCEPT_ALL, EXCEPT_DISTINCT, INTERSECT_ALL, or INTERSECT_DISTINCT. QueryTreeBuilder then passes all operands to the planner, whereas IntersectOrExceptTransform has exactly two inputs.
Reproduced by encoding SELECT 1 EXCEPT ALL SELECT 2 EXCEPT ALL SELECT 3 as a SelectWithUnionQuery with three selects, union_mode = EXCEPT_ALL, and is_normalized = true: execution through dialect = 'clickhouse_json' throws LOGICAL_ERROR (code 49), reporting two input ports where the pipeline expects three. Supplying the two matching list_of_modes entries does not help because this branch ignores them. The same JSON with is_normalized = false and the equivalent SQL both return 1. All four explicit INTERSECT/EXCEPT modes reproduce the internal exception.
Please reject non-binary normalized set operations with BAD_ARGUMENTS, or lower them to binary nodes before treating them as normalized, and add a focused JSON execution/deserialization regression. The probe used PR binary 82ff4fd9da2e; this parser file is byte-identical at the current head.
AI review of a later commit does not approve the PR, see the AI Review comment.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed cross-version metadata compatibility for tables whose keys and other definition expressions were written with redundant parentheses (
PARTITION BY (a),ORDER BY (b, c),DEFAULT (a + 1),TTL (d + INTERVAL 10 YEAR),INDEX ix (b * c),CONSTRAINT c CHECK (a > 0),PROJECTION p (SELECT (b) ...)) or with an explicit single-elementtuple(a). #92340 started preserving these parentheses in stored metadata, soATTACH/REPLACE/MOVE PARTITION FROMbetween two such tables failed withTables have different ...even on a single server version, and a replica reading metadata written by another version failed withMETADATA_MISMATCH. Stored table definition expressions are now compared by their ASTs (getTreeHash), not by their formatted text.Description
#92340 started to preserve redundant parentheses in the stored definition ASTs. Older versions stored the canonical form without them, so the metadata serialized by the two versions differs, and every comparison (
ReplicatedMergeTreereplica join,ATTACH/REPLACE/MOVE PARTITION FROM) rejected definitions that are actually equal.Two sub-cases with different affected ranges:
PARTITION BY (a)vsPARTITION BY a). This is the Fix inconsistent formatting by remembering if an expression was parenthesized #92340 regression: measured on released binaries, 25.8, 26.3 and 26.4 acceptATTACH PARTITION FROMbetween the two forms while 26.5, 26.6 and 26.7 reject it, matching the branches that containb38a892dfbfab6. It does not require an upgrade or a mixed-version cluster: both tables created by the same 26.7 binary already fail, because the comparison is between two in-memory ASTs of which only one carries theparenthesizedflag.tuple(a)vsa. This one fails on every version tried, 25.8 included, so it is a long-standing bug rather than a Fix inconsistent formatting by remembering if an expression was parenthesized #92340 regression. It is fixed here as well becauseextractKeyExpressionListunwraps the optionaltuple(...).Following #110833 (comment), this replaces the earlier text-canonicalization approach entirely:
getTreeHash, not as text or reformatted text. Comparing formatted text is wrong because the text depends on the formatting logic, which can change for unrelated (e.g. aesthetic) reasons, while the stored form may have been written by any past server version.sameASTinsrc/Parsers/IAST.h(aliases significant,nullptr-tolerant overload for optional expressions).ReplicatedMergeTreeTableMetadata::checkImmutableFieldsEquals/checkEquals/checkAndFindDiff(replica join,ALTERapplication). The stored strings are parsed purely syntactically (without resolving against any column set), so the fields of anALTERlog entry that adds a column and changes a key in one go compare safely; thecolumns/contextparameters are gone. Keys additionally go throughextractKeyExpressionList, soa,(a)andtuple(a)are the same single-column key whilea DESCstays different.MergeTreeData::checkStructureAndGetMergeTreeData(theATTACH/REPLACE/MOVE PARTITION FROMstructure gate): sorting/partition/primary keys and the secondary-index/projection definition sets.StorageReplicatedMergeTree::checkTableStructureAttempt: the columns comparison (ColumnsDescription/ColumnDescription/ColumnDefaultequality now compares the default/codec/TTL expressions as ASTs). The column-by-column comparison also has to ignore in-memory-only state that is never serialized (implicit statistics and the auxiliarydata_typeofColumnStatisticsDescription, hence the newhasSameExplicitStatistics), otherwise every replicatedCREATEwould reportINCOMPATIBLE_COLUMNSagainst the columns it had just written to ZooKeeper.StorageReplicatedMergeTree::alter: detection of which metadata fields anALTERactually changed. The changed fields are also written back to Keeper through the same backward-compatible serializers theReplicatedMergeTreeTableMetadataconstructor uses (formatDefinition/formatDefinitionList), so anALTERnever publishes a parenthesized definition that an older replica would reject.AlterCommand::isTTLAlter(whether restating a TTL schedules aMATERIALIZE TTLmutation) and theMODIFY ORDER BYno-op detection inAlterCommands::prepare.ProjectionDescription::operator==.getTreeHashto be a faithful identity of a definition, AST nodes that keep semantic state outside ofchildrennow hash that state (updateTreeHashImploverrides):ASTTTLElement(mode, destination,GROUP BYkeys/assignments, recompression codec),ASTIndexDeclaration(name, granularity),ASTConstraintDeclaration(name,CHECK/ASSUME),ASTProjectionDeclaration(name),ASTProjectionSelectQuery(which clause each child belongs to, previouslySELECT a GROUP BY bandSELECT a ORDER BY bhashed equally),ASTWindowDefinition(frame type and boundary kinds).getTreeHashdocuments the requirement, and the classes whose member set is the whole point of the override (ASTTTLElement,ASTIndexDeclaration,ASTConstraintDeclaration,ASTProjectionDeclaration,ASTWindowDefinition,ASTSetQuery,ASTWithElement,ASTWindowListElement) carry asizeofstatic_assert, so adding a member there fails to compile until it is considered.ASTSelectQuery,ASTProjectionSelectQueryandASTOrderByElementinstead iterate the clause/child-role enumerators, so a newly added one is hashed with no code change. The remaining overrides are not asserted:ASTColumnsApplyTransformer(which reaches theparametersandlambdasubtrees) andASTSelectWithUnionQueryhash more than one member,ASTWithAliasandASTSelectIntersectExceptQueryone each. Measured: thestatic_assertfires for a newString,UInt64or pointer member; a loneboolcan still fit in tail padding, which the comment covers.The negative tests found five ways the comparison was too permissive, each of which master rejects. They are fixed here and each is covered by a test that fails if the fix is reverted:
ColumnDescription::operator==usedIDataType::equals, which ignores theSimpleAggregateFunctionwrapper (asMergeTreeData::sortingKeyChangedalready documents), so a replica declaring a plainUInt64joined a table whose column isSimpleAggregateFunction(sum, UInt64). It comparesgetNamenow.hasSameExplicitStatisticskept only theStatisticsType, soSTATISTICS(tdigest(1))andSTATISTICS(tdigest(2))compared equal although the parameters are a part of the stored definition and surviveSHOW CREATE. The declaration ASTs are compared as well.parametersandlambdaofASTColumnsApplyTransformerare not children and were hashed withupdateTreeHashImpl, which stops at the node itself, so a projection usingAPPLY quantile(0.5)and one usingAPPLY quantile(0.9)hashed equally.stripArtificialParenscould not reach them either. Both now descend.fooIdentifier_barandbar AS Identifier_fooproduced the same byte stream and two projections with different output columns compared equal.ASTWindowDefinitionkeeps its frame type and boundary kinds outsidechildrenand did not hash them, so a projection aggregating overROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWcompared equal to one overROWS BETWEEN CURRENT ROW AND CURRENT ROW. The frame offsets are children and were already covered.One latent bug became reachable and is fixed too:
ASTTTLElement::cloneleftrecompression_codecshared with the source, andformatDefinitionclones the metadata AST specifically in order to canonicalize it, sostripArtificialParenswould have written into the live metadata snapshot of aRECOMPRESSTTL.No parser or formatter changes and no on-disk/
SHOW CREATEchanges: what the user wrote is preserved; only comparisons became insensitive to formatting. Genuinely different definitions still differ (avsb,avsa DESC, different index granularity,CHECKvsASSUME, different TTL destination). The comparison of wholeCREATEqueries duringRESTORE(compareRestoredTableDef) still compares text: it is a whole-query comparison rather than an expression comparison, and its failure direction is safe (refuses the restore).Tested with a real previous-version server (
clickhouse/clickhouse-server:26.4):tests/integration/test_backward_compatibility/test_parenthesized_keys.pyexercises a new replica joining an old table and vice versa, an old replica applying parenthesizedALTERlog entries written by the new version plus restarts of both replicas, and upgrade +ATTACH PARTITION FROM. Unit testsrc/Storages/MergeTree/tests/gtest_replicated_metadata_compare.cpplocks the comparison semantics including the negative cases. Stateless tests:03471_replace_partition_tuple_key_normalization,04604_parenthesized_partition_key_attach_from,04612_parenthesized_index_projection_attach_from,04622_modify_ttl_parenthesized_no_mutation,04646_projection_ttl_parenthesized_zk_metadata,04648_alter_parenthesized_zk_metadata,04650_replica_column_definition_mismatch_rejected,04693_projection_apply_function_name_case(the function name of a projection'sCOLUMNS(...) APPLYtransformer is canonicalized for the comparison only, soAPPLY SUMandAPPLY sumcompare equal while the stored definition keeps the as-written spelling that older replicas compare byte-for-byte; the transformer's own parameters stay significant, because their spelling names the physical projection columns:APPLY quantile(ABS(-0.9))producesquantile(ABS(-0.9))(b)),05401_replica_projection_apply_spelling_mismatch_rejected(a replica whoseAPPLYparameters differ only in spelling cannot join).Workflow [PR]
Sync PR [sync-upstream/pr/110833]