Skip to content

Allow attach as replicated for Ordinary databases - #118757

Merged
alexey-milovidov merged 34 commits into
ClickHouse:masterfrom
kirillgarbar:allow-replicated-conversion-ordinary
Oct 2, 2026
Merged

alexey-milovidov merged 34 commits into
ClickHouse:masterfrom
kirillgarbar:allow-replicated-conversion-ordinary

Conversation

@kirillgarbar

@kirillgarbar kirillgarbar commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

It is allowed to convert MergeTree tables in Ordinary databases to ReplicatedMergeTree with ATTACH TABLE ... AS REPLICATED or convert_to_replicated flag.


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

Version info

  • Merged into: 26.10.1.1307-master (included in 26.10 and later)

@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 8, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e716f02]

Summary: ✅


AI Review

Summary

This PR extends ATTACH TABLE ... AS REPLICATED and the startup convert_to_replicated path to MergeTree tables in Ordinary databases by minting a temporary UUID for conversion, storing a safe literal Keeper path, unfolding default_replica_name the same way as CREATE TABLE, and covering the resulting detach / restart / rename / DROP TABLE edge cases with focused tests. After reviewing the current diff, the current code, and every prior discussion thread, I do not see a remaining correctness issue that still warrants an inline review comment.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit e716f02.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 191/211 (90.52%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 12, 2026
alexey-milovidov and others added 2 commits September 13, 2026 09:07
…Ordinary-database check

The PR removed the query asserting that `ATTACH TABLE ... AS REPLICATED` is
rejected for `Ordinary` databases, but the reference file still expected
seven lines of output, so Fast test failed with "result differs with
reference".

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118757&sha=bcaa82ad9544289b69b70f95bcbe6a23bcab4737&name_0=PR&name_1=Fast%20test
PR: ClickHouse#118757

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e716f0254 with master d9bcb5ab0 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

18 object files changed (+73.97 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseOrdinary.cpp.o 730.06 KiB 771.07 KiB +41.00 KiB (+5.62%)
src/CMakeFiles/dbms.dir/Storages/TableZnodeInfo.cpp.o 117.64 KiB 135.07 KiB +17.43 KiB (+14.82%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

85 translation units recompiled, 844 s compile time in total, 85 of them have a recent master baseline.

Job report

…ses against a live detached storage

`convertMergeTreeTableIfPossible` skipped the detached-table liveness check for `Ordinary`
databases, because their tables have no UUID to key `checkDetachedTableNotInUse` by. But an
`Ordinary` table can still carry `txn_version.txt` files after `RENAME TABLE` from an `Atomic`
database, and `clearTransactionMetadata` must not delete them while the previous storage
instance is alive: its parts check those files in `assertHasValidVersionMetadata` on destruction.

`DatabaseOrdinary` now remembers detached storages by table name (weak references, so the
tracking never extends their lifetime) and offers `checkDetachedTableByNameNotInUse` /
`waitDetachedTableByNameNotInUse`, which the conversion uses for `Ordinary` databases the same
way it uses the UUID-keyed guard for `Atomic`. A storage that was renamed after being detached
no longer identifies as the table, so `RENAME TABLE` does not block a later re-attach.

Test `05214_attach_as_replicated_ordinary_implicit_transaction` renames a table with parts
written under implicit transactions from `Atomic` to `Ordinary`, detaches it, and converts
it to replicated and back.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
alexey-milovidov and others added 3 commits September 14, 2026 06:53
…ble in the liveness guard

A plain `ATTACH TABLE` of an `Ordinary` table does not wait for the previous detached
instance (there is no UUID to key the generic wait on), so `DETACH` -> `ATTACH` -> `DETACH`
can leave two live detached instances with the same name. `insert_or_assign` dropped the
older one, so `ATTACH ... AS REPLICATED` waited only for the newer instance and could still
delete `txn_version.txt` under the parts of the older one. Track the instances in a multimap
and wait until none of them is alive; expired entries are pruned on every detach and check.

Test 05214 now re-attaches the table once before the conversion, so the guard sees two
instances of the same name.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…eMergeTree.cpp` too

`replication.mdx` is the rendered form of the `Documentation{...}` block of `ReplicatedMergeTree`,
so the `convert_to_replicated` path for an `Ordinary` database and the one-time
`default_replica_path` expansion belong in the source text as well.

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

Copy link
Copy Markdown
Member

🕵 The only red check on e6d93a0, Stress test (arm_release), is unrelated to this PR: the server failed to restart on ATTACH TABLE test_7.t_pfl_05079 (s AggregateFunction(quantile('0.5'), Float64)) with CANNOT_CONVERT_TYPE, a quantile parameter type-name round-trip problem from another test. The fix is in progress in #119810. Merged master (283 commits, no conflicts) and adopted both review threads; all 22 attach_as_replicated/rename_table stateless tests pass locally.

…LE ... AS REPLICATED` statement docs

The structured docs of the statement live in `ParserCreateQuery.cpp` and are
rendered into `docs/reference/statements/attach.mdx`; they still described only
the generic behavior. Say that `Atomic` and `Ordinary` databases are supported,
that for `Ordinary` a UUID is generated and `default_replica_path` is expanded
once, and that further replicas must reuse the resulting explicit path.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, the only red check on faa602f, Stress test (arm_asan_ubsan, s3), is unrelated to this PR: Invalid number of columns in chunk pushed to OutputPort. Expected 2, found 1 with a countResample(10, 5, 1) aggregate state (issue #114611), which also fails on master since 2026-09-13. The fix is in progress in #119728. The remaining AI review item (the ATTACH ... AS REPLICATED statement docs in ParserCreateQuery.cpp) is addressed in 8e4b189.

Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
…onvert_to_replicated`

`checkReplicaPathExists` expanded `default_replica_path` on its own and asked
`getZooKeeper` (the default cluster) whether the path exists. A template that
addresses an auxiliary Keeper, `<name>:/clickhouse/tables/{uuid}/{shard}`,
therefore probed the wrong cluster with the prefixed string, so the restart
conversion failed there, while the table itself would later resolve the path
through `TableZnodeInfo` and use the right cluster. The conversion now reuses
the `TableZnodeInfo` that `checkReplicaPathIsSafe` already resolves, and asks
`getDefaultOrAuxiliaryZooKeeper(zookeeper_name)` about the raw path.

The new integration test `test_auxiliary_zookeeper.py` configures a chrooted
auxiliary Keeper as the `default_replica_path` target and checks, for both
`Atomic` and `Ordinary` databases, that the conversion lands in that cluster
(`system.replicas.zookeeper_name`, and the znodes under the chroot seen from
the default Keeper) and that a path already occupied only in the auxiliary
cluster makes the conversion refuse, with the prefixed path in the message.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
alexey-milovidov and others added 3 commits September 15, 2026 03:30
…after unlocking the database mutex

`DatabaseOrdinary::forgetExpiredDetachedTablesByName` locked every weak entry into a local `StoragePtr`
while `DatabaseOrdinary::mutex` was held. If another thread released the last external owner during the
iteration, that local pointer became the final owner and destroyed the detached storage under the database
mutex, which `DatabaseAtomic::cleanupDetachedTables` deliberately avoids because such a destruction can
deadlock. The sweep now hands every strong reference to a `keep_alive` container that the callers
(`detachTable`, `checkDetachedTableByNameNotInUse`, `waitDetachedTableByNameNotInUse`) destroy only after
the lock is released.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…dinary` table

Converting a table of an `Ordinary` database to `ReplicatedMergeTree` mints a UUID for the `{uuid}` macro of
`default_replica_path` and stores the fully expanded path as a literal, because the metadata of such a table
has no place for a UUID. On reload `TableZnodeInfo::resolve` saw no `{uuid}` macro, left `path_prefix_for_drop`
equal to the replica path, and `DROP TABLE` kept the emptied `/clickhouse/tables/<uuid>` parent znode, unlike
the same conversion in an `Atomic` database.

The literal path is the only record of that UUID, so `resolve` now recovers the owned prefix from it for
tables without a UUID of their own: the prefix ends with the last path component that is a UUID. Only
znodes that became empty are removed, as before. Test `05218_attach_as_replicated_ordinary_drop_znode`
converts, restores, reloads and drops such a table and checks the parent znode is gone.

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

Copy link
Copy Markdown
Member

🕵 @groeneai, the only red check on e261595, Stress test (arm_tsan), is unrelated to this PR: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118757&sha=e26159554835816190f768f5e176d644fe6be3b1&name_0=PR&name_1=Stress%20test%20(arm_tsan) — Hung check failed: two DETACH DATABASE queries wait in IMergeTreeCleanupThread::stop for exec_mutex, held by 19 cleanup tasks stuck in clearPartsFromFilesystemImplMaybeInParallel; all 128 parts-cleaning workers sit in DiskObjectStorageTransaction::waitBlobRemoval -> BlobKillerThread::triggerAndWait, and the blob killer's 17 Azure batch-delete tasks sleep in the Azure SDK RetryPolicy::Send. No frame touches DatabaseOrdinary or the conversion code (the c_stacktraces.log artifact has all 1069 threads). Please investigate and provide a fix in a separate PR, or link it here if one is already in progress. The two AI review items are adopted in 96fcffc and bba7e81, and master is merged (486 commits, no conflicts).

Comment thread src/Storages/TableZnodeInfo.cpp Resolved
…nversion-ordinary

Conflicts with the new `table_readonly` refusal in `convertMergeTreeToReplicatedIfNeeded` and
`convertMergeTreeTableIfPossible`: kept master's check first (before any temporary UUID is
assigned for an `Ordinary` database), then this PR's `Ordinary` handling.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master into the branch (6b97b23) to resolve the conflicts with the new table_readonly refusal (#118757 was CONFLICTING). In both DatabaseOrdinary::convertMergeTreeToReplicatedIfNeeded and InterpreterCreateQuery::convertMergeTreeTableIfPossible, master's isTableReadonlyAsReplicated check now runs first, before the temporary UUID is assigned for an Ordinary database, and this PR's Ordinary handling follows. Rebuilt locally; the 10 *attach_as_replicated* / *drop_znode* / *uuid_component_not_owned* stateless tests and master's 05192_convert_to_replicated_table_readonly pass. The previous Upgrade check red needed a 26.9 release newer than v26.9.2.8; v26.9.4.3 is out now, so it should clear on this run.

…cument `{uuid}` in `default_replica_name`

The startup route `DatabaseOrdinary::convertMergeTreeToReplicatedIfNeeded` is a separate entrypoint from
`ATTACH TABLE ... AS REPLICATED`, so the name-in-path refusal and the `{uuid}`-in-`default_replica_name`
refusal get their own restart tests next to the existing two-UUIDs one, sharing a helper.

The `convert_to_replicated` docs now say that `{uuid}` in `default_replica_name` is not supported for any
conversion, as the `ATTACH` statement docs do.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed f9b5f26, which addresses both AI-review items: restart-path (convert_to_replicated) negative tests for the name-in-path refusal and the {uuid}-in-default_replica_name refusal, and the matching docs sentence. test_uuid_shaped_template.py passes locally (12/12). The CH Inc sync failure was the incremental sync being unable to merge the new head into the manually adapted sync branch. I did that merge by hand: private master plus this head, resolving DatabaseOrdinary.cpp and InterpreterCreateQuery.cpp against the private-only code. I pushed the result to sync-upstream/pr/118757 as 673b17a681f. Its diff against private master is identical to this PR's diff apart from the existing local_context adaptation.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118757&sha=f9b5f26215e325b766cc74ad3b227e24f710c2e6&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%202%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

lower_upper_utf8_mixed_ascii #5 (lowerUTF8(unicode), 12.7 ms -> 15.0 ms, confirmed_regression) is unrelated to this PR, which only touches the Ordinary-database attach-as-replicated path. The same query (and its neighbour #4) is flagged slower on arm_release in many unrelated PRs over the last 10 days (#116800, #76867, #120938, #117722, #121081, #118929, #119119). The open #122728 stabilizes only the mixed_01_clustered queries, so it does not cover #4/#5. Every other check is green, and CH Inc sync passes.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix in progress is #122728 (approved, CI finished green).

#5 on this run is upperUTF8(mixed_01_clustered), not lowerUTF8(unicode): perf.py expands the sorted substitution keys (column, function) with function varying fastest, so #4/#5 are lowerUTF8/upperUTF8 of mixed_01_clustered, and lowerUTF8(unicode) is #10. In query_metrics_v2 for f9b5f26215e3 (arm), #5 went 12.7 -> 15.0 ms with minor page faults 4521 -> 6463, the two-level pattern that #122728 removes, while #10 stayed at 234 ms. The seven PRs you listed show the same #4/#5 slowdown, and neither unicode query (#10/#11) was more than 15% slower in any arm run in the last 10 days.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thanks @groeneai, and thanks for the correction: #5 is upperUTF8(mixed_01_clustered), not lowerUTF8(unicode). #122728 is merged, so I merged master into the branch (b86f27f) to pull it in. The merge had no conflicts and builds locally. All 11 *attach_as_replicated* / *drop_znode* / *uuid_component_not_owned* / 05192_convert_to_replicated_table_readonly stateless tests pass.

Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
…`Ordinary` table

Address review: a conversion of a table of an `Ordinary` database to a
replicated engine expanded `default_replica_path` once but stored
`default_replica_name` verbatim. With a name such as
`{database}_{table}_{replica}`, the metadata kept `{database}` / `{table}`,
so on every later load `TableZnodeInfo::resolve` set `DO_NOT_ALLOW` and
`RENAME TABLE` of the converted table was refused.

Both conversion entrypoints (`ATTACH TABLE ... AS REPLICATED` and the
`convert_to_replicated` flag) now store `replica_name_for_metadata` from
the `TableZnodeInfo` that `checkReplicaPathIsSafe` already resolves, the
same way `CREATE TABLE` unfolds those macros; `{replica}` and other
macros stay unexpanded. Integration tests cover both entrypoints with a
rename and a re-attach.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failures and provide a fix in a separate PR. If a fix is already in progress, link it here. Both are unrelated to this PR, which only touches ATTACH ... AS REPLICATED / convert_to_replicated for Ordinary databases:

Comment thread src/Storages/TableZnodeInfo.cpp Resolved
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. I found no fix in progress for either failure. I am investigating both (05241_external_distinct_coalescing hitting MEMORY_LIMIT_EXCEEDED in its final system.query_log check, and joins_in_memory #20 on arm_release), and I will follow up here with the fix PR(s) or my findings shortly.

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator
  • 05241_external_distinct_coalescing: fix in Apply the memory limit of the external DISTINCT tests only to the queries under test #123286. The test's session-level SET max_memory_usage also capped the final system.query_log check. With the randomized use_uncompressed_cache = 1, that check is charged for every block it decompresses, so its memory depends on how much the whole parallel run wrote to query_log. The PR moves the limit into the SETTINGS of the queries under test, and makes the same change in 05242_external_distinct_limit_remerge.
  • joins_in_memory #20 (and #19, which is the same query): the whole difference is inside firstNonDefault. FULL JOIN USING evaluates it over every joined row, and does a virtual isDefaultAt per argument and a virtual insertFrom for every row. On arm its speed depends on where the linker places those callees, so unrelated changes move it by up to ~24%. I am preparing a separate PR that removes the per-row virtual calls, and I will link it here.

@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

joins_in_memory #19/#20: fix in #123302. It copies the rows decided by each firstNonDefault argument as ranges instead of making two virtual calls per row. On x86, #19/#20 user CPU goes from 0.40 to 0.15 s and wall time from 0.092 to 0.079 s, with the #10 control unchanged. The arm effect will show in that PR's Performance Comparison.

alexey-milovidov and others added 3 commits October 1, 2026 19:51
…onverted `Ordinary` table

The owned prefix of a converted `Ordinary` table is recovered by matching its literal path against
the current `default_replica_path`. When the template changes later, the match fails and the table
owns only its own znode again: it keeps loading, and `DROP TABLE` leaves the minted UUID-named parent
behind instead of removing anything it may not own. Document this and add a restart-after-config-change
regression test.

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

Copy link
Copy Markdown
Member

🕵 Merged master (426 commits, no conflicts) and pushed e716f02.

  • The red Integration tests (amd_asan_ubsan, db disk, targeted) / (flaky) on cd33c81 was a bug in this PR's own test. test_name_in_replica_name_unfolded* compared against SHOW CREATE TABLE, whose TSV output escapes the quotes around the engine arguments. Fixed in 9ddb5d6 by reading engine_full with FORMAT TSVRaw.
  • 05227_clickhouse_local_max_execution_time_s3 (Stateless tests arm_binary, parallel) is unrelated to this PR and was not reproducible: all 4 reruns with the same settings passed.
  • I replied to the review thread about a changed default_replica_path and added the regression test it asked for.

All 15 tests in test_modify_engine_on_restart/test_uuid_shaped_template.py pass locally, including the new one.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 2, 2026
Merged via the queue into ClickHouse:master with commit 8f53dd7 Oct 2, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 2, 2026
feiyunwill pushed a commit to feiyunwill/ClickHouse that referenced this pull request Oct 5, 2026
…ries under test

05241_external_distinct_coalescing set max_memory_usage = 128 MiB for the
whole session, so the limit also applied to the final system.query_log
check. With the randomized use_uncompressed_cache = 1, that check is charged
for every block it decompresses into the uncompressed cache
(CachedCompressedReadBuffer::nextImpl allocates the cache cell under the
query's memory tracker), and in a parallel run the granules around the four
matching rows hold the ProfileEvents of many other tests. The check then
failed with MEMORY_LIMIT_EXCEEDED while the queries under test were fine
(Stateless tests (amd_debug, parallel) on ClickHouse#118757).

Move the limit into the SETTINGS of the four queries under test, so the
check runs with the job's normal limits. 05242_external_distinct_limit_remerge
has the same construction (512 MiB) and gets the same change. The queries
under test keep the same limit; the references are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-feature Pull request with new product feature 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.

4 participants