Skip to content

Validate engine features before rewriting metadata on ATTACH AS REPLICATED - #110863

Closed
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/attach-as-replicated-unique-key-validate-110854
Closed

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/attach-as-replicated-unique-key-validate-110854

Conversation

@groeneai

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):

Fix ATTACH TABLE ... AS REPLICATED leaving a table unloadable after restart when the source table used an unsupported clause for the target engine (e.g. a MergeTree table with a UNIQUE KEY clause, which ReplicatedMergeTree does not support). The conversion is now validated before the on-disk metadata is rewritten, so a rejected ATTACH ... AS REPLICATED keeps the stored metadata intact.

Description

Closes: #110854

ATTACH TABLE ... AS REPLICATED rewrote the on-disk metadata to the Replicated engine (convertMergeTreeTableIfPossible in InterpreterCreateQuery.cpp) before the engine-feature validation ran. Feature support is only checked later in StorageFactory::get when the storage is instantiated, where ReplicatedMergeTree rejects the UNIQUE KEY clause. So the query returned Code 36 BAD_ARGUMENTS, but the metadata file had already been replaced with an invalid ReplicatedMergeTree(...) ... UNIQUE KEY (...) combination and there was no rollback. On the next server start the load job for the table failed with Code 36, surfaced to clients as Code 722 ASYNC_LOAD_WAIT_FAILED.

Repro (from the issue):

SET allow_experimental_unique_key = 1;
CREATE TABLE t0 (c0 Int) ENGINE = MergeTree() ORDER BY tuple() UNIQUE KEY (c0);
DETACH TABLE t0;
ATTACH TABLE t0 AS REPLICATED;  -- returns Code 36, but rewrites the metadata anyway
-- after restart:
SELECT * FROM t0;  -- Code 722 ASYNC_LOAD_WAIT_FAILED

The fix validates that the target engine supports the UNIQUE KEY clause in convertMergeTreeTableIfPossible before any side effect (before clearing transaction metadata and before writing the new metadata file). UNIQUE KEY is the only DDL clause whose support differs between the MergeTree family and ReplicatedMergeTree, so this fully covers the conversion. The rejected conversion now keeps the clean Code 36 error, leaves the stored metadata untouched, and the table remains loadable after restart.

Added stateless regression test 04545_attach_as_replicated_unique_key.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SET allow_experimental_unique_key=1; CREATE TABLE t0 (c0 Int) ENGINE=MergeTree() ORDER BY tuple() UNIQUE KEY (c0); DETACH TABLE t0; ATTACH TABLE t0 AS REPLICATED; returns Code 36 every time and rewrites the on-disk metadata; after restart any query on t0 fails Code 722.
b Root cause explained? convertMergeTreeTableIfPossible (InterpreterCreateQuery.cpp) rewrites and persists the metadata to the Replicated engine BEFORE engine-feature validation. ReplicatedMergeTree rejects UNIQUE KEY (supports_unique_key=false) only later in StorageFactory::get, which throws AFTER the metadata file was already replaced, with no rollback. The persisted ReplicatedMergeTree + UNIQUE KEY combo is unloadable on restart.
c Fix matches root cause? Yes. Validates UNIQUE KEY support for the target engine before any side effect (before clearTransactionMetadata / writeMetadataFile), so the rewrite never happens for a rejected conversion.
d Test intent preserved / new tests added? New stateless test 04545_attach_as_replicated_unique_key added: asserts the clean Code 36 and, critically, that a plain ATTACH TABLE t0 afterwards still works (the load path that failed on restart).
e Demonstrated in both directions? Yes. Test FAILS on master HEAD (re-attach fails because metadata was corrupted) and PASSES with the fix. Also verified end-to-end with an actual server restart: pre-fix Code 722, post-fix table loads and SELECT count() returns the inserted rows.
f Fix general, not a narrow patch? Yes. UNIQUE KEY is the only DDL clause whose engine-feature support differs between the MergeTree family (true) and ReplicatedMergeTree (false); all other clauses (settings, sort order, TTL, skip indices, projections) are supported by both. The check covers both conversion directions (to/from replicated) via the computed target engine name and reuses StorageFactory::getStorageFeatures, so it stays in sync with the factory.
g Generalizes across inputs/types? Yes. The check is keyed on the target engine's registered supports_unique_key feature, not on a literal engine name, so it applies to every MergeTree-family engine and both AS REPLICATED / AS NOT REPLICATED directions.
h Backward compatible? Yes. No setting default, on-disk/wire format, or validation-on-existing-data change. It only prevents an invalid metadata rewrite that already errored; the error code (BAD_ARGUMENTS) is unchanged.
i Invariants/contracts preserved? Yes. Reinstates the invariant that persisted table metadata always describes a loadable engine. Reuses the same feature source (StorageFactory) as the later validation, so the two cannot diverge. No lock/ownership/block-structure contracts touched.

Session id: cron:clickhouse-worker-slot-3:20260717-130800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach @tavplubix — could you review? This validates engine-feature support (UNIQUE KEY) before ATTACH ... AS REPLICATED rewrites the on-disk metadata, fixing #110854 where a rejected conversion left the table unloadable after restart (Code 722).

@PedroTadim PedroTadim 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 [8a086bf]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, 7/8) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb, issue

AI Review

Summary

This PR broadens the ATTACH TABLE ... AS REPLICATED fix with shared preflight checks and better regression coverage, but the current version still has late failure paths after the metadata rewrite. I found one new inline issue and one older rollback gap that is still present in the current code, so this is not ready to merge as-is.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:3142-3157, 2225-2360] ATTACH TABLE ... AS REPLICATED still mutates detached tables before every remaining failure is ruled out. clearTransactionMetadata runs before the rewrite, while validateEngineSupportsReplicatedConversion still leaves at least two late failures behind it: max_replicated_table_num_to_throw in throwIfTooManyEntities, and the deliberate constructor-time rejection for inline disk = disk(...) Keeper disks. Either path can still reject the attach after part txn_version files were deleted and/or after the .sql was rewritten, so the rejected conversion does not preserve the original detached table state. Suggested fix: restore a real rollback/backstop for post-validation failures, or move the remaining late checks ahead of clearTransactionMetadata and the metadata rewrite.
  • [src/Interpreters/InterpreterCreateQuery.cpp:3149-3157, 2225-2360] ATTACH TABLE ... AS NOT REPLICATED now has the same late-failure bug in the opposite direction. After this function rewrites the detached table to MergeTree, doCreateTable checks max_table_num_to_throw against the rewritten engine. If the server is already at the regular-table limit, the query throws TOO_MANY_TABLES after the .sql file was de-replicated, so a later plain ATTACH TABLE t loads the table as non-replicated even though the original request failed. Suggested fix: preflight the target-side table-count limit before touching metadata, or restore rollback for post-rewrite failures.
Final Verdict

