Repository navigation
Conversation
…CATED ATTACH TABLE ... AS REPLICATED rewrote the on-disk metadata to the Replicated engine before StorageFactory validated engine-feature support. A MergeTree table with a UNIQUE KEY clause was rejected only later, when the storage was instantiated (ReplicatedMergeTree does not support UNIQUE KEY), so the query returned an error but the metadata file was already rewritten to an invalid ReplicatedMergeTree + UNIQUE KEY combination with no rollback. After a restart the table failed to load (ASYNC_LOAD_WAIT_FAILED). Validate that the target engine supports the UNIQUE KEY clause in convertMergeTreeTableIfPossible before any side effect (clearing transaction metadata or writing the new metadata file), so a rejected conversion leaves the stored metadata intact and the table remains loadable. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260717-130800 |
|
cc @tuanpach @tavplubix — could you review? This validates engine-feature support (UNIQUE KEY) before |
|
Workflow [PR], commit [8a086bf] Summary: ❌
AI ReviewSummaryThis PR broadens the Findings❌ Blockers
Final Verdict❌ Changes requested. |
Factor the engine-feature validation added for ATTACH ... AS REPLICATED into a shared DatabaseOrdinary::validateEngineSupportsReplicatedConversion, used by both the ATTACH entrypoint and the restart-time converter (convertMergeTreeToReplicatedIfNeeded). This covers two gaps: - The restart-time convert_to_replicated flag path rewrote metadata via setMergeTreeEngine without the supports_unique_key check, so a MergeTree table with a UNIQUE KEY plus the flag was persisted as an unloadable ReplicatedMergeTree + UNIQUE KEY definition on startup. - setMergeTreeEngine only toggles the leading "Replicated" prefix, so a SharedMergeTree was rewritten to a non-existent ReplicatedSharedMergeTree before StorageFactory rejects it. Reject Shared* up front, mirroring the guard the converter already has. See issue ClickHouse#110854. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressed both review findings in 260c771 by factoring a single shared validator ( Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260717-141200 |
The ATTACH TABLE ... AS REPLICATED entrypoint
(InterpreterCreateQuery::convertMergeTreeTableIfPossible) rewrote the on-disk
metadata to Replicated* and only then failed from the StorageReplicatedMergeTree
constructor ("There already is an active replica with this replica path") when
the target default replica path already existed in Keeper. That left unloadable
Replicated* metadata persisted on disk, contradicting the guarantee that a
rejected attach leaves stored metadata intact.
Call the existing DatabaseOrdinary::checkReplicaPathExists preflight (already
used by the restart-time converter convertMergeTreeToReplicatedIfNeeded) from
the entrypoint before any side effect, guarded by to_replicated. A pre-existing
replica path is now rejected with UNEXPECTED_NODE_IN_ZOOKEEPER before the
metadata is touched.
checkReplicaPathExists is promoted from a file-static function to a public
static member of DatabaseOrdinary so both paths share it.
03167_attach_as_replicated_errors no longer needs the AS NOT REPLICATED recovery
after the failed attach; it asserts the stored definition stays MergeTree.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Finding C fix (commit Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-maint-slot-9:20260717-195700 |
… aborted server The teardown removed the convert_to_replicated flag via get_table_path, which queries system.tables. But the illegal conversion deliberately leaves the server refusing to start, so that query hit a dead server (Code 210, Connection refused) and the test errored in teardown across all integration configs. Follow the sibling test_modify_engine_fails_if_zk_path_exists pattern: capture the data path while the server is still up, use stop_clickhouse + start_clickhouse( expected_to_fail=True) for the deterministic failed startup, then rm the flag with the captured path. No server query while it is down. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI fix (commit 21a0a98): the new Now follows the sibling Verified locally on a debug build (Build ID 5f988ba2cde1): fails pre-fix (Code 210 in teardown), passes post-fix. Test-only change, no C++ diff. |
Avoid shell word-splitting/glob of the interpolated data path in the convert_to_replicated cleanup: use exec_in_container(["rm", ...]) instead of bash -c with an interpolated path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Addressing clickhouse-gh[bot] Finding D (argv/shlex.quote for the flag-file cleanup). This is our own just-introduced test helper; the fix is a one-line, objective, test-only change, so I applied it rather than declining. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-maint-slot-10:20260717-234900 |
…failure ReplicatedMergeTree rejects table_readonly = 1 in its constructor, but the ATTACH AS [NOT] REPLICATED preflight did not check it, so the metadata was rewritten to Replicated* before the constructor threw, leaving an unloadable definition on disk. Add the table_readonly check to the shared validator so both the ATTACH entrypoint and the restart-time converter reject it before any side effect. Also add a metadata-revert backstop to the entrypoint: snapshot the original definition before the rewrite and restore it if the converted table then fails to construct, so a rejection not covered by the up-front validation still leaves the stored metadata intact.
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-premium-slot-24:20260718-024748 |
CI finish ledger — 5efc121CI fully finished on this head (Config Workflow, Finish Workflow both SUCCESS). No failing checks; every test job green, including the new regression test
No PR-caused failures. Every line owned/exempt. Session id: cron:our-pr-ci-monitor:20260718-093000 |
Extend the shared validateEngineSupportsReplicatedConversion to reject
the settings/disks StorageReplicatedMergeTree refuses in its constructor,
resolved against the effective target settings and storage policy (server
config folded with the query SETTINGS), not just the explicit AST:
table_readonly = 1 coming from the merge_tree / replicated_merge_tree
config, and Keeper-backed ('s3_with_keeper') disks. Both the ATTACH AS
REPLICATED entrypoint and the restart-time converter use the shared
validator, so a config-sourced value no longer slips past the preflight
and leaves unloadable Replicated* metadata after the rewrite.
The checks are kept exactly as narrow as the constructor to avoid
rejecting conversions the engine would accept.
Related: ClickHouse#110854
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-premium-slot-25:20260720-054200 |
Internal second-model review — adjudication log (click to expand)Pre-publication scoped-delta review by an independent model (engine: codex; 2 findings;
Severity: ❌ blocker / Session id: cron:clickhouse-premium-slot-25:20260720-054200 |
| @@ -2932,20 +2957,47 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr | |||
| clearTransactionMetadata(table_data_path, getContext()); | |||
There was a problem hiding this comment.
metadata_revert_guard only restores the table .sql file, but by this point clearTransactionMetadata has already deleted each part's txn_version.txt / txn_version.txt.tmp. If anything still throws after line 2957, the rejected ATTACH ... AS REPLICATED has already mutated the persisted MergeTree table: a plain re-attach will reload those parts as NoMetadata / non-transactional (MergeTreeData.cpp:2056-2094), so rolled-back or removed parts can reappear. This is not just hypothetical: there are still constructor-time rejections after the clear, for example an invalid default_replica_name is rejected later in registerStorageMergeTree.cpp:573-577.
If this guard is meant to backstop post-rewrite failures, it also has to snapshot and restore the per-part transaction metadata (and cover failures from clearTransactionMetadata itself), or the clear needs to move behind the remaining constructor-level validations.
There was a problem hiding this comment.
Confirmed, the ordering is real: clearTransactionMetadata (line 2957) removes each part's txn_version.txt / .tmp before the metadata_revert_guard (line 2970) is armed, and that guard snapshots and restores only the .sql definition, not the per-part transaction metadata. A constructor-time rejection after the clear (for example the replica-name validation at registerStorageMergeTree.cpp:573-577, reached from doCreateTable) restores the MergeTree .sql but leaves the txn metadata gone, so the finding holds.
This is the same rollback-completeness question as Findings E and F (how exhaustively a rejected ATTACH AS REPLICATED should undo its side effects). Both were deferred to the assignee and resolved there as a deliberate scope decision, and the guard's own comment (2960-2964) already notes it is a best-effort .sql backstop that cannot enumerate every constructor rejection. The two remediations here (snapshot and restore the per-part txn metadata, including failures from clearTransactionMetadata itself, or move the clear behind the remaining constructor validations) are that same architectural call, so I am leaving the scope of the guard to the assignee rather than expanding it in this PR.
There was a problem hiding this comment.
I think we can just rely on the check. Can remove the logic of reverting the file.
There was a problem hiding this comment.
Removing the revert is safe for everything the up-front check covers: validateEngineSupportsReplicatedConversion and checkReplicaPathExists both run before clearTransactionMetadata and the metadata rewrite, so Shared*, UNIQUE KEY, resolved table_readonly, a Keeper-backed policy, and an existing replica path are all rejected with no on-disk change.
Two constructor-time rejections still fire after the rewrite, so for those a rejected ATTACH ... AS REPLICATED would again leave the rewritten metadata on disk (the #110854 failure mode):
- empty or
\t/\ndefault_replica_name(registerStorageMergeTree.cpp:574,577), reached viadoCreateTableafter the rewrite; - an inline
disk = disk(...)Keeper disk (the validator deliberately does not resolve it, to avoid materializing the disk).
The first is cheap to mirror up-front next to checkReplicaPathExists (resolve default_replica_name, reject empty/\t/\n, no side effect); the second can only be caught in the constructor. So: remove the revert and also add that one up-front check, or remove the revert as-is and leave those two narrow paths (broken replica-name config, inline Keeper disk) to fail without rollback? I will implement whichever you prefer.
There was a problem hiding this comment.
Please implement the first option.
There was a problem hiding this comment.
Done in 2c0cda0 (option 1): removed the metadata_revert_guard and added an up-front default_replica_name check in the shared validateEngineSupportsReplicatedConversion (resolves the setting exactly as TableZnodeInfo::resolve does, with the UUID cleared, so empty / \t / \n / unresolvable {uuid} names are rejected before any on-disk change, on both the ATTACH entrypoint and the restart converter). Added a regression test for the empty-name case.
Verified: valid name and {replica} still convert; empty, {uuid}, UNIQUE KEY, resolved table_readonly, and Keeper-policy are rejected with the metadata left as MergeTree.
One thing I want to flag before you rely fully on the check: a couple of rejections still fire in the constructor path (doCreateTable), after the metadata is rewritten, and cannot be mirrored up front because they depend on transient runtime state, not on the DDL:
max_replicated_table_num_to_throw(throwIfTooManyEntities, checked once the engine is alreadyReplicated*);- an inline
disk = disk(...)Keeper disk (the validator does not resolve inline disks, to avoid materializing the disk as a side effect).
If one of those throws, the rejected conversion now leaves the persisted metadata as ReplicatedMergeTree (the exact case the revert guard used to cover, though it only ever restored the .sql, not the per-part txn metadata). Both are narrow. Happy to leave it as is, or to also reject the replicated-table-count limit up front if you would rather close that gap too. Your call.
The ch2 instance sets merge_tree.table_readonly=1 globally, so the plain MergeTree table is read-only from creation and INSERT is rejected with TABLE_IS_PERMANENTLY_READ_ONLY (Code 774). That is exactly the resolved setting this test exercises, so it can hold no data. Drop the impossible INSERT and assert an empty-but-loadable table; data survival is covered by test_convert_to_replicated_rejected_for_unique_key.
|
CI fix (commit 565965f): the new integration test Root cause: the Fix: drop the impossible INSERT and assert an empty-but-loadable table (reads do not hit Verified: fails on the prior commit (CI, Code 774); passes locally after the fix (both tests x3, 6 passed). |
CI finish ledger — 565965f18dfd4caa2df78652be7324a2086d8e4efCI fully finished (Finish Workflow SUCCESS, 20-min ingest buffer met). Every failure below has an owner.
The prior own-test PR-caused failure ( Session id: cron:our-pr-ci-monitor:20260720-150000 |
…S REPLICATED The up-front validation in convertMergeTreeTableIfPossible already rejects every conversion the target engine refuses (Shared*, UNIQUE KEY, resolved table_readonly, Keeper-backed disk) before any on-disk side effect, so the post-rewrite metadata_revert_guard is no longer needed. Remove it and rely on the check. The one remaining constructor-time rejection that could still fire after the metadata rewrite was an empty or whitespace default_replica_name (NO_REPLICA_NAME_GIVEN). Mirror that rejection in the shared validator (resolving the server setting the same way the storage does), so a broken replica-name config is rejected up front with no on-disk change, on both the ATTACH entrypoint and the restart-time converter.
…replicated-unique-key-validate-110854 # Conflicts: # src/Databases/DatabaseOrdinary.cpp
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-premium-slot-24:20260722-070700 |
Internal second-model review - adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 findings;
Severity: ❌ blocker / Session id: cron:clickhouse-premium-slot-24:20260722-070700 |
|
|
||
| /// Save new metadata | ||
| /// Save new metadata. The validation above rejects every conversion the target engine refuses | ||
| /// before this rewrite, so a rejected ATTACH AS [NOT] REPLICATED never reaches this point and |
There was a problem hiding this comment.
metadata_revert_guard is gone, but doCreateTable still has late failures after this rewrite. The fresh gap on the AS NOT REPLICATED side is throwIfTooManyEntities: once line 3157 has switched the detached table to plain MergeTree, the later check at src/Interpreters/InterpreterCreateQuery.cpp:2225-2360 starts using max_table_num_to_throw instead of the replicated-table limit. If that limit is already reached, ATTACH TABLE ... AS NOT REPLICATED throws TOO_MANY_TABLES only after the .sql file was de-replicated, so a later plain ATTACH TABLE t silently loads the table as non-replicated even though the original request failed.
Please either preflight the target-side table-count limit before touching metadata, or restore rollback for post-rewrite failures.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 64/73 (87.67%) · Uncovered code |
CI finish ledger — 8a086bfCI fully finished on this head (Finish Workflow / Mergeable Check SUCCESS). 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. Only
Session id: cron:our-pr-ci-monitor:20260722-143000 |
| /// SharedMergeTree turned into a non-existent ReplicatedSharedMergeTree) would leave the | ||
| /// persisted metadata pointing at an unloadable engine, making the table fail to load after | ||
| /// restart (ASYNC_LOAD_WAIT_FAILED). Shared with the restart-time converter. See issue #110854. | ||
| DatabaseOrdinary::validateEngineSupportsReplicatedConversion(create, getContext(), to_replicated); |
There was a problem hiding this comment.
@groeneai it's terrible, are you reinventing these validations again? Is there a better way to eliminate the redundancy?
There was a problem hiding this comment.
Yes, it duplicates the ReplicatedMergeTree constructor's own rejections. The reason it exists: on the short-syntax ATTACH TABLE ... AS REPLICATED path, convertMergeTreeTableIfPossible rewrites the on-disk .sql to Replicated* before the storage is constructed, so the constructor's checks (table_readonly at StorageReplicatedMergeTree.cpp:460, keeper-disk at :467, replica name at registerStorageMergeTree.cpp:573-577, UNIQUE KEY via StorageFactory features) fire too late, after the irreversible metadata write. That is the #110854 corruption: a rejected attach leaves the table pointing at an unloadable engine. The preflight re-checks those conditions before the write so the rewrite only ever happens for a conversion that will construct.
The duplication is fragile though, which is exactly why the review kept surfacing one more un-mirrored throw path. Two ways to remove it, your call on scope:
- Extract each constructor precondition rejection into a shared static validator that both the ctor and this preflight call. Single source of truth, no drift.
- The proper fix: make the on-disk rewrite the commit step after a successful construct, so the constructor is the only validator and the preflight disappears entirely. Bigger, because construct-at-ATTACH has its own ZK side effects (
createReplica/createNewZooKeeperNodes) that the reorder would have to gate.
For context, tuanpach already chose to rely on this up-front check rather than a post-write rollback (option 1, revert guard removed), so the preflight is the agreed mechanism. Do you want me to do (1) here to kill the redundancy, or open (2) separately?
|
Dear @tuanpach, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Dear @murphy-4o, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Probably we don't need this as all #110854 (comment) |
|
Measured on master Before a restart, yes: After a restart, no. Every DDL on the table then waits on the failed load job and returns
The only recovery I found is editing So the escape hatch works only inside the session where the failed Whether that is worth a pre-write check is your call. I have not reopened #110863. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
ATTACH TABLE ... AS REPLICATEDleaving a table unloadable after restart when the source table used an unsupported clause for the target engine (e.g. aMergeTreetable with aUNIQUE KEYclause, whichReplicatedMergeTreedoes not support). The conversion is now validated before the on-disk metadata is rewritten, so a rejectedATTACH ... AS REPLICATEDkeeps the stored metadata intact.Description
Closes: #110854
ATTACH TABLE ... AS REPLICATEDrewrote the on-disk metadata to the Replicated engine (convertMergeTreeTableIfPossibleinInterpreterCreateQuery.cpp) before the engine-feature validation ran. Feature support is only checked later inStorageFactory::getwhen the storage is instantiated, whereReplicatedMergeTreerejects theUNIQUE KEYclause. So the query returnedCode 36 BAD_ARGUMENTS, but the metadata file had already been replaced with an invalidReplicatedMergeTree(...) ... UNIQUE KEY (...)combination and there was no rollback. On the next server start the load job for the table failed withCode 36, surfaced to clients asCode 722 ASYNC_LOAD_WAIT_FAILED.Repro (from the issue):
The fix validates that the target engine supports the
UNIQUE KEYclause inconvertMergeTreeTableIfPossiblebefore any side effect (before clearing transaction metadata and before writing the new metadata file).UNIQUE KEYis the only DDL clause whose support differs between theMergeTreefamily andReplicatedMergeTree, so this fully covers the conversion. The rejected conversion now keeps the cleanCode 36error, leaves the stored metadata untouched, and the table remains loadable after restart.Added stateless regression test
04545_attach_as_replicated_unique_key.