Skip to content

Allow Distributed and Remote tables in Replicated databases - #108820

Closed
UberDever wants to merge 29 commits into
ClickHouse:masterfrom
UberDever:uberdever/feature/allow-distributed-in-replicated-db
Closed

UberDever wants to merge 29 commits into
ClickHouse:masterfrom
UberDever:uberdever/feature/allow-distributed-in-replicated-db

Conversation

@UberDever

@UberDever UberDever commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

database_replicated_allow_only_replicated_engine prevents creating tables with unreplicated table-owned data on disk in a Replicated database. Before this change, Distributed was also rejected because its optional background INSERT queue makes storesDataOnDisk return true, even though that queue is auxiliary delivery state and the table's actual data belongs to its destination shards.

This change distinguishes table-owned on-disk data from auxiliary state. The restriction applies only to non-ATTACH CREATE queries when database_replicated_allow_only_replicated_engine = 1.

This is deliberately a conservative eligibility check: safe and sound, but not complete.

Let:

  • S be the set of table configurations that are safe under this contract: they do not own unreplicated on-disk table data.
  • A be the set of table configurations admitted by the check.

The required invariant is:

A ⊆ S
∀x: admitted(x) ⇒ safe(x)

Completeness is explicitly not required:

S ⊄ A
¬∀x: safe(x) ⇒ admitted(x)

soundness = 1
completeness < 1

Equivalently, the admitted configurations form a proper subset of the safe configurations: A ⊊ S.

In other words, there must be no unsafe allowances, while conservative false rejections are acceptable. A configuration is allowed only when its storage contract positively establishes eligibility. Discovering another safe but rejected configuration is therefore not a correctness defect and does not require broadening this PR.

Current classification:

Engine or configuration Result Reason
ReplicatedMergeTree family and SharedMergeTree Allow The engine provides a replication or shared-storage contract.
Writable non-replicated MergeTree with a local or remote storage policy Reject It owns unreplicated on-disk table data; a remote disk alone does not establish replication.
Static read-only non-replicated MergeTree Allow It cannot create new table-owned data.
Log, TinyLog, StripeLog, EmbeddedRocksDB, persistent Set and persistent Join Reject They own unreplicated on-disk table data.
Set and Join with persistent = 0 Allow Their contents remain in memory.
Database-managed and explicit-path server File tables Reject Writable variants keep unreplicated table data in files.
Archive-backed File sources Reject conservatively write rejects an archive, but whether the :: syntax denotes an archive depends on allow_archive_path_syntax, and a Replicated database replays on other replicas only the settings changed by the initiating query, not each replica's profile, so the classification can differ across replicas.
Glob-backed File sources Reject conservatively Writability depends on runtime filesystem expansion (is_path_with_globs follows the number of matching files), so it can differ across replicas and change over the life of the table; completeness is not required.
MaterializedPostgreSQL Reject It owns a local nested table.
Distributed, Remote, and RemoteSecure Allow Their optional local queue is auxiliary delivery state rather than data of the table itself.
Memory, Buffer, and Null Allow They do not own on-disk table data.
Merge, Alias, and View Allow They are metadata-only.
Views with inner tables Depends Each generated inner table is created and checked separately.
External-storage engines, data lakes, external databases, and external queues Allow Their data is managed outside ClickHouse-owned table storage.
Lazy StorageTableProxy Reject conservatively The nested storage is unknown without loading it.

ATTACH remains outside the existing gate.

The Distributed background INSERT queue is local to the node accepting an insert and is not replicated. Users requiring acknowledgement only after data reaches the destination shards should set distributed_foreground_insert = 1.

Changelog category (leave one):

  • Improvement

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

Allow Distributed, Remote, RemoteSecure, and non-persistent Set and Join tables in Replicated databases when database_replicated_allow_only_replicated_engine is enabled. Continue rejecting writable non-replicated MergeTree tables using local or remote storage policies, and reject server File tables backed by explicit paths.


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

@EmeraldShift

Copy link
Copy Markdown
Contributor

Hmm, I've been building Distributed tables in Replicated databases for a while now with no problems. The text seems to agree:

...or tables which do not store data on disk are allowed in a Replicated database

What was broken?

@UberDever

UberDever commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Hmm, I've been building Distributed tables in Replicated databases for a while now with no problems. The text seems to agree:

...or tables which do not store data on disk are allowed in a Replicated database

What was broken?

We have this kind of problem on our side

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx :) create table if not exists db2.table1 (n Int32) engine ReplicatedMergeTree order by n

   ┌─shard──┬─replica────────────────────────────┬─status─┬─num_hosts_remaining─┬─num_hosts_active─┐
1. │ shard1 │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx │ OK     │                   1 │                0 │
2. │ shard1 │ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx │ OK     │                   0 │                0 │
   └────────┴────────────────────────────────────┴────────┴─────────────────────┴──────────────────┘

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx :) create table if not exists db2.table2 as db2.table1 engine Distributed('default', db2.table1, n)