❌ Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 17, 2026
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed both review findings in 260c771 by factoring a single shared validator (DatabaseOrdinary::validateEngineSupportsReplicatedConversion) used by both the ATTACH ... AS REPLICATED entrypoint and the restart-time converter convertMergeTreeToReplicatedIfNeeded. It rejects Shared* engines and clauses the target engine does not support (UNIQUE KEY) before any metadata rewrite.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Converter (A): create MergeTree+UNIQUE KEY, touch convert_to_replicated, restart → server aborts with Code 36 at startup, on-disk metadata stays ENGINE = MergeTree. Entrypoint: DETACH then ATTACH TABLE t0 AS REPLICATED → Code 36 every time.
b Root cause explained? Both the entrypoint and the restart-time converter call setMergeTreeEngine, which only toggles the leading Replicated prefix, then rewrite metadata. Neither pre-validated engine features on the converter path, and neither rejected Shared*. So (A) MergeTree+UNIQUE KEY+flag was persisted as unloadable ReplicatedMergeTree ... UNIQUE KEY; (B) SharedMergeTree was rewritten to a non-existent ReplicatedSharedMergeTree before StorageFactory::get rejects it.
c Fix matches root cause? Yes. One validator runs supports_unique_key (via getStorageFeatures on the resolved target engine) and a Shared* rejection BEFORE setMergeTreeEngine/metadata rewrite, on BOTH paths. No band-aids.
d Test intent preserved / new tests added? Existing 04545_attach_as_replicated_unique_key.sql (entrypoint) unchanged and still passes. New tests/integration/test_modify_engine_on_restart/test_unique_key.py covers the restart-time converter: rejects the illegal conversion at startup AND asserts the table loads with data intact after removing the flag.
e Both directions demonstrated? Yes. With the fix the converter throws before rewriting (metadata intact, SELECT count() = 2 after flag removal). Without the fix the metadata is rewritten to the unloadable Replicated* ... UNIQUE KEY (the reported #110854 corruption). Entrypoint verified fails→passes on a Build-ID-pinned binary.
f Fix is general across code paths? Yes — this finding WAS the sibling-path gap. The entrypoint and the restart-time converter (the only two callers of setMergeTreeEngine) now share one validator.
g Fix generalizes across inputs? Yes. The supports_unique_key gate resolves the actual target engine name and consults StorageFactory features (works for all MergeTree-family engines, not just MergeTree), and the Shared* guard covers every Shared* engine, not only SharedMergeTree.
h Backward compatible? Yes. No setting/default/format change. It only converts a latent silent-corruption into an explicit BAD_ARGUMENTS; legal conversions are unaffected (the existing convert-on-restart tests still pass).
i Invariants and contracts preserved? Yes. Validation runs before any side effect (metadata rewrite / transaction-metadata clearing), so the "metadata is only rewritten for a legal conversion" invariant now holds on both paths. The converter still runs inside the existing loadTablesMetadata try/catch that reports parse/convert failures.

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

Copy link
Copy Markdown
Collaborator Author

Finding C fix (commit 5d5f37a16300d) — pre-PR validation gate:

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Fixture from 03167: create already_exists_2 at already_exists_1's default replica path (/clickhouse/tables/{uuid}/{shard}), DETACH already_exists_1, ATTACH already_exists_1 AS REPLICATED. Deterministically failed with REPLICA_ALREADY_EXISTS (Code 253) before the fix.
b Root cause explained? The entrypoint convertMergeTreeTableIfPossible ran clearTransactionMetadata → setMergeTreeEngine → metadata rewrite, and the replica-path collision was only detected later by the StorageReplicatedMergeTree constructor. So the stored definition was already rewritten to Replicated* (unloadable) by the time the attach failed — contradicting the PR's "rejected attach leaves metadata intact" guarantee. The restart-time converter already guarded against this with a checkReplicaPathExists preflight; the entrypoint did not.
c Fix matches root cause? Yes. Add the same DatabaseOrdinary::checkReplicaPathExists preflight to the entrypoint before any side effect, guarded by to_replicated. Rejection now happens before the metadata is touched.
d Test intent preserved / new tests added? Stronger. 03167_attach_as_replicated_errors.sh no longer needs the AS NOT REPLICATED recovery after the failed attach; it now asserts the stored engine stays MergeTree (plain re-attach succeeds). All 6 pre-existing error assertions unchanged.
e Both directions demonstrated? Yes (debug build). Without fix (HEAD 260c771, Build ID b59f7fd258d7…): Code 253 from the storage ctor after rewrite, on-disk ENGINE = ReplicatedMergeTree, re-attach fails. With fix (Build ID 5f988ba2cde1…): Code 308 UNEXPECTED_NODE_IN_ZOOKEEPER from the preflight before any rewrite, on-disk stays ENGINE = MergeTree, re-attach succeeds. Full 03167 matched .reference 10/10.
f Fix is general across code paths? Yes — this IS the sibling-path generalization. checkReplicaPathExists is promoted from a file-static to a public static member of DatabaseOrdinary, and both the ATTACH-AS-REPLICATED entrypoint and the restart-time converter convertMergeTreeToReplicatedIfNeeded now call the same preflight (alongside the shared validateEngineSupportsReplicatedConversion from findings A/B).
g Fix generalizes across inputs? The preflight is engine- and clause-agnostic: it resolves the target default_replica_path (macros expanded) and checks Keeper for existence, independent of the table's columns/engine args. N/A for datatype/type-wrapper variation — this is a DDL metadata-safety path, not a data-processing path.
h Backward compatible? Yes. No setting or on-disk/wire format change. The colliding attach failed before (Code 253) and fails now (Code 308) — the operation was rejected either way; only the failure moves earlier (before the metadata rewrite) and stops corrupting the stored definition. No change to successful attaches.
i Invariants and contracts preserved? Yes. The preflight is the exact read-only ZK existence check the converter already relies on (throws on collision, no state mutation, no new locking). The if (to_replicated) guard preserves the AS NOT REPLICATED path, which claims no new replica path. The entrypoint's remaining side-effect ordering is unchanged.

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

Copy link
Copy Markdown
Collaborator Author

CI fix (commit 21a0a98): the new test_convert_to_replicated_rejected_for_unique_key errored in teardown across all integration configs. Its remove_convert_flag helper resolved the data path via get_table_path (a system.tables query), but the illegal conversion deliberately leaves the server refusing to start, so that query hit a dead server (Code: 210 NETWORK_ERROR, Connection refused).

Now follows the sibling test_modify_engine_fails_if_zk_path_exists pattern: capture the data path while the server is up, use stop_clickhouse + start_clickhouse(expected_to_fail=True) for the deterministic failed startup, then rm the flag with the captured path. No query against a down server.

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

Copy link
Copy Markdown
Collaborator Author

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)
# Question Answer
a Deterministic repro? This is a latent shell-safety defect in a test helper, not a reproduced CI failure. The prior form interpolated a system.tables path into bash -c "rm ..."; a path with whitespace/glob chars would be split/expanded by the shell. The argv form removes the shell deterministically.
b Root cause explained? exec_in_container(["bash","-c", f"rm {table_data_path}convert_to_replicated"]) runs the path through a shell, so word-splitting and glob expansion apply. Since this branch runs while the server is intentionally down, a missed cleanup would make the follow-up start_clickhouse() fail for the wrong reason.
c Fix matches root cause? Yes. Replaced with exec_in_container(["rm", f"{table_data_path}convert_to_replicated"]) — no shell involved, so no splitting/globbing is possible. This is the dominant bare-argv form used across the integration suite.
d Test intent preserved / new tests added? Preserved. Same assertions (stored engine stays MergeTree, count()==2); no logic change beyond how the flag file is removed.
e Both directions demonstrated? Passes WITH the fix: test_convert_to_replicated_rejected_for_unique_key 1 passed in 114.9s (flag removed, follow-up start_clickhouse() succeeds). A failing "before" run is not constructible without an artificial whitespace/glob path, since real disk paths here contain neither.
f Fix is general across code paths? Scoped intentionally. The same bash -c interpolation exists in common.py (set_convert_flags/check_flags_deleted) and test_zk_path_exists.py, but those are pre-existing and shared by sibling tests — out of scope for this PR. Only the line this PR introduced is changed.
g Fix generalizes across inputs? N/A (test helper hardening, not a code bug).
h Backward compatible? N/A (test-only).
i Invariants and contracts preserved? N/A (test-only); the argv rm has identical semantics to the shell form for a normal path.

Session id: cron:clickhouse-maint-slot-10:20260717-234900

Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
@tuanpach tuanpach self-assigned this Jul 18, 2026
…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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (c0 Int) ENGINE=MergeTree ORDER BY tuple() SETTINGS table_readonly=1; DETACH TABLE t; ATTACH TABLE t AS REPLICATED; reproduces on demand.
b Root cause explained? StorageReplicatedMergeTree rejects table_readonly = 1 in its constructor (StorageReplicatedMergeTree.cpp:460, mode <= ATTACH). The ATTACH-AS-REPLICATED preflight validator did not check the setting, so setMergeTreeEngine rewrote the metadata to Replicated* ... table_readonly = 1 before the constructor threw, leaving an unloadable definition on disk.
c Fix matches root cause? Yes. Adds the table_readonly check to the shared validateEngineSupportsReplicatedConversion, which runs before any side effect. Also adds a metadata-revert backstop in the entrypoint for construction-time rejections the up-front validation cannot enumerate.
d Test intent preserved / new tests added? Extended 04545_attach_as_replicated_unique_key.sql with the table_readonly = 1 case: rejected with BAD_ARGUMENTS before rewrite, then plain re-attach loads as MergeTree. No existing assertion weakened.
e Both directions demonstrated? Yes. Pristine binary (Build ID 5F988BA...): 04545 fails (no early BAD_ARGUMENTS; conversion proceeds past validation). With-fix binary (Build ID DD2F3751...): 04545 passes (2\n0).
f Fix is general across code paths? Yes. The table_readonly guard lives in the shared validator, so it covers BOTH the ATTACH entrypoint AND the restart-time converter convertMergeTreeToReplicatedIfNeeded. The metadata-revert backstop is entrypoint-only by design: the converter path is async-load with no synchronous construction to wrap, so it relies on the preflight there (explained in-thread).
g Fix generalizes across inputs? table_readonly is a Bool setting; the guard reads it via FieldVisitorConvertToNumber<UInt64> and rejects only truthy values, so a legal table_readonly = 0 conversion (the RMT default) is not rejected. The revert backstop is input-agnostic: it restores the original metadata on ANY construction-time failure, not just this setting.
h Backward compatible? Yes. This rejects an ATTACH that was already broken (it produced an unloadable table); no setting default, on-disk/wire format, or valid existing behavior changes. Server startup / FORCE_ATTACH loading of pre-existing table_readonly RMT metadata is untouched (the storage guard is mode <= ATTACH; only the user-initiated conversion path is affected).
i Invariants and contracts preserved? The revert guard upholds this PR's own guarantee that a rejected attach leaves stored metadata intact. Its scope is safe: armed only after all validation passes, released only after doCreateTable succeeds; for the armed path every intermediate exit is either an exception (revert fires, correct) or unreachable (Atomic-DB / short-syntax / no-cluster invariants are enforced earlier in the same function). The revert lambda is exception-safe (catches all, logs, never rethrows during unwinding).

Session id: cron:clickhouse-premium-slot-24:20260718-024748

Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5efc121

CI fully finished on this head (Config Workflow, Finish Workflow both SUCCESS). No failing checks; every test job green, including the new regression test test_convert_to_replicated_rejected_for_unique_key (8x OK across sanitizers). Earlier reds were on superseded intermediate heads and are resolved on this head.

Check / test Reason Owner / fixing PR
Sync - CH Inc sync (private, not actionable)

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. merge_tree.table_readonly=1 in config + CREATE ... ENGINE=MergeTree; DETACH; ATTACH ... AS REPLICATED -> deterministic.
b Root cause explained? The shared validator checked only the explicit AST table_readonly; RMT rejects the RESOLVED value (config-folded) at construction, and also Keeper-backed disks. So a config-sourced setting slipped past the preflight, the metadata was rewritten to Replicated*, then the ctor threw -> unloadable metadata.
c Fix matches root cause? Yes. The preflight now resolves the effective settings/policy (config folded with query SETTINGS) and rejects the same cases the ctor rejects, before any rewrite.
d Test intent preserved / new tests added? Yes. New converter-path regression for config-sourced table_readonly (ch2 with merge_tree.table_readonly=1); existing UNIQUE KEY / explicit-table_readonly / replica-path tests unchanged.
e Both directions demonstrated? Yes. Pre-fix: config-sourced value passes validation and reaches the rewrite stage. Post-fix: Code 36 before any rewrite, stored engine stays MergeTree. Build ID fc8d939b.
f Fix is general across code paths? Yes. Single shared validateEngineSupportsReplicatedConversion used by BOTH the entrypoint and the restart-time converter.
g Fix generalizes across inputs? Yes. Both effective-state sources the ctor checks are covered: resolved table_readonly (config or AST) and Keeper-backed disks (via disk or storage_policy). No-over-rejection verified for plain / storage_policy / disk inputs. Inline disk=disk(...) is deliberately left to the ctor (resolving it here has side effects).
h Backward compatible? Yes. Only refuses a conversion the target engine would reject at construction anyway; startup load of pre-existing tables uses FORCE_ATTACH and is unaffected. No setting default / format change.
i Invariants and contracts preserved? Yes. Validation is read-only (no AST mutation, no disk materialization) and runs before any side effect. Rejection set kept exactly as narrow as the ctor to avoid refusing valid conversions.

Session id: cron:clickhouse-premium-slot-25:20260720-054200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication scoped-delta 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 ❌ Storage-policy resolution does not fully match the constructor: an explicit storage_policy did not clear a configured disk, and inline disk = disk(...) custom definitions are skipped AGREE (partial) — fixed @ 635da21 Aligned the resolution to registerStorageMergeTree: an explicit disk now takes precedence and clears the config storage_policy path; documented the deliberate skip of inline disk=disk(...) (resolving it materializes the disk as a side effect, so it is left for the constructor). Re-verified no over-rejection for plain / storage_policy='default' / disk='default'.
2 ⚠️ Keeper-backed disk branch has no regression coverage DISAGREE (not testable in OSS) metadata_type='keeper' is Cloud-only: MetadataStorageFactory rejects it as unknown in OSS, so s3_with_keeper cannot be created in a stateless/integration test (same as the SharedMergeTree Finding-B case). Branch covered by constructor-mirroring code + the no-over-rejection tests (plain/storage_policy/disk all still convert). The config-sourced table_readonly sibling path (same resolution + to_replicated gate) has a new converter-path regression.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-premium-slot-25:20260720-054200

@@ -2932,20 +2957,47 @@ void InterpreterCreateQuery::convertMergeTreeTableIfPossible(ASTCreateQuery & cr
clearTransactionMetadata(table_data_path, getContext());

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.

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.

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.

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.

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.

I think we can just rely on the check. Can remove the logic of reverting the file.

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.

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/\n default_replica_name (registerStorageMergeTree.cpp:574,577), reached via doCreateTable after 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.

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.

Please implement the first option.

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.

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 already Replicated*);
  • 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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fix (commit 565965f): the new integration test test_convert_to_replicated_rejected_for_config_table_readonly was failing deterministically (both a regular amd_asan_ubsan batch and the flaky check), not intermittently.

Root cause: the ch2 instance sets merge_tree.table_readonly = 1 in global config, so the plain MergeTree table is read-only from creation and INSERT INTO ro VALUES (1),(2) is rejected with Code 774 TABLE_IS_PERMANENTLY_READ_ONLY (StorageMergeTree::assertNotReadonly). That config-sourced table_readonly is exactly the resolved setting the test exercises, so the table cannot hold data.

Fix: drop the impossible INSERT and assert an empty-but-loadable table (reads do not hit assertNotReadonly). The rejected-conversion => metadata-not-rewritten => still-loads-as-MergeTree assertions are unchanged; data survival across a rejected conversion stays covered by test_convert_to_replicated_rejected_for_unique_key.

Verified: fails on the prior commit (CI, Code 774); passes locally after the fix (both tests x3, 6 passed).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 565965f18dfd4caa2df78652be7324a2086d8e4ef

CI fully finished (Finish Workflow SUCCESS, 20-min ingest buffer met). Every failure below has an owner.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk; 102 master + 14 unrelated PRs / 21d) #111029 (external, open)

The prior own-test PR-caused failure (test_unique_key.py::test_convert_to_replicated_rejected_for_config_table_readonly) was fixed in this PR @ 565965f (dropped the impossible INSERT on the config-table_readonly read-only table; the essential rejected-conversion / metadata-not-rewritten / table-still-loads assertions need no data).

Session id: cron:our-pr-ci-monitor:20260720-150000

groeneai added 2 commits July 22, 2026 07:58
…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
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With default_replica_name empty (config), ATTACH TABLE t AS REPLICATED on a plain MergeTree table. On the pre-change binary (guard removed, no check) it rewrites the on-disk metadata to ReplicatedMergeTree(..., '') and throws in the constructor, leaving the table unloadable.
b Root cause explained? The up-front validateEngineSupportsReplicatedConversion rejected every conversion the target engine refuses EXCEPT an empty/whitespace/unresolvable replica name, which is sourced from the default_replica_name server setting (not the AST) and only checked in the RMT constructor (registerStorageMergeTree: NO_REPLICA_NAME_GIVEN / BAD_ARGUMENTS), i.e. AFTER the metadata rewrite. The metadata_revert_guard backstopped only the .sql file, never per-part txn metadata.
c Fix matches root cause? Yes. Per the assignee's decision: remove the revert guard and rely on the check, then close the one gap it exposed by resolving default_replica_name up front (exactly as TableZnodeInfo::resolve does, UUID cleared) and rejecting empty / \t / \n / unresolvable {uuid} before any on-disk side effect. Shared validator covers both the ATTACH entrypoint and the restart converter.
d Test intent preserved / new tests added? Added test_convert_to_replicated_rejected_for_empty_replica_name (ch3 instance, empty default_replica_name in config): rejected conversion leaves the table as MergeTree with data intact after restart. Existing UNIQUE KEY / config-table_readonly tests unchanged.
e Both directions demonstrated? Yes. WITHOUT the check (guard removed): on-disk .sql becomes ReplicatedMergeTree(..., ''), re-attach fails (Code 237) = corrupted. WITH the fix: rejected up front (Code 237 / Code 36 for {uuid}), engine stays MergeTree, data intact. Valid r1 and {replica} still convert (no over-rejection).
f Fix is general across code paths? Yes. The rejection lives in the single shared validateEngineSupportsReplicatedConversion, so both callers (ATTACH entrypoint convertMergeTreeTableIfPossible and restart converter convertMergeTreeToReplicatedIfNeeded) get it. No sibling path rewrites metadata without going through this validator.
g Fix generalizes across inputs? Covered replica-name variants: empty, \t/\n, and {uuid} (unresolvable at conversion time). The {uuid} case is why the resolution mirrors TableZnodeInfo::resolve exactly (UUID cleared) rather than expanding with the UUID present, which would let it slip past. {replica} and static names still resolve and convert.
h Backward compatible? Yes. No setting default, on-disk format, or wire change. The new rejection only refuses conversions the RMT constructor already refuses (just earlier, before the metadata rewrite), so no previously-succeeding ATTACH AS REPLICATED becomes rejected.
i Invariants and contracts preserved? Yes. The invariant "a rejected ATTACH AS [NOT] REPLICATED leaves the persisted metadata unchanged" now holds for the replica-name path without the revert guard (rejection happens before clearTransactionMetadata and the .sql rewrite). Residual runtime-only throw paths (max_replicated_table_num_to_throw, inline disk(...) Keeper disk) are noted in-thread for the assignee's scope decision.

Session id: cron:clickhouse-premium-slot-24:20260722-070700

@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; 3 findings;
bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Removing the revert lets a failure after the metadata rewrite (e.g. max_replicated_table_num_to_throw in throwIfTooManyEntities, inline disk(...) Keeper) persist the Replicated* conversion DISAGREE (escalated) Mechanism confirmed real, but restoring the guard directly contradicts the assignee's directive to remove it. He owns this rollback-completeness scope call; the residual runtime-only paths are surfaced in-thread for his decision rather than acted on unilaterally.
2 ❌ The new replica-name preflight accepted default_replica_name = {uuid} (expanded with UUID present) although the storage resolver clears the UUID first, so the ctor throws after the rewrite AGREE - fixed @ 2c0cda0 Expand with UUIDHelpers::Nil to match TableZnodeInfo::resolve. Verified: {uuid} now rejected up front (Code 36), metadata stays MergeTree; {replica} still converts.
3 💡 Test repeats the same root-cause narrative in the instance declaration and the test body AGREE - fixed @ 2c0cda0 Trimmed the test-body comment; the ch3 instance declaration carries the "why".

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

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

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 64/73 (87.67%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 8a086bf

CI 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk: 118 master hits + dozens of unrelated PRs / 30d; unrelated to this PR's ATTACH-AS-REPLICATED metadata change) #111029 (external, open)

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);

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 it's terrible, are you reinventing these validations again? Is there a better way to eliminate the redundancy?

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.

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:

  1. Extract each constructor precondition rejection into a shared static validator that both the ctor and this preflight call. Single source of truth, no drift.
  2. 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?

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

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.

@tavplubix

Copy link
Copy Markdown
Member

Probably we don't need this as all #110854 (comment)

@tavplubix tavplubix closed this Aug 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured on master 49e1373adb63 (26.8.1.1) with Keeper configured.

Before a restart, yes: ATTACH TABLE t0 AS NOT REPLICATED restores ENGINE = MergeTree with UNIQUE KEY (c0) intact, and the rows read back fine.

After a restart, no. Every DDL on the table then waits on the failed load job and returns Code 722:

  • ATTACH TABLE t0 AS NOT REPLICATED -> 722
  • DETACH TABLE t0, DETACH TABLE t0 PERMANENTLY -> 722
  • DROP TABLE t0, DROP TABLE t0 SYNC -> 722
  • SYSTEM RESTORE REPLICA t0 -> 722

The only recovery I found is editing t0.sql on disk by hand. With async_load_databases = 0 the server does not start at all: loadMetadata throws ASYNC_LOAD_WAIT_FAILED on that one table. Hand-repairing the file lets it start with the data intact, which confirms the table is what blocks startup.

So the escape hatch works only inside the session where the failed ATTACH ... AS REPLICATED happened. The state reported here is the post-restart one, where it does not help.

Whether that is worth a pre-write check is your call. I have not reopened #110863.

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

Bad validation on unique key table on attach

5 participants