Skip to content

Compare stored table definition expressions by AST instead of formatted text - #110833

Open
groeneai wants to merge 131 commits into
ClickHouse:masterfrom
groeneai:fix-replace-partition-tuple-key-normalization
Open

groeneai wants to merge 131 commits into
ClickHouse:masterfrom
groeneai:fix-replace-partition-tuple-key-normalization

Conversation

@groeneai

@groeneai groeneai commented Jul 17, 2026 •

Copy link
Copy Markdown
Collaborator

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 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-element tuple(a). #92340 started preserving these parentheses in stored metadata, so ATTACH/REPLACE/MOVE PARTITION FROM between two such tables failed with Tables have different ... even on a single server version, and a replica reading metadata written by another version failed with METADATA_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 (ReplicatedMergeTree replica join, ATTACH/REPLACE/MOVE PARTITION FROM) rejected definitions that are actually equal.

Two sub-cases with different affected ranges:

  • Redundant parentheses (PARTITION BY (a) vs PARTITION 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 accept ATTACH PARTITION FROM between the two forms while 26.5, 26.6 and 26.7 reject it, matching the branches that contain b38a892dfbfab6. 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 the parenthesized flag.
  • An explicit single-element tuple(a) vs a. 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 because extractKeyExpressionList unwraps the optional tuple(...).

Following #110833 (comment), this replaces the earlier text-canonicalization approach entirely:

  • Expressions are compared by their ASTs using 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.
  • The comparison method is reusable: sameAST in src/Parsers/IAST.h (aliases significant, nullptr-tolerant overload for optional expressions).
  • It is applied at every place where serialized, stored expressions are compared to check whether the table was altered or changed unexpectedly:
    • ReplicatedMergeTreeTableMetadata::checkImmutableFieldsEquals / checkEquals / checkAndFindDiff (replica join, ALTER application). The stored strings are parsed purely syntactically (without resolving against any column set), so the fields of an ALTER log entry that adds a column and changes a key in one go compare safely; the columns/context parameters are gone. Keys additionally go through extractKeyExpressionList, so a, (a) and tuple(a) are the same single-column key while a DESC stays different.
    • MergeTreeData::checkStructureAndGetMergeTreeData (the ATTACH/REPLACE/MOVE PARTITION FROM structure gate): sorting/partition/primary keys and the secondary-index/projection definition sets.
    • StorageReplicatedMergeTree::checkTableStructureAttempt: the columns comparison (ColumnsDescription/ColumnDescription/ColumnDefault equality 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 auxiliary data_type of ColumnStatisticsDescription, hence the new hasSameExplicitStatistics), otherwise every replicated CREATE would report INCOMPATIBLE_COLUMNS against the columns it had just written to ZooKeeper.
    • StorageReplicatedMergeTree::alter: detection of which metadata fields an ALTER actually changed. The changed fields are also written back to Keeper through the same backward-compatible serializers the ReplicatedMergeTreeTableMetadata constructor uses (formatDefinition / formatDefinitionList), so an ALTER never publishes a parenthesized definition that an older replica would reject.
    • AlterCommand::isTTLAlter (whether restating a TTL schedules a MATERIALIZE TTL mutation) and the MODIFY ORDER BY no-op detection in AlterCommands::prepare.
    • ProjectionDescription::operator==.
  • For getTreeHash to be a faithful identity of a definition, AST nodes that keep semantic state outside of children now hash that state (updateTreeHashImpl overrides): ASTTTLElement (mode, destination, GROUP BY keys/assignments, recompression codec), ASTIndexDeclaration (name, granularity), ASTConstraintDeclaration (name, CHECK/ASSUME), ASTProjectionDeclaration (name), ASTProjectionSelectQuery (which clause each child belongs to, previously SELECT a GROUP BY b and SELECT a ORDER BY b hashed equally), ASTWindowDefinition (frame type and boundary kinds).
  • Since a member that is not a child and is not hashed silently makes two different definitions compare equal, getTreeHash documents the requirement, and the classes whose member set is the whole point of the override (ASTTTLElement, ASTIndexDeclaration, ASTConstraintDeclaration, ASTProjectionDeclaration, ASTWindowDefinition, ASTSetQuery, ASTWithElement, ASTWindowListElement) carry a sizeof static_assert, so adding a member there fails to compile until it is considered. ASTSelectQuery, ASTProjectionSelectQuery and ASTOrderByElement instead 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 the parameters and lambda subtrees) and ASTSelectWithUnionQuery hash more than one member, ASTWithAlias and ASTSelectIntersectExceptQuery one each. Measured: the static_assert fires for a new String, UInt64 or pointer member; a lone bool can 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== used IDataType::equals, which ignores the SimpleAggregateFunction wrapper (as MergeTreeData::sortingKeyChanged already documents), so a replica declaring a plain UInt64 joined a table whose column is SimpleAggregateFunction(sum, UInt64). It compares getName now.
  • hasSameExplicitStatistics kept only the StatisticsType, so STATISTICS(tdigest(1)) and STATISTICS(tdigest(2)) compared equal although the parameters are a part of the stored definition and survive SHOW CREATE. The declaration ASTs are compared as well.
  • parameters and lambda of ASTColumnsApplyTransformer are not children and were hashed with updateTreeHashImpl, which stops at the node itself, so a projection using APPLY quantile(0.5) and one using APPLY quantile(0.9) hashed equally. stripArtificialParens could not reach them either. Both now descend.
  • The alias was hashed without a length prefix, so fooIdentifier_bar and bar AS Identifier_foo produced the same byte stream and two projections with different output columns compared equal.
  • ASTWindowDefinition keeps its frame type and boundary kinds outside children and did not hash them, so a projection aggregating over ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW compared equal to one over ROWS 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::clone left recompression_codec shared with the source, and formatDefinition clones the metadata AST specifically in order to canonicalize it, so stripArtificialParens would have written into the live metadata snapshot of a RECOMPRESS TTL.

