Skip to content

Fix Inconsistent AST formatting for ALTER TABLE ... MOVE PART ... TO SHARD - #109060

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-alter-move-part-to-shard-ast-format
Aug 11, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:fix-alter-move-part-to-shard-ast-format

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 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 a spurious Inconsistent AST formatting error for ALTER TABLE ... MOVE PART ... TO SHARD '<path>'. The query formatter dropped the SHARD keyword, so the reformatted query could not be parsed back, raising a LOGICAL_ERROR (a handled exception in release builds, an abort in debug and sanitizer builds).

Description

The ASTAlterCommand formatter switched over the move destination type and
emitted the keyword for DISK, VOLUME and TABLE, but had no case for
SHARD. So this query:

ALTER TABLE x MOVE PART 'p' TO SHARD '/path'

was formatted back as ALTER TABLE x (MOVE PART 'p' TO '/path') with the
SHARD keyword dropped. The parser accepts TO SHARD '<path>' (only for
MOVE PART, not MOVE PARTITION), so the reformatted query no longer parses,
and the AST formatting round-trip consistency check in executeQuery
(format(parse(q)) == q) raised LOGICAL_ERROR: Inconsistent AST formatting.
That is a handled exception in release builds, but aborts the server in debug
and sanitizer builds.

The fix adds the missing SHARD case to ASTAlterCommand::formatImpl so the
destination path is emitted with its keyword. The two sibling switches that
consume move_destination_type (execution in InterpreterAlterQuery and the
conversion in PartitionCommands) already handle SHARD correctly; only the
formatter was missing it.

Added a stateless regression test (04342_inconsistent_ast_move_part_to_shard)
that asserts the formatted output keeps SHARD, is stable under a second
round-trip, and that the other move destinations (DISK, VOLUME, TABLE)
still format correctly. It also asserts MOVE PARTITION ... TO SHARD remains a
syntax error, since SHARD is valid only for MOVE PART.

Version info

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

…SHARD

ASTAlterCommand::formatImpl handled the DISK, VOLUME and TABLE move
destinations but not SHARD, so "ALTER TABLE x MOVE PART 'p' TO SHARD
'/path'" was formatted back as "MOVE PART 'p' TO '/path'" (the SHARD
keyword dropped). The formatted query then fails to parse, which trips
the AST formatting round-trip consistency check in executeQuery and
raises a LOGICAL_ERROR (a handled exception in release, aborts the
server in debug and sanitizer builds).

Add the missing SHARD case to the formatter so format(parse(q)) == q.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug build: clickhouse local -q "ALTER TABLE x MOVE PART 'p' TO SHARD '/path'" aborts with SIGABRT (exit 134) every time; SELECT formatQuery('ALTER TABLE x MOVE PART ''p'' TO SHARD ''/path''') deterministically prints MOVE PART 'p' TO '/path' (SHARD dropped).
b Root cause explained? Yes. ASTAlterCommand::formatImpl (src/Parsers/ASTAlterQuery.cpp) switches on move_destination_type and emits a keyword for DISK/VOLUME/TABLE but has no SHARD case, so SHARD falls to default: break; and only the quoted path is written. The parser accepts TO SHARD '<path>', so the reformatted query fails to parse, and the format(parse(q)) == q round-trip check in executeQuery raises LOGICAL_ERROR: Inconsistent AST formatting (handled in release, aborts in debug/sanitizer).
c Fix matches root cause? Yes. Adds the missing case DataDestinationType::SHARD: ostr << "SHARD "; break; to the formatter switch, directly emitting the dropped keyword. Not a band-aid.
d Test intent preserved / new tests added? New stateless test 04342_inconsistent_ast_move_part_to_shard asserts the formatted output keeps SHARD, is stable across a second round-trip, that DISK/VOLUME/TABLE still format, and that MOVE PARTITION ... TO SHARD remains a SYNTAX_ERROR (SHARD is PART-only).
e Both directions demonstrated? Yes. Without the fix (Build ID bc2a1a02): formatQuery drops SHARD (differs from reference) and the ALTER aborts (134); the test would FAIL. With the fix (Build ID b7084ee8): formatQuery keeps SHARD, the ALTER returns UNKNOWN_TABLE (past the check), and clickhouse-test passes 3/3.
f Fix is general across code paths? Yes. The other two switches over move_destination_type (execution in InterpreterAlterQuery.cpp, conversion in PartitionCommands.cpp) already handle SHARD; only the formatter was missing it. TTL move formatting (ASTTTLElement.cpp) has no SHARD destination, so it is unaffected.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Verified with a plain path, a special path, and a backticked db.\table`name; the DISK/VOLUME/TABLE destinations are regression-checked;MOVE PARTITION ... TO SHARDcorrectly stays a syntax error.SHARD` carries only a string-literal path (no type wrappers apply).
h Backward compatible? Yes. Formatter-only change; no setting default, on-disk/wire/metadata format, or validation change. Old and new versions parse and execute identically. N/A for SettingsChangesHistory.cpp.
i Invariants and contracts preserved? Yes. Upholds the formatter invariant format(parse(q)) == q for this command (the very invariant it was breaking). No change to AST structure, parsing, or execution paths.

Session id: cron:clickhouse-worker-slot-0:20260701-124000

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @evillique @george-larionov could you review? Small parser/formatter fix: ASTAlterCommand::formatImpl was missing the SHARD case for MOVE PART ... TO SHARD, so the query formatted back without the SHARD keyword and tripped the AST round-trip consistency check (LOGICAL_ERROR, aborts in debug/sanitizer). Adds the missing case plus a stateless round-trip regression test.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3520a9b]

Summary: ✅


AI Review

Summary

This PR correctly plugs the missing SHARD keyword in ASTAlterCommand::formatImpl, so the plain SQL ALTER TABLE ... MOVE PART ... TO SHARD round-trip no longer trips Inconsistent AST formatting. I found one remaining contract gap before merge: the same SHARD-is-MOVE PART-only invariant is still not enforced for clickhouse_json, so malformed AST JSON can still build a parser-impossible MOVE PARTITION ... TO SHARD command.

Findings

⚠️ Majors

  • [src/Parsers/ASTAlterQuery.cpp:867] The formatter now prints SHARD correctly, but ASTAlterCommand::readJSON still accepts move_destination_type = SHARD when part is false. That lets formatQueryFromJSON and the clickhouse_json dialect construct ALTER TABLE ... MOVE PARTITION ... TO SHARD, even though ParserAlterQuery rejects the SQL form and execution only fails later with NOT_IMPLEMENTED. Reject SHARD unless part is true in the MOVE_PARTITION JSON validation branch, and add a focused regression in 04350_ast_json_parser_impossible_field_combinations.
Final Verdict