Received exception from server (version 25.8.24):
Code: 56. DB::Exception: Received from localhost:9001. DB::Exception: Only tables with a Replicated engine or tables which do not store data on disk are allowed in a Replicated database. (UNKNOWN_STORAGE)

This error is happening on 25.8, but it seems like it is still present on newer versions

@UberDever

Copy link
Copy Markdown
Contributor Author

For history: still reproduces on 26.7 with a simple test

def test_distributed_table_in_replicated_database(start_cluster):
    node.query("DROP DATABASE IF EXISTS db2 SYNC")
    node.query(
        "CREATE DATABASE db2 ENGINE = Replicated('/test/db2', '{shard}', '{replica}')"
    )

    node.query(
        "CREATE TABLE IF NOT EXISTS db2.table1 (n Int32) "
        "ENGINE = ReplicatedMergeTree ORDER BY n"
    )
    
    node.query(
        "CREATE TABLE IF NOT EXISTS db2.table2 AS db2.table1 "
        "ENGINE = Distributed('default', db2.table1, n)",
        settings={"database_replicated_allow_only_replicated_engine": 1},
    )

    assert "table2" in node.query("SHOW TABLES FROM db2")

UberDever and others added 6 commits July 8, 2026 15:59
Pipe each grep through head -n 1 so every rejected clause
contributes exactly one line.
…teQuery.cpp`

The code uses the virtual method `IStorage::hasReplicatedLocalDataStorage`, not the concrete `StorageDistributed` type, so the include is not needed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d3346c3]

Summary: ❌

job_name test_name status info comment
Integration tests (arm_binary, distributed plan, 1/4) FAIL
test_replicated_database_active_node_taken/test.py::test_active_node_owned_by_another_server FAIL cidb
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
timeseries_to_grid_aggregation_functions #3 FAIL dashboard

AI Review

Summary

This PR narrows database_replicated_allow_only_replicated_engine to a concrete "table-owned on-disk data" contract and wires the new hasUnreplicatedTableDataOnDisk predicate through the affected storage classes. I checked the current diff, the current code around each touched storage, and the prior review threads; the remaining behavior matches the updated contract, and the added stateless coverage is focused on the user-visible cases that changed.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit d3346c3.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 43/48 (89.58%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 19, 2026
Comment thread src/Storages/StorageDistributed.h Resolved
alexey-milovidov and others added 3 commits July 26, 2026 17:52
…f the `Replicated` database engine check

The AI review flagged that `IStorage::hasReplicatedLocalDataStorage` returning
`true` for `StorageDistributed` is a factually false statement: the background
`INSERT` queue that a `Distributed` (or `Remote`/`RemoteSecure`) table keeps on
the local disk when `distributed_foreground_insert = 0` is not replicated, so
the predicate no longer matched the contract that `database_replicated_allow_only_replicated_engine`
and its error message advertise.

The queue cannot be ruled out at `CREATE TABLE` time: whether an insert is
spooled locally is decided per query by `distributed_foreground_insert`, and
there is no table-level counterpart in `DistributedSettings`. So instead of
narrowing the implementation, narrow the contract and make every place state
the same thing - the check is about the data *of the table itself*:

* Rename the predicate to `hasUnreplicatedLocalTableData` (inverted sense), so
  that `false` for `StorageDistributed` is the true statement "this table keeps
  no data of its own" rather than a claim about its local files being
  replicated. Update the `StorageProxy`, `StorageTableProxy` and
  `StorageMaterializedPostgreSQL` overrides accordingly.
* Reword the exception thrown by `InterpreterCreateQuery` to talk about
  unreplicated data in local storage and to say why it is refused, and to point
  at the setting that enables the restriction.
* Spell out in the setting's documentation that the `Distributed`/`Remote`
  background `INSERT` queue is a transient send buffer rather than table data,
  that it is local to the node that accepted the `INSERT`, and that
  `distributed_foreground_insert = 1` avoids it.

Extend `02232_allow_only_replicated_engine` with a `Remote` engine case, since
`Remote`/`RemoteSecure` are built on `StorageDistributed` and are admitted for
the same reason.
Comment thread src/Storages/StorageDistributed.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.40% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 32/36 (88.89%) · Uncovered code

Full report · Diff report

@UberDever UberDever changed the title Allow distributed in replicated database Allow unreplicated tables in replicated database Aug 4, 2026
@UberDever UberDever changed the title Allow unreplicated tables in replicated database Allow 'replicated' tables in replicated database Aug 4, 2026
Comment thread src/Core/Settings.cpp Resolved
@UberDever UberDever changed the title Allow 'replicated' tables in replicated database Allow either replicated or non-local disk tables in replicated database Aug 12, 2026
@UberDever UberDever changed the title Allow either replicated or non-local disk tables in replicated database Allow Distributed and Remote tables in Replicated databases Aug 13, 2026
Comment thread src/Storages/IStorage.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d3346c3bfeee066eca98313f930deedc0e3f957b was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

…istent `Set`/`Join`

`Docs check (Mintlify)` failed because
`docs/reference/settings/session-settings/database-replicated.mdx` is an
autogenerated file: the setting description must be changed only in
`src/Core/Settings.cpp`, so the direct edit of the `.mdx` is reverted.

The AI review found two storage shapes that the new
`hasUnreplicatedTableDataOnDisk` predicate misclassified:

* `ENGINE = File(format, path)` sets `is_db_table = false`, so
  `storesDataOnDisk` is `false`, yet such a table keeps its own rows in a
  local unreplicated file exactly like a `File` table inside the database
  directory. `StorageFile` now reports unreplicated on-disk table data for
  everything except a table over a file descriptor, which owns no data.
* `StorageSetOrJoinBase::storesDataOnDisk` is hardcoded to `true`, but with
  `SETTINGS persistent = 0` a `Set` or `Join` table keeps its data only in
  memory, like `Memory`. The predicate now follows `persistent`.

Extended `02232_allow_only_replicated_engine` with the rejected
`File(CSV, path)` case and the allowed non-persistent `Set` and `Join`
cases, and documented both in the setting description.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the AI review verdict and the Docs check (Mintlify) failure in 533e35c6b83b, and merged master (2011aea19a72).

  • Blocker — File(format, path) bypass. Confirmed: StorageFile(FileSource, ...) sets is_db_table = false, so storesDataOnDisk is false even for a server-side table over an explicit path, which nonetheless keeps its own rows in a local unreplicated file. (This bypass predates the PR — the old check was also storesDataOnDisk based — but the new contract should not have it.) StorageFile now overrides hasUnreplicatedTableDataOnDisk and returns true for everything except a table over a file descriptor, which owns no data (and is rejected on the server anyway).
  • Major — persistent = 0 Set/Join. Confirmed: StorageSetOrJoinBase::storesDataOnDisk is hardcoded true, but with SETTINGS persistent = 0 the data lives only in memory, like Memory. The predicate now follows persistent.
  • Tests. 02232_allow_only_replicated_engine now covers the rejected File(CSV, path) case and the allowed non-persistent Set and Join cases. The test passes locally against a build of this branch.
  • Docs check (Mintlify) failed on No direct edits to generated or read-only docs: docs/reference/settings/session-settings/database-replicated.mdx is autogenerated from src/Core/Settings.cpp, so the direct edit of the .mdx is reverted and the setting description (now also covering File and the persistent = 0 variants) lives only in Settings.cpp.
  • Stress test (amd_tsan) failed with Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization, which is the fleet-wide Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (null map size = A, nested column size = B) (STID: 6726-6444) #114368 (closed 2026-08-18 by Do not deserialize a skip index whose on-disk type is stale #112484, merged 2026-08-15). The master merge pulls that fix in, so it should clear on the next run.

Comment thread src/Storages/StorageFile.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
alexey-milovidov and others added 4 commits September 8, 2026 20:20
…ted` database

