Skip to content

Add Remote and RemoteSecure database engines - #110975

Merged
alexey-milovidov merged 31 commits into
masterfrom
remote-database-engine
Aug 11, 2026
Merged

alexey-milovidov merged 31 commits into
masterfrom
remote-database-engine

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Closes: #59304
Related: #106189

Implement the Remote and RemoteSecure database engines, the ClickHouse-to-ClickHouse counterparts of the MySQL and PostgreSQL database engines.

A Remote database provides real-time access to the tables of a database on a remote ClickHouse server over the native TCP protocol. The list of tables and their structure are fetched from the remote server on demand (via system.tables and DESC TABLE), so the database always reflects the current state of the remote server. Each table is exposed as a Distributed storage over an ad-hoc cluster built from the supplied addresses, which forwards SELECT and INSERT queries to the remote server. RemoteSecure connects over a secure TLS port by default. This is handy for federating several ClickHouse clusters or for plugging a larger cluster into clickhouse-local or a smaller cluster.

CREATE DATABASE r ENGINE = Remote('host:port', 'database', 'user', 'password');

DDL statements against the database are not supported: it is a read-through view of the remote server. The password is masked in SHOW CREATE DATABASE and SHOW CREATE TABLE.

Notes:

  • Following the existing MySQL/PostgreSQL database engines and the maintainer's comment on the issue, a separate Remote table engine is not introduced here: a single-shard Distributed already covers it.
  • As with the remote table function, an address that points to the current server is treated as a local shard, so SELECT/INSERT run directly and the stored credentials are honored only for genuinely remote servers.
  • This is functionally independent of Support Remote and RemoteSecure storage engines #106189 (the Remote/RemoteSecure storage engines): the database engine builds its Distributed storages directly. The per-table SHOW CREATE TABLE prints the Remote(...) table engine, which becomes re-executable once Support Remote and RemoteSecure storage engines #106189 is merged.

Changelog category (leave one):

  • New Feature

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

Added the Remote and RemoteSecure database engines that provide real-time access to the tables of a database on a remote ClickHouse server, forwarding SELECT and INSERT queries to it. They are the ClickHouse-to-ClickHouse counterparts of the MySQL and PostgreSQL database engines.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Implement the `Remote` and `RemoteSecure` database engines, the
ClickHouse-to-ClickHouse counterparts of the `MySQL` and `PostgreSQL`
database engines.

A `Remote` database provides real-time access to the tables of a database
on a remote ClickHouse server over the native TCP protocol. The list of
tables and their structure are fetched from the remote server on demand
(via `system.tables` and `DESC TABLE`), so the database always reflects
the current state of the remote server. Each table is exposed as a
`Distributed` storage over an ad-hoc cluster built from the supplied
addresses, which forwards `SELECT` and `INSERT` queries to the remote
server. `RemoteSecure` connects over a secure TLS port by default.

    CREATE DATABASE r ENGINE = Remote('host:port', 'database', 'user', 'password');

DDL statements against the database are not supported: it is a
read-through view of the remote server. The password is masked in
`SHOW CREATE DATABASE` and `SHOW CREATE TABLE`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 19, 2026, 7:58 AM

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db7a48a]

Summary: ✅


AI Review

Summary

This PR adds the Remote and RemoteSecure database engines and, over the review cycle, tightened the local-shard access checks, replica fallback rules, SHOW TABLES / system.tables behavior, SHOW CREATE TABLE fidelity, and multi-shard write semantics. I re-checked the final PR head against the current code and all existing inline discussion, and I did not find a remaining correctness, safety, or compatibility issue in the touched paths.

Tests
  • ⚠️ I did not find automated coverage for the RemoteSecure-specific secure-port path or for the named-collection SHOW CREATE TABLE / replay branch. The implementations look consistent, but those user-visible branches appear to be covered only indirectly or by manual verification.
Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 80.90% 86.60% +5.70%
Functions 91.30% 91.80% +0.50%
Branches 72.90% 78.80% +5.90%