Needs one follow-up before merge: close the clickhouse_json hole so SHARD is rejected consistently for MOVE PARTITION across both SQL text and AST JSON inputs.

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 9/9 (100.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 1, 2026
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d23bbfb

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt. This PR's diff is a 3-line AST formatter fix in src/Parsers/ASTAlterQuery.cpp plus a stateless round-trip test; none of the failures below are in a path this PR touches.

Check / test Reason Owner / fixing PR
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 03227_distinct_dynamic_types_json_paths flaky (CI --diagnose-random-settings: all reruns passed, not reproducible; return code 102 connection-desync) #108854 (external, merged)
Stress test (arm_asan_ubsan) / Hung check failed, possible deadlock found deadlock (chronic family) #108212 (ours, merged) / #105905 (ours, open)
Mergeable Check / PR rollup of the reds above owned via the PRs listed
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260701-183000

@evillique evillique self-assigned this Jul 15, 2026
@evillique

Copy link
Copy Markdown
Member

@groeneai Could you merge the fresh master into this branch?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged fresh master into the branch (now at 83a0a65). Diff unchanged: 3 files, +29/-0. CI is re-running.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 83a0a65

Every failure below has an owner (a fixing PR). No PR-caused failures.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / 02122_join_group_by_timeout flaky (10 unrelated PRs / 30d, 0 on master) #109584 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260716-000000

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 9/9 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ff10dc5

Every failure below has an owner: a fixing PR, or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky on this lane: secondary replicas are built without setQueryId, so the per-table max_concurrent_queries throttle sees several random query ids for one statement and the query competes against itself #112385 (ours, open)
Stateless tests (amd_msan, WasmEdge, parallel, 2/2) / 02805_distributed_queries_timeouts flaky: return code 209 with RemoteSource: Error occurs on cancellation.: Code: 210 ... Connection to localhost:9000 terminated; CI's own diagnosis reports 3/3 reruns pass #112229 (ours, open)

Session id: cron:our-pr-ci-monitor:20260729-083000

@evillique

Copy link
Copy Markdown
Member

@groeneai check test failure and merge the fresh master in

@groeneai

Copy link
Copy Markdown
Collaborator Author

@evillique Merged fresh master in: head is now 3520a9b6ddd1495f4d70a3922b2e3a1e3183403f and CI is running on it.

There was no test failure to check. On the previous head no test ran at all: Config Workflow failed because the praktika config step could not reach play.clickhouse.com, so all 172 downstream jobs were dropped and only the two aggregator checks (Config Workflow, Finish Workflow) show red. Zero test-level failures. The fresh run on the merge commit should give a real signal.

The diff is unchanged by the merge: still the same 3 files (src/Parsers/ASTAlterQuery.cpp plus the 04342 test), +29/-0, no submodule movement.

case DataDestinationType::VOLUME:
ostr << "VOLUME ";
break;
case DataDestinationType::SHARD:

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.

This fixes the SQL formatter branch, but the same invariant is still open on the clickhouse_json carrier. ParserAlterQuery only produces TO SHARD for MOVE PART, yet ASTAlterCommand::readJSON still accepts type = MOVE_PARTITION, part = false, move_destination_type = SHARD in its MOVE_PARTITION validation block. With the new formatter arm here, formatQueryFromJSON now emits ALTER TABLE t (MOVE PARTITION 1 TO SHARD '/path') for that malformed JSON instead of rejecting it, and the JSON dialect can drive it to execution where movePartitionToShard throws NOT_IMPLEMENTED instead of the parser's SYNTAX_ERROR.

Please fail closed in ASTAlterCommand::readJSON when move_destination_type == DataDestinationType::SHARD && !part, and add a regression in the parser-impossible JSON suite (the 04350_ast_json_parser_impossible_field_combinations test looks like the right place).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both mechanical claims check out; the causal one does not, so I am not changing this PR.

Confirmed on master: ParserAlterQuery.cpp:526 accepts TO SHARD only in the MOVE PART branch (which sets part = true), and the MOVE_PARTITION switch in readJSON accepts SHARD without testing part.

Measured on pre-fix master (debug build), the formatter arm is not what opens this:

  • readJSON already accepts that payload today, and formatQueryFromJSON already succeeds on it, emitting ALTER TABLE x (MOVE PARTITION 1 TO 'v1') - the default: break drops the keyword rather than rejecting. The new arm changes which non-parseable text is emitted, not whether the payload is accepted.
  • Neither text parses back: MOVE PARTITION 1 TO 'v1' and MOVE PARTITION 1 TO SHARD '/path' both give SYNTAX_ERROR at the same position.
  • Execution already fails closed before this PR, and does not consult formatImpl: the payload reaches MergeTreeData::executePartitionCommand and throws NOT_IMPLEMENTED ("MOVE PARTITION TO SHARD is not supported by storage MergeTree"), and StorageReplicatedMergeTree::movePartitionToShard starts with if (!move_part) throw NOT_IMPLEMENTED.
  • The debug AST round-trip check lives in the SQL branch of executeQuery, after parseQuery; a JSON payload never reaches it, so there is no new abort path.

So this is a pre-existing gap in a sibling carrier, orthogonal to a 3-line formatter fix, and already refused at the storage layer with a different error code. Not raising it separately either: the payload is rejected either way, so there is no wrong-result, data-loss, crash or access-control consequence behind it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3520a9b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

This PR's diff is a 3-line AST formatter fix in src/Parsers/ASTAlterQuery.cpp plus one
stateless round-trip test, so it cannot reach the path below. Nothing here is PR-caused.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Hung check failed, possible deadlock found deadlock: a cancelled DROP TABLE prometheus sits 1008s in waitTableFinallyDropped with is_cancelled = 1, and DROP DATABASE ... SYNC / DETACH DATABASE convoy behind it on the DDL guard a fix task is moved to pending (investigating at full effort - fixing PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

Frame-level identity of the hung wait on this run, from hung_check.log:
StorageTimeSeries::dropInnerTableIfAny -> InterpreterDropQuery::executeDropQuery ->
waitForTableToBeActuallyDroppedOrDetached -> DatabaseCatalog::waitTableFinallyDropped,
with 04811_promql_topk_bottomk_limitk as the only prometheus/TimeSeries test in the log.

I checked the four merged PRs that touch this wait (#97586, #113263, #113504, #107604): all
four are ancestors of this head, and the hang still fires, so none of them owns this line.
The gap is that executeDropQuery builds the inner-table drop context from
Context::createCopy(global_context) and a global context can never carry a process-list
element, so the throw_if_cancelled callback is null and the 1s condvar loop has no exit
but completion or shutdown.

Build (arm_release) / Post Hooks is bookkeeping noise on a check whose own conclusion is
success, so it is not a failure line.

Session id: cron:our-pr-ci-monitor:20260811-000000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the hung DROP TABLE of a TimeSeries table (waitTableFinallyDropped): #114302 (external, open).

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 11, 2026
Merged via the queue into ClickHouse:master with commit 510b23a Aug 11, 2026
355 of 356 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov @evillique — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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

6 participants