No parser or formatter changes and no on-disk/SHOW CREATE changes: what the user wrote is preserved; only comparisons became insensitive to formatting. Genuinely different definitions still differ (a vs b, a vs a DESC, different index granularity, CHECK vs ASSUME, different TTL destination). The comparison of whole CREATE queries during RESTORE (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.py exercises a new replica joining an old table and vice versa, an old replica applying parenthesized ALTER log entries written by the new version plus restarts of both replicas, and upgrade + ATTACH PARTITION FROM. Unit test src/Storages/MergeTree/tests/gtest_replicated_metadata_compare.cpp locks 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's COLUMNS(...) APPLY transformer is canonicalized for the comparison only, so APPLY SUM and APPLY sum compare 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)) produces quantile(ABS(-0.9))(b)), 05401_replica_projection_apply_spelling_mismatch_rejected (a replica whose APPLY parameters differ only in spelling cannot join).


Workflow [PR]
Sync PR [sync-upstream/pr/110833]

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Check Result
a Deterministic repro? Yes. CREATE TABLE tgt ... PARTITION BY a; CREATE TABLE tmp ... PARTITION BY tuple(a); ALTER TABLE tgt REPLACE PARTITION 1 FROM tmp -> Code 36 BAD_ARGUMENTS "Tables have different partition key" every time.
b Root cause explained? checkStructureAndGetMergeTreeData compares the partition/sorting keys by formatting the raw definition AST to text. a and tuple(a) format to different strings, so the syntactic != throws even though both are the same key. Across an upgrade the older table stores a and the newer table stores tuple(a) (#92340 changed single-element formatting), producing the mismatch.
c Fix matches root cause? Yes. Compare the normalized KeyDescription::expression_list_ast (which unwraps tuple(...) via extractKeyExpressionList) instead of the raw definition_ast, for both partition and sorting keys. Both a and tuple(a) reduce to [a]. Mirrors the primary-key check just below.
d Test intent preserved / new tests added? New stateless test 03471_replace_partition_tuple_key_normalization added: covers a<-tuple(a) for partition and sorting keys, plus negative cases (different column, different arity) that must still be rejected.
e Demonstrated in both directions? Yes. On master the test FAILS (Tables have different partition key); with the fix it PASSES (verified via clickhouse-test with randomized settings, and by A/B rebuild — baseline build id f140c53... fails, fixed build id fc92cdc... passes).
f Fix general, not a narrow patch? Both sibling checks (partition and sorting) are fixed, not just the reported partition one. Primary key already used the normalized form. Secondary-index/projection checks compare full definition ASTs, which is intentional (those are not tuple-wrapped keys).
g Generalizes across inputs? tuple(a)<->a handled for both partition and sorting keys; genuinely different keys (different column, different arity) still rejected. expression_list_ast normalization is column/type agnostic.
h Backward compatible? Yes. The change only makes the equality check accept more (semantically-equal) key pairs; it never rejects anything previously accepted. No setting, no on-disk/metadata format change. It removes a backward-incompatibility rather than adding one.
i Invariants and contracts preserved? Yes. The structure check still guarantees identical key semantics for partition manipulation; expression_list_ast is the analyzed key expression list used everywhere else for key identity, so no weaker guarantee is introduced.

Session id: cron:clickhouse-worker-slot-5:20260717-100900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review? Small fix in checkStructureAndGetMergeTreeData: partition and sorting key equality was comparing the raw definition AST, so a vs tuple(a) (same key, serialized differently across versions) was rejected by REPLACE/MOVE/ATTACH PARTITION after an upgrade. Now compares the normalized expression_list_ast, like the primary-key check already does.

@alesapin

Copy link
Copy Markdown
Member

It's wrong fix.

@alesapin alesapin closed this Jul 17, 2026
@alexey-milovidov

alexey-milovidov commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

@alesapin,

It's wrong fix.

Either "it's a wrong fix" or "it's wrong to fix".

@alexey-milovidov

Copy link
Copy Markdown
Member

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.
Comparing text representation is wrong, because it depends on the formatting logic. The formatting logic can change for unrelated reasons, e.g., aesthetic choice.
But we store text representations on disk and in Keeper.
So the question - how to compare AST if we store text representations? - We should parse the text representations and then compare ASTs.
How to compare ASTs? While we could do it by comparing the trees (getTreeHash), the more robust way is to serialize it, using the same formatter.
So the fix looks correct and perfect.

We can do it everywhere.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d78bdc6]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

The 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

⚠️ Majors

  • src/Parsers/ASTSelectWithUnionQuery.cpp:329: Validate the arity of normalized INTERSECT/EXCEPT nodes. Reading is_normalized = true makes both normalization visitors skip the node. The reader nevertheless admits three or more operands with an INTERSECT/EXCEPT mode. QueryTreeBuilder and Planner forward all operands to an IntersectOrExceptTransform that requires exactly two inputs, producing LOGICAL_ERROR (code 49). Reproduced for all four explicit modes. For three-operand EXCEPT ALL, equivalent SQL and JSON with is_normalized = false return 1; normalized JSON raises the internal exception even when matching list_of_modes entries are supplied. Reject invalid arity with BAD_ARGUMENTS, or lower the operation to binary nodes before marking it normalized.

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
  • ⚠️ Add a focused JSON regression for a normalized three-operand INTERSECT/EXCEPT, with a valid two-operand control. The current normalized-union tests cover UNION ALL and UNION DISTINCT only.
Missing context / blind spots
  • ⚠️ Validation for current head d78bdc602059 was still running. Runtime probes used the PR's 82ff4fd9da2e binary; ASTSelectWithUnionQuery.cpp is byte-identical at the reviewed head. Four focused stateless tests (04604, 04903, 05227, 05055) matched their references. The latest replicated-columns fix was reviewed in source; its server regression was not rerun locally.
Final Verdict

Status: ⚠️ Request changes

Validate normalized set-operation arity at the JSON boundary and add the focused regression.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 47d0303 addressing the AI-review Block.

The sorting-key compare now uses getSortingKey().getOriginalExpressionList() instead of expression_list_ast. That still unwraps tuple(...) (so a vs tuple(a) matches, the original regression), but re-attaches the per-column direction from reverse_flags, so ORDER BY a vs ORDER BY a DESC stays rejected. Partition and primary key keep the plain normalized compare since they carry no direction.

Added the requested reverse-key case to 03471_replace_partition_tuple_key_normalization: ORDER BY a rejects REPLACE PARTITION from ORDER BY a DESC, while a vs tuple(a) still passes.

On the parse-then-reformat-then-compare approach: the concern was only that expression_list_ast dropped the sort direction. getOriginalExpressionList() restores it, so the normalized-AST-via-formatter idea is intact.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 47d0303

CI fully finished on this head (Finish Workflow = SUCCESS 22:43 UTC). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (83 master + 40+ unrelated PRs in 30d; issue #110036) #110030 (ours, open)
Sync - CH Inc sync (private, not actionable)

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

@alexey-milovidov

Copy link
Copy Markdown
Member

CI finish ledger — 81f383d

Fresh CI (after the master merge into this branch) finished. The only red is a known unrelated flaky; the fix is not on master yet, so it re-appears here.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 2/3) — Server died / Unknown error flaky: race between EXCHANGE TABLES and SELECT in 03915_exchange_tables_race aborts with Logical error: Arguments of 'multiply' have incorrect data types (query SELECT n * 0.123 FROM (SELECT * FROM tbl_03007_1)). Not related to checkStructureAndGetMergeTreeData. issue #110133; candidate fixes #110048, #109747 (both open)

Everything else is green. This PR carries no CI regression; it remains blocked only on the design discussion (comparing normalized expression_list_ast vs. AST) and the human merge decision.

@alesapin alesapin 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.

@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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@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 tuple(a) vs a drift from #92340, and route the key/TTL comparisons through it instead of the ad-hoc check in MergeTreeData. I'll also bring in the compatibility tests from #110840 and get them all passing here (alongside the existing reverse-key regression). Follow-up with the reworked PR to come.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ Four unrelated dependency revisions (clickstack, krb5, silk, sz3) included in the fix DISAGREE git diff --name-only HEAD~1..HEAD lists ONLY the 7 intended source/test files. Those four are untracked working-tree submodule-pointer drift, never staged, never committed; the PR's changed-files list (7 files) confirms none are present.
2 ❌ Generated runtime files (access/*.list, preprocessed_configs/config.xml) included in the diff DISAGREE Untracked server-runtime artifacts created by the local test server used for verification. Not staged, not committed, absent from git diff HEAD~1..HEAD and from the PR's 7 changed files.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Both findings concern untracked local working-tree artifacts outside the committed diff, not the PR contents.

Session id: cron:clickhouse-author-slot-0:20260720-105100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE tgt ... PARTITION BY a; CREATE TABLE src ... PARTITION BY (a); INSERT INTO src ...; ALTER TABLE tgt ATTACH PARTITION 1 FROM src -> Code 36 Tables have different partition key every time (also Tables have different ordering for ORDER BY (a) vs ORDER BY a).
b Root cause explained? checkStructureAndGetMergeTreeData formatted each key AST to a one-line string and compared textually. #92340 started preserving redundant parentheses ((a)) and the single-column tuple(a) form, so a key stored by an old version (a) and a new one ((a)/tuple(a)) format to different strings and the syntactic != throws even though the key is identical.
c Fix matches root cause? Yes. KeyDescription::formatBackwardCompatibleOneLine() produces the canonical form (unwrap single-col tuple, strip the parenthesized flag, keep sort direction); the three key compares route through it, normalizing exactly the two formatting differences that caused the false mismatch.
d Test intent preserved / new tests added? 03471_... extended with the (a) parenthesized partition/primary/sorting cases plus kept negative cases; 04604_parenthesized_partition_key_attach_from imported from #110840. Negative guards (a vs b, a vs a DESC) still reject.
e Both directions demonstrated? Yes. Baseline binary (point-fix, Build ID a75463a3): (a) vs a FAILS for partition and ordering. Fixed binary (385ebb99): both SUCCEED; a vs b and a vs a DESC still REJECTED. 50/50 randomized: 100/100 OK.
f Fix is general across code paths? All three key compares (sorting, partition, primary) route through the one method, not just the reported partition case. Secondary-index/projection compares keep the full definition_ast (intentionally out of scope — not tuple-wrapped keys; that formatter canonicalization is #110840's parser-layer concern).
g Fix generalizes across inputs (params/datatypes/wrappers)? a / (a) / tuple(a) all normalize equal; multi-column (a, b) unaffected; sort direction preserved (a vs a DESC differ). Primary key has empty reverse_flags, so getOriginalExpressionList() returns expression_list_ast unchanged (paren strip only) — no behavior change beyond the intended normalization.
h Backward compatible? Yes. The compare only becomes more permissive (accepts semantically-equal keys); it never rejects a previously-accepted pair. No on-disk/wire/metadata format change, no setting. It removes a backward-incompatibility introduced by #92340.
i Invariants and contracts preserved? Yes. The structure check still guarantees identical key semantics for partition manipulation; direction is still enforced; genuinely different keys are still rejected. formatBackwardCompatibleOneLine() operates on a clone, so no AST is mutated in place.

Session id: cron:clickhouse-author-slot-0:20260720-105100

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alesapin done in 4412e19.

Moved the normalization onto the metadata structure as you asked: KeyDescription::formatBackwardCompatibleOneLine() takes the direction-aware expression list (getOriginalExpressionList(), unwraps the single-column tuple(...), keeps per-column direction) and strips the redundant parenthesized flag. checkStructureAndGetMergeTreeData now compares sorting, partition and primary keys through it. a, (a) and tuple(a) compare equal; a vs b and a vs a DESC still differ.

On #110840's tests: the comparison ones pass here. I brought in 04604_parenthesized_partition_key_attach_from and extended 03471 with the (a) cases (50/50 randomized OK). The rest of #110840's suite (04603 and the SHOW CREATE ... PARTITION BY a assertions in test_parenthesized_keys.py) checks formatQuerySingleLine/SHOW CREATE output, which comes from the parser and formatter and never goes through KeyDescription, so a comparison-side change cannot affect it. That is what your parser-layer fix in #110840 covers.

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.

@alesapin

Copy link
Copy Markdown
Member

@groeneai you should take integration test with real 26.4 from PR #110840. Also make sure to add the same formatBackwardComaptible method into TTL description and ColumnsDescription

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alesapin Will do. Bringing in the real-26.4 integration test from #110840 and adding formatBackwardCompatible to TTLDescription and ColumnsDescription as well; I'll follow up here with the reworked PR.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-03.

  • The only red on 07b9476b78be was Fast test: 05345_feature_tier_settings_profile_to_all timed out (issue Flaky test: 05345_feature_tier_settings_profile_to_all #128376, now closed). It has nothing to do with this PR. It comes from the one-minute DiskAccessStorage shutdown delay, which Avoid a one-minute shutdown delay after writing an access entity to disk #118099 fixed (merged to master as 97d3f4ff8c8f). Finish Workflow was red only because the Bugfix validation jobs were dropped after that failure.
  • Merged master (230ae8eec3e0) with no conflicts, so the fix is now in this branch. New head: 4ff3a754564c. The PR diff is unchanged (66 files), and master changed none of the PR's source files.
  • Built clickhouse incrementally with no errors. The non-replicated stateless tests (04604, 04622, 04903, 04926, 05317) pass via clickhouse local.
  • There are no unresolved review threads.

Comment thread src/Parsers/IAST.cpp Resolved
alexey-milovidov and others added 2 commits November 4, 2026 09:31
`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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-05.

  • The only red on 29e6d8376853 was Integration tests (arm_binary, 2/4): test_read_temporary_tables_on_failure/test.py::test_different_versions (DID NOT RAISE). It is unrelated to this PR: on 2026-11-04 it failed in about 40 PRs and on master. The fix Hold the query slot with a connected client in test_read_temporary_tables_on_failure #129151 is already merged to master.
  • Merged master (de6daf9f54e2) cleanly, which brings in that fix. The PR diff is unchanged (69 files). New head: db064fff112e.
  • All PR-touched translation units in src/Interpreters, src/Parsers and src/Storages compile on the merged tree.
  • There are no unresolved review threads.

…on-tuple-key-normalization

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-10.

  • Merged master (da9125b5eb3d) into db064fff112e. The only conflict was in the includes of src/Storages/AlterCommands.cpp: I kept both Storages/IndicesDescription.h from master and Storages/extractKeyExpressionList.h from this PR. The PR diff is still the same 66 files. New head: 6cc1d4314d20.
  • clickhouse builds locally. These stateless tests pass under clickhouse local: 03471, 04604, 04612, 04622, 05227, 05317.
  • There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-12.

  • The only red on 6cc1d4314d20 was CH Inc sync: the private sync PR had become CONFLICTING with private master. The conflict was in the includes of src/Storages/AlterCommands.cpp, the same one resolved in the last public master merge. I kept both Storages/IndicesDescription.h and Storages/extractKeyExpressionList.h, merged the current public head, and pushed 35801f180be6 to the sync branch. The sync PR is MERGEABLE again. Its diff against private master matches this PR's diff file for file, apart from the existing private-only adaptation in StorageSharedMergeTree.cpp, which is unchanged.
  • The Bugfix validation (functional tests) failures are expected: the new tests fail on unpatched master, which is the point of that check. Every other check is green.
  • There are no unresolved review threads, and this pass made no change to the PR branch.

# Conflicts:
#	src/Parsers/tests/gtest_tree_hash_completeness.cpp
#	src/Storages/MergeTree/ReplicatedMergeTreeTableMetadata.h
#	src/Storages/StatisticsDescription.h
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-18.

  • Merged master (3634df08ebb7) into 6cc1d4314d20; new head c87ed662f87a. Three trivial conflicts, both sides kept: includes in src/Parsers/tests/gtest_tree_hash_completeness.cpp (added ASTLiteral.h from master), and master's new [[nodiscard]] on checkEquals (ReplicatedMergeTreeTableMetadata.h) and on empty (StatisticsDescription.h), applied as well to the PR's hasSameExplicitStatistics.
  • The PR diff is unchanged (69 files). clickhouse and the gtest translation unit build. The PR's stateless tests that do not need ZooKeeper pass locally.
  • No unresolved review threads.

clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-20.

  • On c87ed662f87a the only real red was CH Inc sync (Failed. Needs manual intervention). The bot's merge of the new public head into the private sync branch conflicted. I overlaid the PR files onto private master. The only conflict was in the includes of src/Interpreters/InterpreterCreateQuery.cpp, and I kept both sides: Storages/extractKeyExpressionList.h from this PR and the Cloud includes from private master. The overlay's per-file numstat against private master equals this PR's diff. I pushed dd42de335de5 to sync-upstream/pr/110833, and the sync PR is now MERGEABLE.
  • The Bugfix validation failures (functional and integration) are all xfail: the new tests fail on the old binary, which is expected.
  • Merged master (c50de3b98b94) cleanly; new head 89b08b8c3334. The PR diff is unchanged (69 files). -fsyntax-only passes for every changed .cpp in the build's compile_commands.json (20 of 21; gtest_replicated_metadata_compare.cpp is not in this build's configuration).
  • There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-20.

@groeneai, investigate the Server liveness check failed failure in DBReplicated stateless runs (link above) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I looked at that run. The Server liveness check failed is the main server aborting on Logical error: 'Deadlock in Parquet::ReadManager (thread pool).' (#133046), not a hang:

  • The main server (port 9000) threw it at ReadManager.cpp:1622 in 05394_parquet_single_file_parallel_read (SELECT count(), sum(id) FROM file(...) WHERE s = '123' SETTINGS max_threads = 8) and aborted with signal 6 (clickhouse-server.err.log), about a minute before the liveness probe failed with Connection refused (localhost:9000). The SIGKILL of clickhouse-server1 is only the teardown: lldb stopped it to collect the stack traces, and it was killed 15 minutes later.
  • The query ran with input_format_parquet_memory_high_watermark = 1, randomized in tests/clickhouse-test since my Randomize the Parquet reader and writer settings in stateless tests #132712. The deadlock dump in clickhouse-server.log has the first incomplete row group with a task queued in the Dictionary stage, a later row group waiting in ColumnData, and nothing running. The reader bug itself is older (it is in 26.3); the randomization only reaches it.

The fix is already in progress: #133083 (Closes: #133046). It makes the first incomplete row group privileged again in the stages before ColumnData, which is exactly this dump. Its CI is red only because its new test 05836_parquet_deadlock_first_row_group_early_stage is too slow for the flaky checks (> 180s or the 600 s timeout in all four). Until it merges, the abort keeps hitting unrelated jobs: 27 since 2026-11-19 15:31 UTC, 4 of them on master.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-20.

  • CH Inc sync on 82ff4fd9da2e was build failed. Private src/Storages/StorageSharedMergeTree.cpp still called ReplicatedMergeTreeTableMetadata::checkAndFindDiff (2 calls) and checkEquals (1 call) with the old columns/virtuals/context arguments, which this PR removes. I updated them to the new signatures, the same way this PR updates StorageReplicatedMergeTree, in https://github.com/ClickHouse/clickhouse-private/pull/64914 (commit bc510f1afa1e, 3 lines in one file). No other private code calls the changed functions.
  • Performance Comparison (arm_release, master_head, 4/6): the only error is codecs_float_insert failing with Cannot reserve 8.48 MiB, not enough space (the runner's disk filled up), plus 3 "too long" notes on tests this PR does not touch. No query changed performance. The disk-space problem is fixed by Perf CI: remove the parts the hits rebuild replaces before the tests start #131429.
  • No unresolved review threads. The public branch did not need any changes, so I pushed nothing to it.

@stresshouse

stresshouse Bot commented Nov 20, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 28 queries analysed

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
  • StressHouse run: aeee7482-1fd5-40ad-9730-2aa9ef2f5770
  • MIRAI run: a25bdd56-09f6-4155-8d7e-b1026c5e3e94
  • PR check IDs:
    • clickbench_460470_1795174989
    • clickbench_460476_1795174990
    • tpch_adapted_1_official_460511_1795174990
    • tpch_adapted_1_official_460532_1795174990

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-20.

# Conflicts:
#	src/Storages/ProjectionsDescription.cpp
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-22.

  • The branch conflicted with master. I merged master (841a49bef228) in cc4ad2c25e91. The only conflict was in the includes of src/Storages/ProjectionsDescription.cpp: master dropped Interpreters/ExpressionAnalyzer.h (no longer used there), and this PR added Interpreters/FunctionNameNormalizer.h. I kept the new include and dropped the unused one. The PR diff against master is unchanged (same 69 files, same stat).
  • The merged tree builds (clickhouse target), and the 12 new .sql tests that do not need Keeper pass against it with clickhouse local. I did not run the six ReplicatedMergeTree tests or the two .sh tests locally; CI covers them.
  • The only red job on the previous head 82ff4fd9da2e was Performance Comparison (arm_release, master_head, 4/6), the runner disk-full problem already described above (Perf CI: remove the parts the hits rebuild replaces before the tests start #131429).
  • No unresolved review threads.

alexey-milovidov and others added 2 commits November 23, 2026 04:00
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass on 2026-11-23.

  • Fast test on cc4ad2c25e91 was red because of this PR: 05075_mutation_partition_pruning_table_in_set (a test added on master after this branch) failed with INCOMPATIBLE_COLUMNS although both sides printed the same text. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110833&sha=cc4ad2c25e9174fe0333b82563b2434f273229b3&name_0=PR&name_1=Fast%20test
    • Cause: StorageReplicatedMergeTree::checkTableStructureAttempt compared the in-memory columns with the columns parsed from ZooKeeper, and ColumnDefault::operator== now uses sameAST. AddDefaultDatabaseVisitor turns the table of ALIAS p IN some_table into an ASTTableIdentifier. It is written as p IN (db.some_table) and parsed back as a plain ASTIdentifier, so the two ASTs hash differently.
    • Fix in d78bdc602059: the local columns go through ColumnsDescription::parse(old_columns.toString(false)) first, so both sides are compared in their stored form.
  • Finish Workflow failed only because the Bugfix validation jobs were dropped after the Fast test failure.
  • Merged master (b04c4d810830) cleanly in 86dec3dc3969. The PR diff against master is the same 69 files.
  • Locally, on the merged tree with a server with embedded Keeper: 05075_mutation_partition_pruning_table_in_set and all 20 .sql/.sh tests added by this PR pass.
  • No unresolved review threads.

JSONObjectReader r(json);

union_mode = parseSelectUnionMode(r.getString("union_mode", "UNION_DEFAULT"));
is_normalized = r.getBool("is_normalized");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 23, 2026 06:22

AI review of a later commit does not approve the PR, see the AI Review comment.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants