Skip to content

Allow Distributed and Remote tables in Replicated databases - #123493

Merged
alexey-milovidov merged 46 commits into
masterfrom
continue-pr-108820-distributed-in-replicated-db
Oct 19, 2026
Merged

alexey-milovidov merged 46 commits into
masterfrom
continue-pr-108820-distributed-in-replicated-db

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

This supersedes #108820 by @UberDever (all original commits are preserved), with master merged in. The update could not be pushed to the fork branch because the merge touches .github/workflows and the push token lacks the workflow scope.

Related: #108820

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; the check runs before the storage is constructed, because the constructor starts replication.
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.
CREATE TABLE ... AS file(...) (lazy table function proxy or direct StorageFile) Reject The table function reports the classification without being executed; file over a path creates a local StorageFile. Other table functions create storages that do not own on-disk table data.
CREATE TABLE ... AS url(...) with a relative URL Reject conservatively url_base is not persisted in the definition, so the backend the URL resolves to (e.g. file:// or https://) can differ across replicas and after a restart.

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.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.251-master (included in 26.11 and later)

UberDever and others added 30 commits June 29, 2026 18:27
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]>
…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.
…buted-in-replicated-db' into uberdever/feature/allow-distributed-in-replicated-db
…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.
…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]>
# Conflicts:
#	src/Storages/StorageFile.cpp
alexey-milovidov and others added 2 commits October 8, 2026 03:50
…o its scheme delegate

`CREATE TABLE ... AS url('file://...', 'CSV')` with an inferred structure creates a lazy
`StorageTableFunctionProxy` classified by the outer `url` table function, which did not
forward `hasUnreplicatedTableDataOnDisk` to its `file` delegate. This let the table into a
`Replicated` database with `database_replicated_allow_only_replicated_engine = 1`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/TableFunctions/TableFunctionURL.cpp Resolved
alexey-milovidov and others added 4 commits October 8, 2026 17:35
…n `Replicated` databases

The constructor of `StorageMaterializedPostgreSQL` starts replication, which creates
the publication and the replication slot in PostgreSQL and the nested table. The
`database_replicated_allow_only_replicated_engine` check in `InterpreterCreateQuery`
runs after the storage is constructed and does not roll that back, so check it in
the storage factory before construction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…` conservatively

`url_base` is not persisted in the definition of `CREATE TABLE ... AS url(...)`, so
a relative URL can resolve to a different backend (e.g. `file://` vs `https://`) on
another replica of a `Replicated` database or after a restart. Classify such a table
function as possibly owning unreplicated data on disk.

The table function is now classified in `InterpreterCreateQuery` before it is executed:
with a static structure it returns the final storage directly (e.g. `StorageURL`),
which does not know whether its URL was relative.

`StorageURL::isAbsoluteURL` is extracted from `StorageURL::resolveURLBase`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n replica-side DDL replay too