Changed lines: Changed C/C++ lines covered: 465/534 (87.08%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 19, 2026
Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
alexey-milovidov and others added 2 commits July 19, 2026 20:38
Fix the `arm_tidy` build failure (`misc-unused-alias-decls`): the `fs`
namespace alias and the `<filesystem>` include in `DatabaseRemote.cpp`
were unused.

Address the review on `DatabaseRemote.cpp`:

- `fetchTablesList`: special-case a local shard, enumerating the local
  database under `local_context` instead of opening a self-connection
  with the stored engine credentials. Otherwise `SHOW TABLES` and
  `system.tables` would list local table names according to the
  configured remote user rather than the caller's privileges, matching
  the local-shard special case of `getStructureOfRemoteTable`.

- `getCreateTableQueryImpl`: reuse `getCreateQueryFromStorage` with
  `only_ordinary = false` so that column defaults, aliases and
  materialized expressions inferred from the remote `ClickHouse` table
  are preserved in `SHOW CREATE TABLE`. Emitting only names and types
  changed the insert/read semantics of the recreated `Remote(...)` table.

- `fetchTable`: distinguish a genuinely missing table (return `nullptr`)
  from a transport/authentication failure. On the throwing path (e.g.
  `SHOW CREATE TABLE`) the latter is now propagated instead of being
  reported as `UNKNOWN_TABLE`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a case to `04541_remote_database_engine` that creates a table with
`DEFAULT`, `ALIAS` and `MATERIALIZED` columns and checks that
`SHOW CREATE TABLE` through the `Remote` database preserves those column
specifiers and their expressions.

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

Copy link
Copy Markdown
Member Author

Fixed the arm_tidy failure (unused fs alias in DatabaseRemote.cpp) and addressed the review in commits cd369e5 / 77568d1:

  • Local shard in fetchTablesList: a shard pointing to this server is now special-cased — the local database is enumerated under local_context instead of opening a self-connection with the stored engine credentials, mirroring the local-shard path of getStructureOfRemoteTable. So SHOW TABLES/system.tables no longer list local table names according to the configured remote user.
  • SHOW CREATE TABLE column metadata: getCreateTableQueryImpl now reuses getCreateQueryFromStorage with only_ordinary = false, preserving column DEFAULT/ALIAS/MATERIALIZED specifiers and expressions. Added a regression case to 04541_remote_database_engine.
  • fetchTable error handling: a genuinely missing table returns nullptr (reported as UNKNOWN_TABLE), while a transport/authentication failure is now propagated on the throwing path (e.g. SHOW CREATE TABLE) instead of masquerading as UNKNOWN_TABLE.

The Fast test of the previous commit died with a hung server: a query to a
missing table computed the table-name hints, which enumerate the tables of
every database; for a `Remote` database over a local shard, each table was
resolved through `DatabaseCatalog::getTable`, which on a concurrently dropped
table computed the name hints again, recursing without bound
(04243_table_name_hints_access timed out and the server was reported dead).

- `fetchTable` now infers the structure of a local-shard table with the
  non-throwing `tryGetTable` instead of the `DatabaseCatalog::getTable` call
  inside `getStructureOfRemoteTable`, so it never enters the hint machinery.
- `getAllTableNames` (used by the name hints) is overridden to return just the
  table names instead of inferring the structure of every table through
  `getTablesIterator` (a `DESC TABLE` round trip per table on a remote server).
- A `Remote` database that refers to itself on the same server is now rejected
  with `INFINITE_LOOP` instead of recursing forever.
- The best-effort table listing logs failures at debug level, like the
  best-effort path of `fetchTable`, so a `SHOW TABLES` covering the database is
  not reported as failed by an error-level log entry.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110975&sha=cd369e5be7d90f6cc2f127eda896e76b4749b577&name_0=PR&name_1=Fast%20test
PR: #110975

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

Copy link
Copy Markdown
Member Author

The Fast test failure ("Server died") was a real bug in this PR: 04243_table_name_hints_access timed out because a query to a missing table computed the table-name hints, which enumerate the tables of every database; for a Remote database over a local shard each table was resolved through DatabaseCatalog::getTable, which on a concurrently dropped table computed the name hints again, recursing without bound. The stack traces collected by the test harness show the cycle isTableExist → fetchTable → DatabaseCatalog::getTable → TableNameHints::getAllRegisteredNames → DatabaseRemote::getTablesIterator → fetchTable → ...

Fixed in b56462d:

  • fetchTable infers the structure of a local-shard table with the non-throwing tryGetTable instead of the DatabaseCatalog::getTable call inside getStructureOfRemoteTable, so it never enters the hint machinery.
  • getAllTableNames (used by the name hints) is overridden to return just the names instead of inferring the structure of every table (a DESC TABLE round trip per table on a remote server).
  • A Remote database that refers to itself on the same server is rejected with INFINITE_LOOP instead of recursing forever.
  • The best-effort table listing logs failures at debug level, so a SHOW TABLES covering the database is not reported as failed by an error-level log entry.

Added regression cases to 04541_remote_database_engine (missing table reports UNKNOWN_TABLE; self-referring database is rejected); verified locally that both 04541_remote_database_engine and 04243_table_name_hints_access pass.

Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
…rrors from table resolution

Two fixes to `DatabaseRemote` following review:

- The direct self-reference check in `tryGetLocalDatabase` did not cover longer local cycles
  (`a` -> `b` -> `a`), which recursed without bound through the local-shard path. A thread-local
  set of databases being traversed now rejects re-entry with `INFINITE_LOOP`.
- `tryGetTable` is the ordinary table-resolution path (both `IDatabase::getTable` and the
  analyzer's `DatabaseCatalog::tryGetTable` delegate to it), so it now uses the throwing variant
  of `fetchTable`: a transport/authentication failure while resolving a remote table is reported
  as the real remote error instead of `UNKNOWN_TABLE`, like `DatabaseMySQL::tryGetTable` on a
  connection failure. The listing paths (`getTablesIterator`, `getAllTableNames`,
  `isTableExist`) stay best-effort.

Both cases are covered by new sections of `04541_remote_database_engine`.

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

Copy link
Copy Markdown
Member Author

Addressed the two remaining review threads in 1a1a5cb:

  • Longer local cycles (a → b → a): the pointer-equality check of tryGetLocalDatabase only caught the direct self-reference. A thread-local set of databases being traversed on the local-shard path now rejects re-entry across the whole chain with INFINITE_LOOP, so SHOW TABLES terminates with an empty (best-effort) result and table resolution terminates with the INFINITE_LOOP error instead of recursing forever.
  • Remote failures on ordinary table resolution: tryGetTable now uses the throwing variant of fetchTable (returning nullptr only for a genuinely missing table), because both IDatabase::getTable and the analyzer's DatabaseCatalog::tryGetTable delegate to it. A transport/authentication failure while resolving a remote table is now reported to SELECT/INSERT/etc. as the real remote error rather than UNKNOWN_TABLE — the same behavior as DatabaseMySQL::tryGetTable on a connection failure. The listing paths (getTablesIterator, getAllTableNames, isTableExist) stay best-effort. (A plain getTable override was not enough: the analyzer resolves tables through the catalog's tryGetTable.)

Both cases are covered by new sections of 04541_remote_database_engine, verified locally together with 04243_table_name_hints_access.

The AST fuzzer (amd_debug, targeted) failure (report) is unrelated to this PR: the fuzzed query is EXPLAIN AST optimize = 1 SELECT ... INNER JOIN ... SETTINGS distributed_product_mode = 'local' over the Distributed-with-empty-database tables of 04303_58766_distributed_product_mode_local_default_database, hitting chassert(!part.empty()) in ASTIdentifier on the old-analyzer rewrite path. The fix is already in progress: #110677.

Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
…mote replicas

Two fixes for the `Remote` database engine after review:

- For a shard that points to this server, the ordinary table-resolution
  path validated only `SHOW_COLUMNS` on the underlying local table, but
  the returned `Distributed` proxy could still read and write its data
  directly. `StorageDistributed` gets an opt-in `check_local_shard_access`
  flag (the class is `final`, so no subclassing) that enforces the
  caller's own `SELECT`/`INSERT` rights on `remote_database.remote_table`
  in `read`/`write`/`distributedWrite` when a shard is local, mirroring
  the local-target check of the `remote` table function
  (`TableFunctionRemote::executeImpl`). Covered by the stateless test
  `04613_remote_database_engine_access`.

- The local-shard fast path of `fetchTablesList`/`fetchTableStructure`
  returned early even when the local replica did not have the database or
  the table, hiding tables that exist on the remote replicas of the shard
  (e.g. `Remote('127.0.0.1|other_host', db)`), although the `Distributed`
  read path would fall back to them (`SelectStreamFactory::createForShard`).
  The metadata lookup now falls back to a precomputed cluster of only the
  genuinely remote replicas (a TCP self-connection would resolve local
  metadata under the stored engine credentials rather than the caller's
  own), and the resulting `Distributed` storage uses that cluster as well,
  because a missing local database fails `Context::resolveStorageID` before
  the read-path fallback could engage, and an `INSERT` writes to every
  replica of the shard. Covered by the integration test
  `test_database_remote`, which exercises the fallback and the
  local-replica preference across two nodes.

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

Copy link
Copy Markdown
Member Author

Addressed the two remaining review findings in 9f2af35:

  • Local-shard data-access check (Blocker): StorageDistributed is final, so instead of a subclass it gets an opt-in check_local_shard_access flag, set by the tables of a Remote database. When a shard points to this server, read, write and distributedWrite now enforce the caller's own SELECT/INSERT rights on remote_database.remote_table, mirroring the local-target check of the remote table function (TableFunctionRemote::executeImpl, added there as a security fix). The new stateless test 04613_remote_database_engine_access verifies that a user with SHOW COLUMNS on the underlying table (enough to resolve the proxy) but without SELECT/INSERT is rejected on both paths, and succeeds once the underlying rights are granted.

  • Remote-replica fallback for local shards (Major): the local-shard path of fetchTablesList/fetchTableStructure now returns early only when the local catalog actually has the database/table; otherwise it falls back to a precomputed cluster of only the genuinely remote replicas. A plain fallback over shard_info.pool would not do: the pool includes the local replica as a TCP connection, so the lookup could non-deterministically self-connect under the stored engine credentials and, for a missing local database, "succeed" with an empty system.tables result instead of reaching the other replica. The resulting Distributed proxy is also built over the remote-only cluster in the fallback case, because a missing local database fails Context::resolveStorageID before the read-path fallback of SelectStreamFactory::createForShard could engage, and an INSERT writes to every replica of the shard, so it must not fail on the local one. The new integration test test_database_remote covers both the fallback (Remote('node1|node2', db) with the database only on node2: SHOW TABLES, EXISTS, DESCRIBE, SELECT, INSERT all work through node2) and the local-replica preference when the database exists locally.

Verified locally with two servers on distinct ports (the second port makes the same host a genuinely remote replica): metadata lookup, SELECT and INSERT fall back correctly when the local replica lacks the database, the local replica is still preferred when it has it, and 04541, 04243_table_name_hints_access and the new 04613 all pass.

# Conflicts:
#	src/Storages/StorageDistributed.cpp
Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
…oxy, check local access only when the local replica serves the table

- The remote-replica fallback cluster is now built per shard: only the
  replicas that point to this server are stripped from their shards, and
  every other shard stays intact. If some shard consists of local replicas
  only, no fallback cluster is built at all, because substituting a cluster
  without that shard would silently read and write only a subset of the
  configured shards; a database or table missing on such a local replica is
  reported as missing, like `Distributed` fails when a shard has nothing
  to fall back to.
- `TRUNCATE TABLE` on a table of a `Remote` database is rejected with
  `NOT_IMPLEMENTED`. `InterpreterDropQuery` calls `IStorage::truncate`
  directly, bypassing the database-level DDL guards, and for a
  `StorageDistributed` with no async-insert spool that was a silent no-op
  reported as success. The `check_local_shard_access` constructor flag is
  renamed to `is_remote_database_proxy`, since it now controls both proxy
  behaviors.
- The `SHOW_COLUMNS` check on the underlying local table now runs only
  when the local replica actually serves the table. Previously it ran
  before the fallback decision, so on the remote-replica fallback path a
  caller without grants on never-touched local objects was rejected.

Covered by new sections of 04541 (TRUNCATE), 04613 (resolution rejected
without SHOW_COLUMNS) and two new cases of tests/integration/test_database_remote
(mixed shards with a local-only shard; fallback under a restricted user).

Addresses the AI review at #110975 (comment)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review of the 838d0b6 run in 73461c8:

  • Global fallback replaced with a per-shard one (Blocker): the fallback cluster is now cluster with the local replicas stripped from their shards while every other shard stays intact. If some shard consists of local replicas only (e.g. Remote('node1,node2', db) on node1), there is nothing to fall back to for that shard, and substituting a cluster without it would silently read and write only a subset of the configured shards — so no fallback cluster is built at all, and a database or table missing on such a local replica is reported as missing, the same way Distributed fails rather than skipping a shard.
  • TRUNCATE TABLE is rejected (Blocker): InterpreterDropQuery calls IStorage::truncate directly, bypassing the database-level DDL guards, and for a StorageDistributed with no async-insert spool it was a silent no-op reported as success. The proxy tables of a Remote database now throw NOT_IMPLEMENTED from truncate. The check_local_shard_access constructor flag of StorageDistributed is renamed to is_remote_database_proxy, since it now controls both proxy-specific behaviors.
  • The local SHOW_COLUMNS check runs only when the local replica actually serves the table (Major): previously it ran before the fallback decision, so on the remote-replica fallback path a caller without grants on local objects that are never touched was rejected.

Coverage: new sections of 04541_remote_database_engine (TRUNCATE is rejected and the remote data stays intact) and 04613_remote_database_engine_access (resolution is rejected without SHOW_COLUMNS when the local replica serves the table), and two new cases of tests/integration/test_database_remote (a mixed-shard address expression with a local-only shard reports the table as missing instead of silently querying the other shard; the replica fallback works for a user with rights on the proxy database only). Verified locally with two servers: replica fallback, local-only-shard rejection, restricted-user fallback, and local-replica preference all behave as described; 04541, 04613 and 04243_table_name_hints_access pass.

The two failures of the 838d0b6 run are unrelated to this PR:

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110975&sha=838d0b61235b06939c8acd923ebd396f51cf5b10&name_0=PR&name_1=Stress%20test%20%28amd_debug%29 (a segmentation fault in Aggregator::prepareChunkAndFillWithoutKey, reached from ConvertingAggregatedToChunksTransform::initialize, during the Stress test (amd_debug) run) and provide a fix in a separate PR. If the fix is already in progress, link it here.

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

Copy link
Copy Markdown
Collaborator

Acknowledged — investigating the Aggregator::prepareChunkAndFillWithoutKey segfault reached via ConvertingAggregatedToChunksTransform::initialize. No existing/in-progress fixing PR for this signature (checked CIDB by signature and open PRs), so I'll follow up here with a separate PR (or my findings, if it turns out not to be actionable) shortly.

… list

`SHOW TABLES` uses `getLightweightTablesIterator`, whose default
implementation goes through `getTablesIterator` and keeps only the
tables whose structure could be fetched. For a `Remote` database that
dropped any table whose `DESC TABLE` failed - e.g. a remote user with
`SHOW TABLES` on the database but no `SHOW COLUMNS` on one table, or a
transient `DESC TABLE` failure - even though the remote `system.tables`
query had already returned the name.

Override `getLightweightTablesIterator` in `DatabaseRemote` to build the
result straight from `fetchTablesList`, so `SHOW TABLES` reports the
names the remote server returned without depending on per-table metadata
resolution, matching the existing `getAllTableNames`. Extend
`04613_remote_database_engine_access` to check that `SHOW TABLES` still
lists the table after `SHOW COLUMNS` on the underlying table is revoked.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Databases/DatabaseRemote.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov the fix is up in a separate PR: #111287.

Root cause: finalizing a -State aggregate under a looping combinator (-Resample/-ForEach/-Map) aliases each sub-state pointer into a ColumnAggregateFunction one at a time; if a push_back reallocates and throws MEMORY_LIMIT_EXCEEDED mid-loop, Aggregator::insertAggregatesIntoColumns then runs the throwing function's full destroy() over the sub-states already transferred to the column, which ~ColumnAggregateFunction frees again (double free). The fix reserves the destination before the loop so the aliasing transfer is non-throwing. Reproduced deterministically via groupArrayStateResample (crashes without the fix, graceful memory-limit error with it).

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Investigated. My conclusion differs from the framing in two measurable ways, and I do not think a fix PR is warranted yet.

The #110737 attribution does not hold, in both halves. #110737 is "Let in-progress mutations survive transient Keeper reconnections" (closed). Its diff is 27 files, all MergeTree mutation and Keeper code plus two integration tests, and none of them is 04299 or any Delta Lake path, so it did not introduce the test. The test came in with merged #106115 "Add path validation in delta lake" (e1319006c00f973, 2026-05-29). More importantly, those 16 failures are a different defect wearing the same test name: bucketing by the Reason: line gives 0 timeout rows on #110737. All 16 are result differs with reference (the GOT ACCESS DENIED ERROR line missing on both kernel arms), reported 100% reproducible and explicitly not a randomization issue, across 4 heads x 4 checks. They were stale base: #111483 "Restrict local object access only for user files path" (17f9afed514b, 2026-07-28) is not an ancestor of either failing head, and is an ancestor of f66ba96f412.

The real timeout history is much thinner. Over 90 days the test has 58 failing rows across 3 PRs and 0 on master. Split by reason, the Reason: Timeout! bucket is 31 rows all on a single 2026-05-29 head of #106115 (b1e805978e2, before the path validation was finished) plus exactly one row, yours. Against a median of 4330 passing runs per day over the last 21 full days (range 2224 to 5622), the 600 s hang has occurred once on current code. It is also already OK twice on 97edf248317.

It is a genuine hang, not a slow test losing the shared cap. In that job the test cost 600.04 s while the next slowest of 12319 was 121.40 s, so widening a threshold would be the wrong move regardless.

What I could not do is reproduce it. 380 runs on a debug build (up to 48-way concurrent, including the exact two-invocation shape and shared-cwd variants) all finished, slowest 1.17 s. I checked the probe was not vacuous: it reaches the real containment check (Data lake path ../delta_secret.txt should be inside the table directory) rather than dying earlier at the user_files_path guard, and reproduces the reference byte for byte. No stack survives in the artifacts either: the harness did send SIGTSTP, but lldb was not installed on the runner and no client stack was printed, and the uploaded clickhouse-local.log is a stale window from the previous day with 0 lines for this table.

One structural detail worth recording, since it explains why the hang can only ever be seen on the second read. Arm 1 pipes into grep -q PATH_ACCESS_DENIED, which matches and closes the pipe, so clickhouse-local is SIGPIPEd before it finishes exiting; arm 2 greps for a string that never appears and therefore waits for the process to exit fully (measured: 0.06 s versus 1.04 s on an equivalent pipe). So a wedge anywhere in shutdown is invisible on the first read and fatal on the second. That is a property of the test, not evidence of where the wedge is.

Given one occurrence, no reproduction, no stack, and no tracking issue, a fix PR now would be guesswork. I would rather not guess at a shutdown wedge and ship a change I cannot show fixes anything. What I suggest instead, if you want it: install lldb on the stateless runners, or have the harness fall back to SIGQUIT, so the next occurrence yields a stack. I am happy to do that as a separate PR, or to author the fix as soon as one occurrence gives a stack. Tell me which you prefer.

…SHOW CREATE TABLE

Address two AI review findings on the implicit sharding key of multi-shard
Remote databases (introduced in 97edf24):

- The implicit rand() key made the read path of StorageDistributed treat the
  proxy as a table with a sharding key: with
  force_optimize_skip_unused_shards = 1 (the "has sharding key" mode), a
  SELECT from a multi-shard Remote database threw
  UNABLE_TO_SKIP_UNUSED_SHARDS instead of reading all shards as before. The
  new hasShardingKeyForReads makes shard pruning and the distributed
  group-by optimization behave as if such a proxy has no sharding key,
  exactly like a Distributed table declared without one.

- SHOW CREATE TABLE did not serialize the implicit key, so the emitted
  Remote(...) table definition recreated a table that rejects a multi-shard
  INSERT (STORAGE_REQUIRES_PARAMETER). The key is now appended to the
  emitted engine arguments (positional form, the named-collection form via
  sharding_key = rand(), and the rebuilt fallback-addresses form).

New test 04813_remote_database_engine_multi_shard_sharding_key covers both:
reads under force_optimize_skip_unused_shards = 1 and = 2, the serialized
key, and a round trip that recreates the emitted definition and inserts
through it.

#110975

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

Copy link
Copy Markdown
Member Author

🕵 Addressed both Majors of the 08-05 AI review in 7bad59a:

  • Read path (DatabaseRemote.cpp:535): the implicit rand() sharding key of a multi-shard proxy is now write-only. StorageDistributed::hasShardingKeyForReads makes shard pruning (optimize_skip_unused_shards / force_optimize_skip_unused_shards) and the distributed group-by optimization behave as if the proxy has no sharding key, restoring the pre-97edf248 read behavior.
  • SHOW CREATE TABLE (DatabaseRemote.cpp:803): the implicit key is now serialized into the emitted Remote(...) definition (trailing rand() in the positional and fallback-addresses forms, sharding_key = rand() in the named-collection form), so a recreated table accepts a multi-shard INSERT.

New stateless test 04813_remote_database_engine_multi_shard_sharding_key covers reads under force_optimize_skip_unused_shards = 1 and = 2, the serialized key, and the emitted-definition round trip (recreate + INSERT). Locally verified together with 04541, 04613, 04653, and 04243 — all match their references; single-shard SHOW CREATE output is unchanged.

The three reds on the 97edf248317 run are unrelated to this PR:

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

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

Investigated. The fix is already in progress: PR 112644 ("Do not read-and-discard the archive prefix when reading a packed part member"), mine, open since 2026-07-30. It is not in the build that failed here, so this occurrence is expected.

Presence probe at 97edf248: src/IO/PackedFilesReader.cpp is byte-identical at that sha and at current master (3936 bytes, min_bytes_for_seek count 0 in both), and 4 on refs/pull/112644/head (control: patchSettings occurs twice in all three).

What the artifact says

I read hung_check.log for that job rather than the CI database row (for this family the stored context is truncated: over 60 days, only 9 of 2638 Hung check failed rows still carry the Found hung queries in processlist section).

Two hung rows, both is_cancelled = 1, elapsed 410.47 s and 410.40 s. Row 1 is the carrier; Row 2 is a victim of it, blocked in future::get inside MergeTreeMarksLoader::loadMarks waiting for the same marks future.

Row 1 has 54 stacks. 50 of 54 carry the identical lower stack, and none is truncated (max 39 frames against FRAMEPOINTER_CAPACITY = 45 in src/Common/FramePointers.h:8, and all 54 end in thread_start):

MergeTreeMarksLoader::loadMarksImpl
  CompressedReadBufferFromFile::nextImpl
    ReadBufferFromFileView::nextImpl
      ReadBufferFromEncryptedFile::performSeekAndSetReadUntilPosition
        ReadBufferFromRemoteFSGather::seek
          ReadBuffer::ignore          <- reads and discards
            ReadBufferFromRemoteFSGather::nextImpl
              CachedOnDiskReadBufferFromFile::nextImplStep

Your negative claim is correct, verified with a positive control. By grep -ac <name> hung_check.log: DatabaseRemote, DatabaseRemoteSecure, StorageRemote, TableFunctionRemote and RemoteQueryExecutor each match 0 lines in the whole file, while MergeTreeMarksLoader matches 154 and ReadBufferFromEncryptedFile 150. This is not caused by 110975.

Mechanism

ReadBufferFromFileView is only ever constructed from the two packed-part paths (src/IO/PackedFilesReader.cpp:125 and src/Storages/MergeTree/DataPartStorageOnDiskPacked.cpp:346), so the marks being read live inside a data.packed archive.

MergeTreeMarksLoader.cpp:179 sizes the read buffer for the marks member alone via adjustBufferSize(file_size), which clamps only buffer_size (src/IO/ReadSettings.cpp:44). The seek threshold is untouched and still describes the whole session: remote_read_min_bytes_for_seek defaults to 4 * DBMS_DEFAULT_BUFFER_SIZE = 4 MiB (src/Core/Settings.cpp:6777, src/Core/Defines.h:22), and it was not randomized in this run.

So when the archive prefix ahead of the member is skipped, ReadBufferFromRemoteFSGather::seek judges diff < min_bytes_for_seek at src/Disks/IO/ReadBufferFromRemoteFSGather.cpp:251 and takes ignore(diff) at :253 instead of seeking, transferring the whole prefix through the member-sized buffer.

The ProfileEvents of Row 1 quantify it: 35773097 bytes fetched from S3 to obtain 208 bytes of marks (LoadedMarksMemoryBytes: 208, LoadedMarksCount: 4, ReadBufferFromS3Bytes: 35773097), across CachedReadBufferReadFromCacheMisses: 707650 cached-read steps, i.e. 50.6 bytes moved per step.

Why it reaches 410 s here rather than being merely slow

The stress build rewrites the logger level from trace to test (tests/docker_scripts/stress_runner.sh:271), and the cached read path emits 3 LOG_TEST per step (LogTest: 2123599 against 707650 steps = 3.0009). One of them, src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp:1800, formats getInfoForLog on every read.

That is where the 50 threads actually are: 48 of the 50 are inside the logger, 45 of them sampled on __lll_lock_wait under the shared OwnSplitChannel / Poco FileChannel mutex. LoggerElapsedNanoseconds: 19537198222015 is 19537 s of logger time across 54 threads, about 362 s per thread, against 410 s elapsed. Aggregate CPU is UserTimeMicroseconds + SystemTimeMicroseconds = 0.34 s, 1.4 percent of the 23.9 s aggregate RealTimeMicroseconds, so nothing is spinning and nothing is deadlocked: 50 marks-loader pool threads each move a multi-MB prefix 50 bytes at a time while contending for one logger mutex.

is_cancelled = 1 is a consequence, not the cause. There is no interruption point inside ignore, so cancellation cannot land until the transfer completes.

PR 112644 clamps the seek threshold down to the already-clamped buffer size in PackedFilesReader::patchSettings (src/IO/PackedFilesReader.cpp:99), so the prefix is seeked over. Both packed constructors above route through that function. Measured on an uncached encrypted disk in that PR: the same marks member goes from 9 requests moving 3049387 bytes to 12 requests moving 27522 bytes.

Breadth for the exact signature, 60 days: 1 row, this one. ReadBufferFromFileView appears in 15 rows over 9 PRs and 0 master runs, but only this row is the hung check; the rest are Build (arm_tidy) diagnostics and unrelated stateless failures. It needs a packed part on an encrypted remote disk with remote_filesystem_read_method = 'read' and load_marks_asynchronously = 1, which is why it is rare.

On the darwin item

One correction, since you noted no tracking issue: that family does have a merged fix, 4bb7efd8f26d from PR 112267 by Algunenano, "Work around Darwin pthread_rwlock losing wakeups under signals", merged 2026-07-30, closing 111579. It is present in this build (4bb7efd8f26d is an ancestor of 97edf248, behind_by 0), so Server died here is a residual rather than the case that PR closed. Alongside it that job records test timeouts rather than segfaults (02015_executable_user_defined_functions and 03312_squashing_with_low_card_mem_usage, both Reason: Timeout!), and its own summary line reads Failed: 6, Passed: 5204, Skipped: 1345. That is the hang shape rather than the profiler segfault 111579 covered. No action needed from you on 110975 for it.

…is unavailable

When the local shard of a `Remote` database is itself another `Remote`
database whose own target is down, the `NetException` from the inner
proxy propagated out of `fetchTablesList` / `fetchTableStructure`
instead of engaging the same-shard remote-replica fallback, so
`SHOW TABLES`, `EXISTS TABLE`, `DESCRIBE`, `SHOW CREATE TABLE` and
`SELECT` on `outer = Remote('node1|node2', 'inner')` failed even though
the replica of `outer` on node2 was healthy and could answer. Treat the
inner-proxy failure like an unavailable local replica: catch the
`NetException` and fall through to `remote_only_cluster` when the local
database is a nested `Remote` proxy and a fallback cluster exists;
rethrow otherwise, so a database without remote replicas still surfaces
the real error, and non-nested local databases keep the old behavior.

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

Copy link
Copy Markdown
Member Author

🕵 Addressed the AI review Major in db7a48a: when the local shard of the outer Remote database is itself a nested Remote database whose own target is down, the failure is now treated like an unavailable local replica — fetchTablesList and fetchTableStructure catch the NetException and fall back to the same-shard remote replicas (remote_only_cluster) instead of failing the whole database. Without a fallback cluster, or when the local database is not a nested Remote proxy, the error still propagates as before. Added integration test test_unavailable_nested_remote_database_falls_back_to_a_healthy_replica and a sentence in remote.md.

The only CI red on the previous run, AST fuzzer (amd_debug) — Cannot serialize FutureSetFromSubquery with no query plan over merge() + GLOBAL NOT IN — is unrelated to this PR and already tracked: issue #112848, fix in progress #112849.

@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db7a48ae0 with master a96691076 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 16bd8e494; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 689.52 MiB 687.22 MiB -2.30 MiB (-0.33%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

6 object files changed (+494.88 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseRemote.cpp.o new 492.16 KiB +492.16 KiB

737 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

25 translation units recompiled, 178 s compile time in total, 24 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Databases/DatabaseRemote.cpp: 7.1 s

Job report

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 6f6f163 Aug 11, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the remote-database-engine branch August 11, 2026 00:08
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
alexey-milovidov pushed a commit that referenced this pull request Aug 11, 2026
Build (arm_tidy) is red on master:

  src/Databases/DatabaseRemote.cpp:1058:26: error: use 'contains' to check
  for membership [readability-container-contains,-warnings-as-errors]

clang-tidy runs as warnings-as-errors there, so the single diagnostic aborts
the build and every PR that merges master inherits the red.

The line is not an authoring mistake. readability-container-contains under
clang-tidy-21 flags the find(...) != end() container form but not
std::string::find(char) != npos; clang-tidy-22 flags both. The compiler bump
landed in #108400 at 2026-08-10 17:33 UTC and the branch carrying this line
merged at ~00:15 UTC, so the TU entered master's tidy build already diagnosed
by a checker that had not diagnosed it during the branch's own 12 green runs.

String is std::string and the project builds at C++23, so contains is
available and exactly equivalent. Verified by asserting
(s.find(':') != npos) == s.contains(':'), and the full guard including
!starts_with('['), over 13 inputs covering empty, ":", "::", leading and
trailing ':', bare and bracketed IPv6, non-IPv6 hosts and an embedded NUL.
No behaviour change.

The last green master commit already contained the clang-22 bump, so any
other new violation of this check must lie in the green-to-red range. Sweeping
that range's added lines for all three forms the check recognises yields
exactly this one line.

Related: #110975
@groeneai

Copy link
Copy Markdown
Collaborator

Fix: #119345.

Root cause is a lost wakeup in TableSnapshot::Iterator, on the default allow_delta_kernel_rs path. next() waits on an untimed data_files_cv.wait(lock, pred) while holding next_mutex. Normal completion sets iterator_finished under that mutex, but setScanException() and ~Iterator() publish shutdown without it, and wait's re-check does not close that hole: the unprotected window is inside wait, between its last predicate call and the atomic register-and-unlock. A scan thread that throws there finds no registered waiter, the notification is dropped, and the scan loop then exits while (!shutdown.load()) without setting iterator_finished and without a second notify. Nothing can satisfy the predicate again, so the read waits forever and the stored exception is never rethrown, which is why no error reached stderr. The artifact agrees: the consumer polling in LazyOutputFormat::getChunk, three untimed futex waits, and no TableSnapshot thread left in the dump.

To be explicit about what is and is not proven: I reproduce the lost wakeup deterministically with a failpoint and fix it, but I could not reproduce the f66ba96f412 occurrence itself, so I do not claim it is proven to be that one.

The diagnostics tooling I asked about on 2026-08-05 turned out to be unnecessary, so that question is moot: an earlier occurrence of the same signature (2026-08-23, on #115547) carries a full thread backtrace all in the CI database.

One thing worth knowing if this test is triaged again: the 600 s stall still recurs, and it is reported green. The 2026-08-23 and 2026-09-10 occurrences are OK rows at 600,060 ms and 600,040 ms, because the coverage stateless job force-sets OK once the diagnostics rerun passes. Under a FAIL/ERROR filter the test therefore looks fixed when it is not.

This branch was successfully deployed

1 active deployment
staging - docs — db7a48ae Deployed Aug 7, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Remote database engine

4 participants