The AI review reported that `StorageFile::hasUnreplicatedTableDataOnDisk`
over-classifies read-only `File` sources, so `database_replicated_allow_only_replicated_engine`
rejects tables that never own any local data.

Only half of that is actionable. An archive-backed table is read-only
unconditionally - `StorageFile::write` throws `Writing to archives is not
supported` before anything else whenever `archive_info` is set and the table is
not over a file descriptor - and whether the path denotes an archive follows
from the path syntax alone, so the answer is fixed at `CREATE TABLE` time and is
the same on every replica. Such a table owns no data of its own, so it is now
allowed.

Globs are deliberately not treated the same way. `is_path_with_globs` follows
`FileSource::parse`, which sets `with_globs` from the number of files the
pattern matches on the local filesystem right now (`paths.size() > 1`), not from
the presence of glob syntax: `File(CSV, 'input-*.csv')` is writable while the
pattern matches exactly one file, and the classification can differ across
replicas and change over the life of the table. That makes it unusable as an
eligibility contract for replicated DDL. Rejecting a glob-backed read-only table
is a false rejection, which this gate tolerates; accepting a table that turns
out to own local unreplicated data is what it must not do.

Added a positive case for an archive-backed `File` table to
`02232_allow_only_replicated_engine` and documented the variant in the setting
description in `Settings.cpp` (the `.mdx` page is autogenerated from it).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ated` database again

Whether the path of a `File` table denotes an archive depends on `allow_archive_path_syntax`, and a
`Replicated` database applies on other replicas only the settings changed by the initiating query, not each
replica's own profile. So the archive exception was not replica-stable: the initiator could admit the table
while another replica reparses the path as a plain writable file and rejects it. Drop the exception so such a
table is rejected conservatively, like a glob-backed one.

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

Copy link
Copy Markdown
Member

🕵 Superseded by #123493, which keeps all of your commits and merges the current master (it resolves a conflict in StorageFile.cpp). I could not push the merge to this fork branch: it touches .github/workflows, and the push token lacks the workflow scope. Thank you for the contribution, @UberDever!

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-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants