Skip to content

Support Replicated MergeTree engines and ON CLUSTER DDL (#71) - #73

Merged
alex-clickhouse merged 5 commits into
mainfrom
alex-clickhouse/replicated-mergetree
Nov 25, 2026
Merged

alex-clickhouse merged 5 commits into
mainfrom
alex-clickhouse/replicated-mergetree

Conversation

@alex-clickhouse

@alex-clickhouse alex-clickhouse commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #71.

Why

On a self-managed cluster, the provider creates only plain MergeTree family tables, and only on the server of the connection. Rows written to one replica do not get to the other replicas. The migrations history table has the same problem: each replica has its own history, so a migration that ran through one replica looks unapplied on another. That is the divergence that #71 reports.

A Replicated engine alone does not fix this. ClickHouse does not replicate CREATE TABLE and DROP TABLE. It does replicate ALTER TABLE on a Replicated table, so running the migrations once on each host fails at the second host. The DDL must run once, on all hosts.

What

Replicated engines. Each MergeTree family engine builder has two new methods:

b.ToTable("events", t => t
    .HasReplacingMergeTreeEngine("Version")
    .WithOrderBy("Id")
    .WithReplication());                       // ReplicatedReplacingMergeTree(`Version`)
//  .WithReplication("/clickhouse/tables/{shard}/{database}/{table}", "{replica}")
//                                             // ReplicatedReplacingMergeTree('/clickhouse/...', '{replica}', `Version`)

Without arguments, ClickHouse uses the server settings default_replica_path and default_replica_name. The model keeps the engine annotation as it is (for example ReplacingMergeTree) and adds ClickHouse:Replicated, ClickHouse:Replicated:ZooKeeperPath and ClickHouse:Replicated:ReplicaName. Model validation rejects replication on Log and Memory engines, and a path without a replica name. Because the annotations have the ClickHouse: prefix, the existing AlterTable check rejects a migration that turns replication on or off.

UseCluster(name). A context option that adds ON CLUSTER '<name>' to the DDL that migrations, EnsureCreated() and EnsureDeleted() generate:

  • CREATE DATABASE and DROP DATABASE (the migration operations and the database creator)
  • CREATE TABLE, DROP TABLE, RENAME TABLE
  • every ALTER TABLE: ADD/DROP/MODIFY/RENAME COLUMN, the REMOVE CODEC/TTL/COMMENT statements, ADD/DROP INDEX, ADD/DROP CONSTRAINT

The name is a string literal, so macros such as {cluster} work. DROP TABLE and the two check constraint operations now have their own overrides, because the base implementations have no place for the clause. The check constraint overrides keep the statement terminator of the base implementations. The CREATE TABLE override writes the statement itself for the same reason.

Replicated migrations history table.

  • With UseCluster, __EFMigrationsHistory is ReplicatedMergeTree('/clickhouse/tables/{uuid}', '{shard}-{replica}'). The server default path contains {shard}, which gives each shard its own history. Then a host on a second shard sees no applied migrations and fails on CREATE TABLE ... ON CLUSTER (TABLE_ALREADY_EXISTS). I checked both paths on a two-shard cluster. {shard}-{replica} keeps the replica names unique when shards reuse the same replica names.
  • A database with the Replicated engine refuses ON CLUSTER and an explicit path. So UseReplicatedMigrationsHistoryTable() gives ReplicatedMergeTree() without ON CLUSTER. There, each shard has its own history: a Replicated database refuses a replicated table that the shards share, also with database_replicated_allow_replicated_engine_arguments set to 1 or 3 (checked on a two-shard cluster). The README and XML docs say to run the migrations through one shard.
  • A replicated history table has replicated_deduplication_window = 0 and replicated_deduplication_window_for_async_inserts = 0. Without them, ClickHouse drops the second history row of a migration that is reverted and applied again (the row is equal to the first one). Then the next Migrate() fails with TABLE_ALREADY_EXISTS.
  • An existing history table is not converted. The README has the SQL to convert a MergeTree history table, and I tested it on the cluster.

Statement terminators in migration scripts (also fixed here). EF Core puts only a line break between the commands of a migration script. The provider's ALTER TABLE, RENAME TABLE, CREATE DATABASE and DROP DATABASE statements had no ;, so clickhouse-client read two statements as one and failed with a syntax error. This bug is also on main. Migrations that run from code were not affected, because the provider sends each statement separately. All statement ends in the SQL generator now go through one helper, TerminateStatement, that appends the terminator.

How

  • ClickHouseEngineBuilder has two protected helpers that set the annotations. The seven MergeTree family builders expose them as WithReplication overloads. Log and Memory builders do not get the method.
  • ClickHouseMigrationsSqlGenerator puts the path and replica name before the engine arguments, and prefixes the engine name with Replicated. The engine-argument code now returns a list, so that the two kinds of arguments join with one separator.
  • UseCluster and UseReplicatedMigrationsHistoryTable are properties of ClickHouseOptionsExtension. The generator, the database creator and the history repository read them from IDbContextOptions. These services are scoped, so two contexts with different settings that share one internal service provider still generate different DDL.
  • The MergeTree family check moves to one internal helper (ClickHouseEngines), which the convention, the validator and the generator share.

Design notes

  • Replication is part of the model, so it is in the migrations. The cluster name is an option, so the same migrations can run with or without ON CLUSTER. A development server without ClickHouse Keeper cannot create a Replicated table.
  • Public API change: the constructors of ClickHouseMigrationsSqlGenerator and ClickHouseDatabaseCreator take IDbContextOptions (the creator also takes IRelationalTypeMappingSource). A subclass must pass them on.
  • WithReplication() without arguments uses the server default path, which contains {uuid}. ClickHouse accepts {uuid} only with ON CLUSTER or in a Replicated database. The README and XML docs say this.
  • A Replicated table ignores an insert with the same rows as a recent insert, so two equal SaveChanges calls store the rows once. The README says this and names the table setting that keeps both. (On 26.10 the session setting insert_deduplicate=0 has no effect, because deduplicate_insert overrides it.)
  • The provider has no migration lock (this is not new). Two migrators on different replicas can still race, and a host sees a migration as applied only after its history row has replicated. The README says to run the migrations from one place.
  • Not in this PR: Distributed tables, DROP ... SYNC, and a Replicated database engine for EnsureCreated(). The README tells users to keep {uuid} in an explicit path, because a drop and a create with the same fixed path fails for about 8 minutes (REPLICA_ALREADY_EXISTS). To use other history table settings, a user can derive from ClickHouseHistoryRepository. A test shows how.

Tests

  • MigrationScriptIntegrationTests (1 test, single server): generates the script of three migrations that use each overridden statement, as dotnet ef migrations script does, splits it at the terminators and runs each statement. It then checks the schema and the history rows. I also ran the same script through clickhouse-client --multiquery by hand: exit code 0, with the expected schema and 3 history rows. Every_DDL_statement_ends_with_the_statement_terminator checks all 14 DDL statement kinds, with and without UseCluster. Without the terminator, all three tests fail.
  • ReplicationSqlGenerationTests (35 tests, no server): the default and the explicit path for each of the 7 engines, escaping, validation, the AlterTable rejection, ON CLUSTER on each DDL statement, and the three history table configurations.
  • ReplicationIntegrationTests (5 tests): a new ClickHouseClusterFixture starts three clickhouse-server:latest containers, with ClickHouse Keeper embedded in the first. It defines two clusters: test_cluster, one shard with the replicas ch1 and ch2, and two_shards, which adds ch3 as a second shard. ch3 reuses the replica name r1 of ch1. Each test writes through one host and reads through another:
    • EnsureCreated with all 6 engines that need no server config (GraphiteMergeTree needs a rollup config). Each table has 2 replicas in system.replicas, rows written through replica 1 can be read through replica 2, and EnsureDeleted removes the database on both.
    • Migrations: migration 1 applied through replica 1, then replica 2 lists only migration 2 as pending and applies it. Replica 1 then lists both as applied, reverts migration 2 and applies it again, and replica 2 then has no pending migrations.
    • Two shards that reuse a replica name: migration 1 applied through shard 01, then ch3 (shard 02) lists only migration 2 as pending and applies it. A history path with {shard} makes this test fail on the pending migrations. A replica name without {shard} makes it fail with REPLICA_ALREADY_EXISTS.
    • An explicit path and UseCluster("{cluster}").
    • A Replicated database with UseReplicatedMigrationsHistoryTable().
  • I made each part of the fix fail on purpose and ran the cluster tests. With a history table that is not replicated, the 2 migration tests fail. Without ON CLUSTER, the 3 tests that use it fail. With insert deduplication left on in the history table, the migration test fails at the revert-and-apply step.
  • Not in CI, checked by hand: the history table conversion SQL, and the migration code and model snapshot that dotnet ef migrations add scaffolds for a replicated table. The annotations come out as .Annotation("ClickHouse:Replicated", true) and so on.
  • A separate review agent read the first commit and tested it on the cluster. The second commit fixes what it found: the history row deduplication, the shard path, ON CLUSTER for check constraints, and the missing docs.
  • Full suite: EFCore.ClickHouse.Tests 704 passed (661 before), EFCore.ClickHouse.FunctionalTests 323 passed, 4 skipped (the same as before). The cluster fixture adds about 45 s.
  • Build: 0 errors. The provider project has the same 45 warnings as main. The test projects have 13 more EF1001 warnings, because the new unit tests use ClickHouseAnnotationNames the same way as the existing tests.
  • Coverage: all new lines are covered.

🤖 Generated with Claude Code


Note

Medium Risk
Changes migration DDL generation and shared migration history on clusters; incorrect cluster/replication config can fail migrations or diverge history across hosts. Constructor signature changes affect custom subclasses of the SQL generator and database creator.

Overview
Adds cluster-ready table engines and DDL so self-managed ClickHouse deployments can use Replicated MergeTree tables and run migrations consistently across hosts.

Replicated engines: Every MergeTree-family fluent builder gains .WithReplication() and .WithReplication(zooKeeperPath, replicaName), which emit Replicated* engines with Keeper path/replica arguments ahead of engine-specific args. Replication is stored on the model (ClickHouse:Replicated, path, replica name); validation blocks replication on Log/Memory engines and mismatched path/replica pairs; migrations that toggle replication are rejected like other engine changes.

Cluster DDL: UseCluster(clusterName) on UseClickHouse adds ON CLUSTER to generated DDL from migrations, EnsureCreated/EnsureDeleted, and the database creator—covering create/drop database, create/drop/rename table, and all migration ALTER TABLE paths (including check constraints). UseReplicatedMigrationsHistoryTable() targets Replicated-engine databases (no ON CLUSTER). The history repository now builds a shared ReplicatedMergeTree history table when those options are set, with deduplication settings disabled so revert/re-apply keeps history rows.

Other fixes in this PR: Migration scripts now terminate every statement with ; (fixes clickhouse-client multi-statement runs). SummingMergeTree with multiple sum columns emits a tuple argument. ClickHouseMigrationsSqlGenerator and ClickHouseDatabaseCreator constructors take extra dependencies (IDbContextOptions, and type mapping on the creator)—subclasses must forward them.

Docs (README, changelog) and integration/SQL-generation tests for replication and clusters are included.

Reviewed by Cursor Bugbot for commit 4bae37a. Bugbot is set up for automated code reviews on this repo. Configure here.

@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Shard-specific migration histories can cause already-applied migrations to rerun across shards, while missing check-constraint statement terminators produce invalid migration scripts.

2 open issues
What changed in this PR

Adds replicated MergeTree engines and cluster-wide DDL to the ClickHouse EF Core provider, addressing the table and migration-history divergence reported in #71.

Changes:

  • Adds replication configuration and validation for all seven MergeTree-family engines.
  • Adds UseCluster for cluster-wide DDL and replicated migration-history options.
  • Adds SQL-generation tests, two-replica integration coverage, and deployment documentation.
File Description
test/​EFCore.ClickHouse.Tests/​ReplicationSqlGenerationTests.cs Tests replicated engines, validation, cluster DDL, and history configuration.
test/​EFCore.ClickHouse.Tests/​ReplicationIntegrationTests.cs Tests replication and migration history across two replicas.
test/​EFCore.ClickHouse.Tests/​ClickHouseClusterFixture.cs Provides a two-node cluster with embedded Keeper.
src/​EFCore.ClickHouse/​Storage/​Internal/​ClickHouseDatabaseCreator.cs Adds cluster clauses to database creation and deletion.
src/​EFCore.ClickHouse/​README.nuget.md Summarizes replication and cluster support.
src/​EFCore.ClickHouse/​Migrations/​Internal/​ClickHouseHistoryRepository.cs Configures replicated history tables with deduplication disabled.
src/​EFCore.ClickHouse/​Migrations/​ClickHouseMigrationsSqlGenerator.cs Generates replicated engine arguments and cluster-wide DDL.
src/​EFCore.ClickHouse/​Metadata/​Internal/​ClickHouseEngines.cs Centralizes MergeTree-family identification.
src/​EFCore.ClickHouse/​Metadata/​Internal/​ClickHouseAnnotationNames.cs Defines replication metadata keys.
src/​EFCore.ClickHouse/​Metadata/​Conventions/​ClickHouseDefaultEngineConvention.cs Uses the shared engine-family helper.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseVersionedCollapsingMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseSummingMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseReplacingMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseGraphiteMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseEngineBuilder.cs Adds shared replication configuration helpers.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseCollapsingMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Metadata/​Builders/​ClickHouseAggregatingMergeTreeEngineBuilder.cs Adds replication overloads.
src/​EFCore.ClickHouse/​Infrastructure/​Internal/​ClickHouseOptionsExtension.cs Stores and clones cluster and history options.
src/​EFCore.ClickHouse/​Infrastructure/​Internal/​ClickHouseModelValidator.cs Validates engine compatibility and paired replication arguments.
src/​EFCore.ClickHouse/​Infrastructure/​ClickHouseDbContextOptionsBuilder.cs Exposes cluster and replicated-history options.
src/​EFCore.ClickHouse/​Extensions/​ClickHouseEntityTypeExtensions.cs Adds replication metadata accessors.
RELEASENOTES.md Announces replication and cluster support.
README.md Documents configuration, limitations, and history-table conversion.
CHANGELOG.md Records functionality and constructor API changes.

Review effort: Balanced

Comment on lines +68 to +71
else if (options?.ReplicatedMigrationsHistoryTable == true)
{
// A Replicated database refuses an explicit path and replica name.
engine.WithReplication();

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The shared history configuration lacks an automated two-shard integration test with reused replica names to catch history isolation or replica-name collisions and verify migration continuity across shards.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Test shared history across shards with reused replica names

src/​EFCore.ClickHouse/​Migrations/​Internal/​ClickHouseHistoryRepository.cs:66

Please add an automated two-shard integration test for this shared history configuration, with replica names reused across shards. The current fixture assigns both hosts to shard 01, so it cannot catch regressions that isolate history by shard or cause cross-shard replica-name collisions. Extend the fixture and verify that, after synchronizing history, a host on shard 2 sees migrations applied through shard 1 and can apply the next migration without replaying the first.

1 resolved since last review

Review effort: Balanced

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

alex-clickhouse and others added 5 commits November 25, 2026 15:25
Add WithReplication() and WithReplication(zooKeeperPath, replicaName) to
every MergeTree family engine builder. The migrations SQL generator then
emits the Replicated variant of the engine, with the path and replica
name before the engine arguments.

Add the UseCluster(clusterName) option. It adds ON CLUSTER to the DDL
that migrations, EnsureCreated() and EnsureDeleted() generate, so that
each statement runs on all hosts.

With UseCluster, or with the new UseReplicatedMigrationsHistoryTable()
option for databases with the Replicated engine, the migrations history
table uses ReplicatedMergeTree. All replicas then see the same applied
migrations.

Tests run the DDL and migrations on a cluster with two replicas and
write through one replica and read through the other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under UseCluster, create the history table with the path
/clickhouse/tables/{uuid} and the replica name {shard}-{replica}. The
default path contains {shard}, so each shard had its own history.

Turn off insert deduplication for a replicated history table. Otherwise
ClickHouse drops the history row of a migration that is reverted and
then applied again.

Add ON CLUSTER to ADD CONSTRAINT and DROP CONSTRAINT.

Document that WithReplication() without arguments needs ON CLUSTER or a
Replicated database, that Replicated tables drop duplicate inserts, and
how to convert an existing history table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
End ADD CONSTRAINT and DROP CONSTRAINT with the statement terminator,
as the EF Core base implementations do. A migration script joins the
commands with only a line break.

Document that UseReplicatedMigrationsHistoryTable() gives each shard
its own history: a Replicated database refuses a replicated table that
the shards share, also with database_replicated_allow_replicated_engine_arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EF Core puts only a line break between the commands of a migration
script. The ALTER TABLE, RENAME TABLE, CREATE DATABASE and DROP DATABASE
statements had no terminator, so clickhouse-client read two statements
as one and failed with a syntax error. All statement ends now go through
one helper that appends the terminator.

A new integration test generates the script of migrations that use each
overridden statement and runs it statement by statement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a third host, ch3, as shard 02 of a new cluster two_shards. Its
replica name r1 is also the replica name of ch1 in shard 01. The new
test applies the first migration through shard 01, then checks that
ch3 sees it as applied and applies only the second migration.

A history path with {shard} makes the test fail on the pending
migrations. A replica name without {shard} makes it fail with
REPLICA_ALREADY_EXISTS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alex-clickhouse
alex-clickhouse force-pushed the alex-clickhouse/replicated-mergetree branch from fb02e5e to 4bae37a Compare November 25, 2026 15:27

@security-ai-gate-reviewer security-ai-gate-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Auto-approved by the AI review gate on 4bae37a. Details in the approver's comment on this pull request.

@security-ai-gate-reviewer

Copy link
Copy Markdown

AI review gate — auto-approved

4bae37af2c6f is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.

History (latest 5 heads, newest first)

  • 4bae37af2c6f approved — green: Cursor Bugbot

@alex-clickhouse
alex-clickhouse merged commit 5fd71d5 into main Nov 25, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

request support for ReplicatedMergeTree

2 participants