The factory-side check only ran for `LoadingStrictnessLevel::CREATE`, but other
replicas of a `Replicated` database replay the query with `SECONDARY_CREATE`, so they
still constructed the storage (starting replication) before the interpreter rejected it.
Use the same condition as the interpreter (`!create.attach`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 10, 2026 12:29
…able function structure

For `CREATE TABLE ... AS f(...)` without a column list, the structure is inferred
in `getTablePropertiesAndNormalizeCreateQuery` before `doCreateTable` runs the
`database_replicated_allow_only_replicated_engine` check, so a definition that
the policy rejects still opened the source and could fail with a file or access
error instead of the deterministic exception. Apply the same veto right before
the inference, and share the condition and the exception between both places.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
awitten1 pushed a commit to awitten1/ClickHouse that referenced this pull request Oct 10, 2026
`test_memory_limit/test.py::test_multiple_queries` fills a 4 GB container
with 30 unbounded `SELECT * FROM system.numbers GROUP BY number` queries
(15 concurrent), so its run time is the number of rows needed to reach the
server limit times the per-row cost. On the coverage build the per-row cost
is very high: in the failing job of ClickHouse#123493 the first wave of 15 queries
needed 216 s to reach the 3.60 GiB limit, while the whole test takes about
50 s on a release build.

ClickHouse#108862 switched this query to a `HashSet` (8 bytes per key instead of 16),
so each query now inserts about twice as many rows before it is stopped.
On master coverage runs the test went from 240 s at 581c15c to 424 s
at the ClickHouse#108862 merge, and the weekly median is now about 570 s with a
maximum of 909 s, against the 900 s pytest timeout. It timed out 5 times
in 60 days, always on coverage shards.

Modules in `LLVM_COVERAGE_SKIP_PREFIXES` run in
`Integration tests (amd_binary_excluded_from_llvm)` instead, so the test
keeps running unchanged on a regular binary (and on arm_binary and
amd_cfi). The trailing slash keeps `test_memory_limit_observer/` in the
coverage shards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 11, 2026 12:28
…a `File` table

`CREATE TABLE ... ENGINE = File(...)` and `ENGINE = URL('file://...')` without a column list
infer the schema while the storage is constructed, so the post-construction
`hasUnreplicatedTableDataOnDisk` check came too late: a missing file was reported as a schema
inference error instead of the `database_replicated_allow_only_replicated_engine` rejection.

Move the check for `File` into its storage creator, before the path is resolved. The `URL`
engine creates its `file://` delegate with the same creator, so it is covered too. The check is
factored out into `throwIfUnreplicatedTableDataNotAllowed`, which `MaterializedPostgreSQL`
now reuses.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123493&sha=f7e21683d2df5972b637945b4fa515fd90a1ef26&name_0=PR&name_1=Stateless%20tests%20(arm_asan_ubsan%2C%20azure%2C%20sequential) (the whole job hit its 9000 s timeout with no failing test; the same job also fails on master without a named test) and provide a fix in a separate PR. If the fix is already in progress, link it here. The other failure, 05317_local_read_throttler_filesystem_cache under ParallelReplicas, is fixed on master by #124920, which is now merged into this branch.

@groeneai

Copy link
Copy Markdown
Collaborator

This is the 9000 s job limit that #123849 (splitting the job into 2 batches) fixes. On f7e2168 all 1180 tests finished (1082 passed, 98 skipped, 0 failed) after 8652 s of test time, and the job was killed 6 s after the last test, during log export.

That run's workflow started at 12:44 UTC, before #125003, #125008 and #125009 were merged (2026-10-10 15:35 UTC). They cut the median test time of this job on master from 8177 s to 7647 s, and master has not timed out since, so the new head 3f81e89 (which merges master) should fit. #123849 is still needed for real headroom; it conflicts with master in the generated workflow files, and @ Algunenano merges it himself.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai. Confirmed: on the new head 3f81e89 (which merges master), Stateless tests (arm_asan_ubsan, azure, sequential) and every other completed check passed (0 failed tests). The job timeout is covered by #123849 and is unrelated to this PR. Only CH Inc sync and Fast test (arm_darwin) (queued) are still pending.

alexey-milovidov and others added 2 commits October 16, 2026 03:44
# Conflicts:
#	src/Interpreters/InterpreterCreateQuery.cpp
In the private CI (`CH Inc sync`), `ReplicatedMergeTree` is replaced with
`SharedMergeTree`, so `CREATE TABLE ... ENGINE = ReplicatedMergeTree` by the
test user fails with `ACCESS_DENIED`: it needs `TABLE ENGINE ON SharedMergeTree`,
which cannot be granted in builds without that engine. The test is already in the
private no-cloud list; it only ran there because this PR changes it.

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

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve the conflict in src/Interpreters/InterpreterCreateQuery.cpp. Both sides had only added new helper functions, so I kept both. The CH Inc sync failure came from this PR's own test: in the private CI, ReplicatedMergeTree is replaced with SharedMergeTree, so the test user's CREATE TABLE ... ENGINE = ReplicatedMergeTree failed with ACCESS_DENIED because the user has no TABLE ENGINE ON SharedMergeTree grant. Private master already skips this test, and it ran here only because this PR changes it. I added the no-shared-merge-tree tag in 8dd33fa. The other two sync failures, 05318_file_log_one_bad_file (max_rows_to_read on system.text_log) and 05359_parquet_file_logical_type (MD5 in FIPS mode), are unrelated to this PR.

@alexey-milovidov

alexey-milovidov commented Oct 17, 2026 •

Copy link
Copy Markdown
Member Author

🕵 All public CI checks pass on 8dd33fa. Only CH Inc sync failed (build failed). The private run on the private sync PR had these failures:

  • Build (amd_msan): MSan builds were also failing on private master at that time.
  • Integration tests (amd_tsan, 2/8): the runner could not pre-pull Docker images (infra).
  • Three stateless jobs, each with one failed test. The previous private failure, the ACCESS_DENIED in 02232_allow_only_replicated_engine, was fixed in 8dd33fa. No private test config enables database_replicated_allow_only_replicated_engine. The only private test that sets it creates SharedMergeTree tables, which the new check still allows (supportsReplication).

These check runs cannot be rerun individually, so I merged the latest private master into sync-upstream/pr/123493 (clean merge, no code changes) to retrigger the private CI.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Looks good. This is conservative. Next we will allow MergeTree tables over shared storage and File tables when user_files is mapped to a shared bucket.

@alexey-milovidov alexey-milovidov self-assigned this Oct 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 19, 2026
Merged via the queue into master with commit 524a0c2 Oct 19, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the continue-pr-108820-distributed-in-replicated-db branch October 19, 2026 23:20
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-improvement Pull request with some product improvements 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