Skip to content

Ignore redundant parentheses in stored table definitions - #114188

Merged
alexey-milovidov merged 9 commits into
masterfrom
normalize-parentheses-in-stored-metadata
Aug 13, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
normalize-parentheses-in-stored-metadata

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 10, 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 ATTACH PARTITION FROM, REPLACE PARTITION, MOVE PARTITION TO TABLE and adding a ReplicatedMergeTree replica failing with Tables have different ..., METADATA_MISMATCH or INCOMPATIBLE_COLUMNS for tables whose definitions were written with redundant parentheses, such as PARTITION BY (a), ORDER BY (b), INDEX ix (b * c) TYPE minmax, PROJECTION p (SELECT (b) ...), CONSTRAINT c CHECK (a > 0), TTL (d + INTERVAL 10 YEAR) or DEFAULT (a + 1).

Description

This is an alternative to #110833 that contains only the parentheses normalization, so that it is easy to backport. It does not touch getTreeHash and does not change how definitions are compared - they are still compared as text.

The definition expressions of a table (keys, TTL, indices, projections, constraints, column defaults) are stored in ZooKeeper as text and compared as text. #92340 made the AST remember whether the user wrote redundant parentheses around an expression, so the same definition now has two spellings, and every comparison of a stored definition started to reject one against the other:

CREATE TABLE dst (x UInt64, y UInt64) ENGINE = MergeTree PARTITION BY x ORDER BY y;
CREATE TABLE src (x UInt64, y UInt64) ENGINE = MergeTree PARTITION BY (x) ORDER BY y;
INSERT INTO src VALUES (1, 1);
ALTER TABLE dst ATTACH PARTITION 1 FROM src;
-- Code: 36. DB::Exception: Tables have different partition key. (BAD_ARGUMENTS)

An upgrade or a mixed-version cluster is not needed: both tables above are created by the same binary. Measured on released binaries, 25.8, 26.3 and 26.4 accept this and 26.5, 26.6 and 26.7 reject it, which matches the branches that contain b38a892dfbfab6.

The fix is a single formatting mode. IAST::FormatSettings::ignore_redundant_parentheses suppresses the parentheses of the parenthesized flag - the one place that emits them, decideParensEmission, is skipped - and IAST::formatIgnoringRedundantParentheses is the one-line formatter built on it. Because the formatter visits everything it prints, this covers nested parentheses (PARTITION BY (x + (1))) and every kind of definition, not just the top level of a key.

It is used where a stored definition is serialized or compared:

  • ReplicatedMergeTreeTableMetadata::formattedAST / formattedASTNormalized (the ZooKeeper /metadata payload and the replica-join comparison). This replaces the partial stripArtificialParens workaround added by Fix inconsistent formatting by remembering if an expression was parenthesized #92340, which only cleared the flag on an expression list and its immediate children, and it no longer has to clone the AST.
  • IndicesDescription::explicitToString / allToString, ProjectionsDescription::toString, ConstraintsDescription::toString and ColumnDescription::writeText - the serializers of the indices, projections, constraints and columns parts of the replicated metadata. ColumnsDescription::operator== compares two sets of columns through the same serializer.
  • MergeTreeData::checkStructureAndGetMergeTreeData - the ATTACH/REPLACE/MOVE PARTITION FROM structure gate (sorting/partition/primary keys, secondary indices, projections).
  • StorageReplicatedMergeTree::alter - the definitions an ALTER writes back into Keeper, so an ALTER never publishes a parenthesized definition either.
  • AlterCommand::isTTLAlter (whether restating a TTL schedules a MATERIALIZE TTL mutation) and the MODIFY ORDER BY no-op detection in AlterCommands::prepare.

The text these produce is exactly what every server produced before #92340, so a new replica and an old one agree in both directions. Nothing else changes: the parser and the formatter are untouched, the table metadata keeps what the user wrote, and SHOW CREATE still prints PARTITION BY (x + (1)). Definitions that differ in more than the parentheses are still rejected (a vs b, a different index expression, a different column default).

The columns payload of StorageKeeperMap and ObjectStorageQueue also contains these expressions, but both storages now compare it structurally, so a table created by any version keeps working. StorageKeeperMap already parses both sides and re-serializes them with the current serializer before comparing. ObjectStorageQueueTableMetadata compared the stored string verbatim; it now falls back to comparing the parsed ColumnsDescription when the strings differ, so a queue table created by 26.5-26.7 with redundant parentheses in a column DEFAULT, CODEC or TTL is accepted in both directions, and this also un-breaks such a table created by 25.8 and earlier (which is broken on 26.5-26.7 today).

Retrying the creation of a replica that failed between the ZooKeeper transaction and saving the local metadata is also covered: createReplicaAttempt recognizes an already-created empty replica by comparing its /metadata and /columns, and now falls back to a structural comparison (ReplicatedMergeTreeTableMetadata::checkEquals, parsed ColumnsDescription) when the raw strings differ, so such a retry works across the old and new spellings instead of failing with REPLICA_ALREADY_EXISTS.

Tests: 04836_parenthesized_definitions_attach_partition_from, 04837_parenthesized_definitions_replicated_metadata and 04850_parenthesized_definitions_replica_recovery. Each case in them fails on master with the error it is named after. The unit test ObjectStorageQueueTableMetadata.ColumnsComparisonIgnoresRedundantParentheses covers the stored-JSON compatibility of the queue metadata.

Version info

  • Merged into: 26.8.1.1335 (included in 26.8 and later)
  • Backported to: 26.7.4.31, 26.6.3.38, 26.5.7.50

The definition expressions of a table (keys, `TTL`, indices, projections,
constraints, column defaults) are stored in ZooKeeper as text and compared as
text. #92340 made the AST remember the redundant parentheses the user wrote, so
`PARTITION BY (a)` stopped comparing equal to `PARTITION BY a`, and
`ATTACH`/`REPLACE`/`MOVE PARTITION FROM` and adding a replica started to fail.

Format those definitions with a new `ignore_redundant_parentheses` mode, which
gives back the text every server produced before the parentheses were a part of
the AST. What the user wrote is still stored in the table metadata and still
shown by `SHOW CREATE`; only the comparisons and the Keeper payload became
insensitive to it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [680a97c]

Summary: ✅


AI Review

Summary

This PR makes stored table-definition comparisons ignore redundant user-written parentheses across MergeTree metadata serialization, partition attach checks, replicated metadata recovery, and ObjectStorageQueue compatibility paths. The replicated/MergeTree fixes look sound in the current head, but the new ObjectStorageQueue fallback is too permissive and now accepts immutable column-comment mismatches.

Findings

⚠️ Majors

  • [src/Storages/ObjectStorageQueue/ObjectStorageQueueTableMetadata.cpp:355] The new fallback compares parsed columns via ColumnsDescription::operator==, which is toString(false) and therefore ignores column comments. Because this metadata is stored with columns_.toString(true) in the constructor, a queue table whose Keeper metadata says COMMENT 'old' and whose local CREATE says COMMENT 'new' will now pass checkEquals instead of throwing METADATA_MISMATCH. Normalize the parsed columns and compare a representation that still includes comments, rather than routing through comment-blind equality.
Final Verdict

⚠️ Changes requested: fix the ObjectStorageQueue column comparison so it ignores only redundant parentheses, not immutable comment differences.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 157/167 (94.01%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 10, 2026
Comment thread src/Storages/ColumnsDescription.cpp Resolved
alexey-milovidov and others added 2 commits August 11, 2026 13:25
…ageQueue metadata

The `columns` field of the ObjectStorageQueue metadata in ZooKeeper was
compared with the local serialization verbatim, so a queue table created
by a version that kept the redundant parentheses of the user in a column
`DEFAULT`, `CODEC` or `TTL` expression (26.5-26.7) would fail with
`METADATA_MISMATCH` on a server that does not store them (and the other
way around). When the strings differ, compare the parsed
`ColumnsDescription` structurally, like `StorageKeeperMap` already does.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure, Stress test (arm_release) "Hung check failed, possible deadlock found", is a query stuck in InterpreterSelectQueryAnalyzer under the fuzzer workload - unrelated to this change (which only affects the formatting of stored table definitions). It matches the known pattern of uninterruptible CPU-bound query analysis, tracked in #112203. Merged master and pushed the review fix, so CI will re-run on the new commit.

@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 680a97ca4 with master 45cb8371b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.21 MiB 689.21 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

1797 translation units recompiled, 13082 s compile time in total, 1796 of them have a recent master baseline.

Job report

alexey-milovidov and others added 3 commits August 12, 2026 09:10
… when reusing a partially created replica

A retry of a partially created replica could find `/metadata` and `/columns` written
by a server version with a different (redundantly parenthesized) spelling of the same
table definition; the raw string comparison in `createReplicaAttempt` then failed with
`REPLICA_ALREADY_EXISTS`. Fall back to structural comparison
(`ReplicatedMergeTreeTableMetadata::checkEquals` / `ColumnsDescription::parse`)
when the texts differ.

Co-Authored-By: Claude Fable 5 <[email protected]>
…spellings

The test hand-crafts the ZooKeeper nodes of a replica as a 26.5..26.7 server
would have left them after failing between the ZooKeeper transaction and saving
the local metadata: the same definitions, spelled with redundant parentheses.
Retrying `CREATE TABLE` must reuse the empty replica instead of throwing
`REPLICA_ALREADY_EXISTS`.

Co-Authored-By: Claude Fable 5 <[email protected]>
{
if (zk_metadata_str == local_metadata)
return true;
try

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is weird. Let exceptions propagate, do not catch unless we have a really good reason.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Removed the try/catch in 97b10b4 — exceptions now propagate. The lambdas are only reached for an empty, never-active replica at our own path (the zk_host.empty() && ... chain short-circuits before them), so a structural mismatch now throws METADATA_MISMATCH from checkEquals and an unparseable node throws its parse error — both describe the problem better than the REPLICA_ALREADY_EXISTS the fall-through create attempt would produce. This also resolved the style-check finding about silent catch (...).

if (!query)
return "";
return query->formatWithSecretsOneLine();
return query->formatIgnoringRedundantParentheses();

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

For reviewers: this is the key change.

alexey-milovidov and others added 3 commits August 13, 2026 05:11
…adata propagate

Per review: do not swallow exceptions in `createReplicaAttempt` when comparing the
`metadata` and `columns` of an existing empty replica. A structural mismatch or an
unparseable node now throws (e.g. `METADATA_MISMATCH`), which describes the problem
better than the `REPLICA_ALREADY_EXISTS` of the fall-through create attempt. This
also resolves the style-check finding about silent `catch (...)`.

Co-Authored-By: Claude Fable 5 <[email protected]>
…04850 test

The style check requires shell tests to include it in `ReplicatedMergeTree` paths
to avoid overlaps between concurrent test runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 13, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Approved.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo labels Aug 13, 2026
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
…ypick/26.3/114188

Only the part of #114188 that applies to 26.3 is taken.

The `parenthesized` flag of `IAST` was introduced by #92340 in 26.5, so 26.3
never writes a table definition with the redundant parentheses the user has
written, and the bug the pull request fixes cannot happen here. Everything
built on `IAST::FormatSettings::ignore_redundant_parentheses` -
`IAST::formatIgnoringRedundantParentheses` and all of its call sites - would
be dead code on this branch, and the tests
`04836_parenthesized_definitions_attach_partition_from` and
`04837_parenthesized_definitions_replicated_metadata` assert that `SHOW CREATE`
prints the parentheses back, which is 26.5 and later behavior. Those are left out.

What is taken are the two places that have to accept a definition stored by
26.5..26.7, which 26.3 needs in order to read such a table at all:

- `ObjectStorageQueueTableMetadata::checkImmutableFieldsEquals` compares the
  `columns` payload structurally when the stored and the local text differ,
  covered by the unit test
  `ObjectStorageQueueTableMetadata.ColumnsComparisonIgnoresRedundantParentheses`.
- `StorageReplicatedMergeTree::createReplicaAttempt` recognizes an
  already-created empty replica by comparing its `/metadata` and `/columns`
  structurally, covered by
  `04850_parenthesized_definitions_replica_recovery`.

Both fail on 26.3 without this change.
alexey-milovidov added a commit that referenced this pull request Aug 13, 2026
…ypick/25.8/114188

Only the part of #114188 that applies to 25.8 is taken.

The `parenthesized` flag of `IAST` was introduced by #92340 in 26.5, so 25.8
never writes a table definition with the redundant parentheses the user has
written, and the bug the pull request fixes cannot happen here. Everything
built on `IAST::FormatSettings::ignore_redundant_parentheses` -
`IAST::formatIgnoringRedundantParentheses` and all of its call sites - would
be dead code on this branch, and the tests
`04836_parenthesized_definitions_attach_partition_from` and
`04837_parenthesized_definitions_replicated_metadata` assert that `SHOW CREATE`
prints the parentheses back, which is 26.5 and later behavior. Those are left out.

What is taken are the two places that have to accept a definition stored by
26.5..26.7, which 25.8 needs in order to read such a table at all:

- `ObjectStorageQueueTableMetadata::checkImmutableFieldsEquals` compares the
  `columns` payload structurally when the stored and the local text differ,
  covered by the unit test
  `ObjectStorageQueueTableMetadata.ColumnsComparisonIgnoresRedundantParentheses`.
- `StorageReplicatedMergeTree::createReplicaAttempt` recognizes an
  already-created empty replica by comparing its `/metadata` and `/columns`
  structurally, covered by
  `04850_parenthesized_definitions_replica_recovery`. This branch has no
  `ReplicatedMergeTreeTableMetadata::parseAndNormalize` (the implicit indices
  it normalizes appeared in 25.12), so `parse` is used, as everywhere else here.

Both fail on 25.8 without this change.
robot-ch-test-poll2 added a commit that referenced this pull request Aug 13, 2026
Cherry pick #114188 to 25.8: Ignore redundant parentheses in stored table definitions
robot-clickhouse added a commit that referenced this pull request Aug 13, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Aug 13, 2026
Cherry pick #114188 to 26.3: Ignore redundant parentheses in stored table definitions
robot-clickhouse added a commit that referenced this pull request Aug 13, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Aug 13, 2026
Cherry pick #114188 to 26.5: Ignore redundant parentheses in stored table definitions
robot-clickhouse added a commit that referenced this pull request Aug 13, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Aug 13, 2026
Cherry pick #114188 to 26.6: Ignore redundant parentheses in stored table definitions
robot-clickhouse added a commit that referenced this pull request Aug 13, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Aug 13, 2026
Cherry pick #114188 to 26.7: Ignore redundant parentheses in stored table definitions
robot-clickhouse added a commit that referenced this pull request Aug 13, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 13, 2026
Backport #114188 to 26.7: Ignore redundant parentheses in stored table definitions
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 14, 2026
…on-tuple-key-normalization

Master got the minimal text-level fix for the same bug in ClickHouse#114188
(`formatIgnoringRedundantParentheses`). Conflicts resolved in favour of this
branch, whose AST comparison subsumes the text comparison, with two changes:

* `ReplicatedMergeTreeTableMetadata::formatDefinition` and `formatDefinitionList`
  now produce the Keeper payload with `formatIgnoringRedundantParentheses`
  instead of walking the tree with `stripArtificialParens` - the new format-time
  mode does the same, more thoroughly, and without cloning to mutate.
* `stripArtificialParens` stays only where the AST itself, not its text, has to
  be canonical: `Diff::getNewMetadata`, which stores the reparsed key expression
  in the local metadata.
PedroTadim added a commit that referenced this pull request Aug 14, 2026
Backport #114188 to 26.5: Ignore redundant parentheses in stored table definitions
PedroTadim added a commit that referenced this pull request Aug 14, 2026
Backport #114188 to 26.6: Ignore redundant parentheses in stored table definitions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

2 participants