Skip to content

Log tolerated connection failures to remote MySQL/PostgreSQL databases as warnings instead of errors - #109472

Merged
kssenii merged 18 commits into
masterfrom
fix-remote-db-unreachable-log-level
Aug 20, 2026
Merged

kssenii merged 18 commits into
masterfrom
fix-remote-db-unreachable-log-level

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Fix CI upgrade test failure:
Example failing report — Upgrade check (amd_release) on the unrelated PR #108255: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108255&sha=28ca539bd4bf66de37e388238de45d840bc30c52&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (Error message in clickhouse-server.log (see upgrade_error_messages.txt) with the getTablesIterator line above; the report shows green now because the check passed on a later rerun — which is exactly the flaky-victim pattern).

Problem. A DatabasePostgreSQL or DatabaseMySQL pointed at an unreachable server writes the connection failure to the server log at <Error> level on code paths that explicitly tolerate and retry the failure. A temporarily unavailable remote server is a normal operational state on these paths, yet it floods the log with error-level messages. Concretely:

  • every system.tables / system.columns scan that touches the database logs an error (DatabasePostgreSQL::getTablesIterator: Code: 614. DB::Exception: ... Connection to ... failed);
  • the background cleaner logs one more error every rescheduling cycle;
  • ATTACH DATABASE ... ENGINE = MySQL(...) logs three error lines for a single tolerated probe failure.

This also trips the Upgrade check (which fails on any unexpected error message in clickhouse-server.log) on unrelated PRs: the stateless test 04210_show_remote_databases_in_system_tables (added in #104416) leaves PostgreSQL/MySQL databases pointed at the unroutable 192.0.2.1 during the check's restart window, and since #109082 made remote databases visible to system.tables scans by default, the check failed on 137 distinct PRs in 14 days, and 0 times on master.

Root cause. Seven log sites report a caught-and-tolerated (or caught-and-propagated) connection failure at error level: the catches in DatabasePostgreSQL::getTablesIterator (kept non-throwing so system.tables scans do not fail) and DatabasePostgreSQL::removeOutdatedTables (the cleaner reschedules and continues) use tryLogCurrentException with the default LogsLevel::error; the same for the DatabaseMySQL constructor catch on ATTACH and DatabaseMySQL::getCreateTableQueryImpl with throw_on_error = false; and the connection-pool layers (mysqlxx::Pool::allocConnection, mysqlxx::PoolWithFailover::get, postgres::PoolWithFailover::get) log at error level before propagating the exception to the caller — who is the one deciding how severe the failure actually is.

Fix. Downgrade those seven sites to warning. Exception propagation is unchanged everywhere: a non-tolerated failure (e.g. CREATE DATABASE with an unreachable host) still reaches the client as an error through the normal query-error path.

The new test 04506_remote_database_unreachable_no_error_log attaches PostgreSQL and MySQL databases pointing at an unreachable host, exercises the tolerated paths (attach probe, system.tables scan, background cleaner), and asserts through system.text_log that each path produced a warning (proving the failure path fired) and no error-level lines at all for the corresponding queries.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

A `DatabasePostgreSQL`/`DatabaseMySQL` pointed at an unreachable server
logged the connection failure at error level on code paths that
explicitly tolerate and retry it:

- `DatabasePostgreSQL::getTablesIterator` — its catch exists so that
  `system.tables` scans do not fail on a postgres error
- `DatabasePostgreSQL::removeOutdatedTables` — the background cleaner
  catches, reschedules and continues
- `DatabaseMySQL` constructor — the connection probe failure is
  explicitly tolerated on `ATTACH`
- `DatabaseMySQL::getCreateTableQueryImpl` with `throw_on_error = false`
- `mysqlxx::Pool::allocConnection`, `mysqlxx::PoolWithFailover::get` and
  `postgres::PoolWithFailover::get` — they log before propagating the
  exception to the caller, who decides the severity

The Upgrade check fails on any unexpected error message in the server
log, so the leftover unreachable-host databases created by test
`04210_show_remote_databases_in_system_tables` (added in #104416, made
reachable by `system.tables` scans by default in #109082) tripped the
check on 137 unrelated PRs in 14 days (0 on master).

The new test attaches PostgreSQL and MySQL databases pointing at an
unreachable host, exercises the tolerated paths, and asserts through
`system.text_log` that they produce warnings but no error-level lines.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bbf97ae]

Summary: ✅


AI Review

Summary

This PR demotes tolerated remote MySQL/PostgreSQL connection failures from Error to Warning on the attach / metadata / reconnect paths that were tripping the Upgrade check, and the PostgreSQL side now does a reasonable transient-vs-permanent split with focused regression coverage. I do not think the MySQL side is fully there yet: some permanent connection misconfigurations still get downgraded to Warning, so the operational contract is still incomplete.

Findings

⚠️ Majors

  • [src/Common/mysqlxx/Pool.cpp:411-420] [dismissed by author -- https://github.com/Log tolerated connection failures to remote MySQL/PostgreSQL databases as warnings instead of errors #109472#discussion_r3528314252] Only the three server-side ER_ACCESS_DENIED_ERROR / ER_DBACCESS_DENIED_ERROR / ER_BAD_DB_ERROR cases are kept at Error here. Every other mysqlxx::ConnectionFailed still goes down the warning path, and the tolerated catches in DatabaseMySQL reuse that classification for ATTACH and getCreateTableQueryImpl(..., throw_on_error = false). That means a permanently broken attached MySQL database whose connect failure is not one of those three codes will still leave only Warning lines in the server log, even though the PostgreSQL side of this PR now preserves Error visibility for equivalent permanent setup failures.
    Suggested fix: extend the MySQL permanent-failure classification beyond those three ER_* codes, or invert the logic to an allowlist of genuinely transient connect failures and keep everything else at Error.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: keep permanent MySQL connect misconfigurations at Error, not just the three currently special-cased server-side ER_* codes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 113/121 (93.39%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 6, 2026
@kssenii kssenii self-assigned this Jul 6, 2026
Comment thread src/Common/mysqlxx/Pool.cpp Outdated
LOG_ERROR(log, "Failed to connect to MySQL ({}): {}", description, e.what());
/// The error is either rethrown or reported to the caller via nullptr, and the caller
/// decides how severe the failure is, so do not log it at error level here.
LOG_WARNING(log, "Failed to connect to MySQL ({}): {}", description, e.what());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Probably LOG_TRACE is also ok here, I've seen in other places that retriable erros are logged as such, but its up to you.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept it at warning to stay consistent with the other two pool-layer sites downgraded in this PR (mysqlxx::PoolWithFailover::get, postgres::PoolWithFailover::get) and to keep the failure visible at default log levels; the new test also pins each site at warning.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept it at Warning so operators still see the tolerated failure on the default warning stream; happy to drop to Trace if you'd rather it stay out of the log entirely.

The engine-layer catch sites already explain the tolerance in adjacent
comments and code structure; keep a single terse note at the pool-layer
sites where the reason for the warning level is not obvious.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-ci and removed pr-improvement Pull request with some product improvements labels Jul 6, 2026
Comment thread src/Common/mysqlxx/Pool.cpp Outdated
{
LOG_ERROR(log, "Failed to connect to MySQL ({}): {}", description, e.what());
/// The failure is propagated to the caller, who decides how severe it is.
LOG_WARNING(log, "Failed to connect to MySQL ({}): {}", description, e.what());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Downgrading this site to Warning also demotes permanent MySQL misconfiguration, not just the transient "host unreachable" case the PR is targeting. The branch immediately below still treats ER_ACCESS_DENIED_ERROR, ER_DBACCESS_DENIED_ERROR, and ER_BAD_DB_ERROR as non-retriable and rethrows them. On ATTACH / metadata load, DatabaseMySQL catches that exception with attach = true and now logs only Warning, so a broken attached database with bad credentials or a missing remote DB no longer leaves any Error-level record in the server log. Please keep Error for those errnums and only downgrade the transport failures that are actually tolerated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — allocConnection now keeps error level for ER_ACCESS_DENIED_ERROR/ER_DBACCESS_DENIED_ERROR/ER_BAD_DB_ERROR (reusing the classification of the rethrow branch below) and logs warning only for transport failures; test 04506 still passes since connection-refused is a transport error. (commit 3b79e5d)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The current branch still logs some permanent MySQL setup failures at Warning here. In src/Common/mysqlxx/Pool.cpp:406-416 only the three server-side ER_* codes keep Error, so client-side permanent misconfigurations from mysql_real_connect (for example a typoed host or an invalid socket path) still take the LOG_WARNING branch. On the ATTACH / metadata-load paths the higher layers were also downgraded to Warning, so those broken attached databases again have no Error-level record in the server log. This still needs a permanent-vs-transient split for the client-side connect failures too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The deny-list keeps the common permanent misconfigs (access-denied, dbaccess-denied, bad-db) at Error; other permanent MySQL failures (SSL, host-blocked) staying at Warning is an accepted gap, tracked as a small follow-up to extend the deny-list.

Per review: downgrading every connection failure in
mysqlxx::Pool::allocConnection to warning also demoted permanent
misconfiguration. The catch below already treats ER_ACCESS_DENIED_ERROR,
ER_DBACCESS_DENIED_ERROR and ER_BAD_DB_ERROR as non-retriable; on ATTACH
the caller tolerates the exception, so without an error-level record here
a broken attached database with bad credentials or a missing remote
database would leave no error in the server log. Keep error for those
errnums and downgrade only transport failures.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ent -> Error

`pqxx::broken_connection` carries no error code (only libpq's localized message,
and the connection is already finished when it is thrown), so the PostgreSQL
pool cannot distinguish transient transport failures from permanent
misconfiguration the way the MySQL pool does via `errnum()`. It previously
logged every such failure at Warning, which silences a permanently-broken
attached database (bad credentials, missing database) from any Error-level log.

Add `isTransientConnectionError`, which matches the known transient transport
messages (connection refused, timeout, host/network unreachable, connection
reset, DNS temporary failure) and defaults everything else - including a
server-side `FATAL:` rejection or an unrecognized message - to non-transient, so
an unclassifiable failure fails loud (Error) instead of being silently
downgraded. Both the foreground `get()` and the background reconnect paths use
it. This keeps a transient/unreachable remote (which is what trips the Upgrade
check) at Warning while restoring Error visibility for permanent setup failures.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 34 queries analysed

This is a sync PR whose only change is demoting MySQL/PostgreSQL database-engine connection-failure logs from Error to Warning (plus tests) — it does not touch any query-execution code that ClickBench or TPC-H exercise. Every flagged "improvement" (including the large ×8.5 and ×2.4 faster results) lands on paths the diff cannot reach, so all ten are downgraded to not-sure as run-to-run variance rather than real PR effects; the small source-run count (6 vs 30 baseline) makes this variance expected. ClickBench Q31 was correctly held as no_change within master's variance band, consistent with a PR that has no execution-path impact.

clickbench

⚠️ 8 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 422 340 -19.4% <0.0001 This PR only changes MySQL/PostgreSQL database-engine connection error log levels; it does not touch the SELECT execution path, so the -19.4% shift is run-to-run variance.
⚠️ 15 not_sure 192 163 -15.1% <0.0001 The diff is confined to remote-database connection logging (MySQL/Postgres); ClickBench runs on native tables, so -15.1% here is not a PR effect.
⚠️ 16 not_sure 734 599 -18.4% <0.0001 Nothing in this PR reaches ClickBench's query engine; the -18.4% delta is unrelated variance, not a real improvement.
⚠️ 18 not_sure 1244 1060 -14.8% <0.0001 PR only demotes MySQL/PostgreSQL connection-failure log levels; the -14.8% change on this query cannot be attributed to it and reads as noise.
⚠️ 23 not_sure 164 69 ×2.4 faster <0.0001 Even the large ×2.4 faster (with a CPU drop) sits on a code path this PR never touches; the changed MySQL/Postgres logging is dead for ClickBench, so treat it as variance.
⚠️ 30 not_sure 279 225 -19.4% <0.0001 The diff is external-database connection logging only; -19.4% here is off-path and not a PR-driven improvement.
⚠️ 33 not_sure 1250 1175 -6.0% <0.0001 Small -6.0% shift on a path unrelated to MySQL/Postgres connection logging; run-to-run variance.
⚠️ 34 not_sure 1233 1162 -5.8% <0.0001 Same as Q33: -5.8% on a query this PR's connection-logging change never executes; treat as noise.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 66 ×8.5 faster <0.0001 ×8.5 faster looks dramatic, but TPC-H does not exercise MySQL/PostgreSQL database engines; the changed connection-logging code is never run here, so this is build/variance, not this PR.
⚠️ 8 not_sure 166 77 ×2.2 faster <0.0001 ×2.2 faster on a path untouched by this PR's connection-logging change; not attributable to the diff.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 9fb3c986-ca05-4132-9200-d6c491eae71a
  • MIRAI run: 78b34105-a309-4dec-831a-0f341e28d5b7
  • PR check IDs:
    • clickbench_6119_1787110005
    • clickbench_6125_1787110005
    • clickbench_6136_1787110005
    • tpch_adapted_1_official_6143_1787110005
    • tpch_adapted_1_official_6162_1787110005
    • tpch_adapted_1_official_6189_1787110005

… errors

The `catch (...)` in `DatabasePostgreSQL::getTablesIterator` and
`removeOutdatedTables` demoted every exception to Warning, so a genuine logic
error on those background paths would be hidden. Demote only the tolerated
connection failure (`POSTGRESQL_CONNECTION_FAILURE`, which `PoolWithFailover::get`
throws once every replica's connect attempt fails); any other exception keeps
its default Error level.

Also tighten the `04506` cleaner assertion: pin `pg_cleaner_warning_seen` to the
test's own unreachable endpoint (`message LIKE '%127.0.0.1:1%'`) so it proves the
downgraded line belongs to this test rather than any `removeOutdatedTables` line
in the time window. The negative (`no_error`) assertion stays broad on purpose so
it still catches any stray Error.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Databases/MySQL/DatabaseMySQL.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 78/81 (96.30%) · Uncovered code

Full report · Diff report

tiandiwonder and others added 3 commits July 28, 2026 03:05
Address three gaps the reviewer found in the earlier scoping:

- MySQL (`DatabaseMySQL` ctor `empty()` probe and `getCreateTableQueryImpl`): the
  tolerated `catch (...)` demoted every exception to Warning, but `empty()` also runs
  `INFORMATION_SCHEMA` queries and cache construction, so a permission error or a
  permanent metadata problem after a successful connect was hidden at Warning. Classify
  by type: only `mysqlxx::ConnectionFailed` → Warning, everything else → Error.

- PostgreSQL (`getTablesIterator` / `removeOutdatedTables`): the previous code demoted
  only `POSTGRESQL_CONNECTION_FAILURE` (what `PoolWithFailover::get` rewraps a failed
  connect as), so a connection dropping mid-query surfaced as a raw
  `pqxx::broken_connection` (code `STD_EXCEPTION`) and went back to Error — exactly the
  "remote became unavailable" case to silence. Classify by type too: `broken_connection`
  or `POSTGRESQL_CONNECTION_FAILURE` → Warning, everything else → Error.

- `04506` test: `now()` is second-resolution, so a stale background-cleaner row from a
  run in the same second could satisfy or spuriously fail the cleaner assertions. Use a
  microsecond run discriminator (`now64(6)` + `event_time_microseconds`).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
It was added above `#if USE_MYSQL`, so a build with USE_MYSQL off would pull the
header unconditionally. Place it with the other mysqlxx includes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment on lines +203 to +206
/// A transient transport failure (server unreachable / not responding) is logged
/// at Warning and left for the caller to tolerate; anything else (a server-side
/// rejection or unrecognized failure) stays at Error so a permanent misconfiguration
/// remains visible. See `isTransientConnectionError`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's remove/trim some of the comments, it basically repeats the code / self-explanatory

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in c336d82119c "Trim the log-level comments" — sorry for not replying at the time.

kssenii and others added 2 commits August 7, 2026 12:40
Address review: the comments largely restated the code they sat above. Keep only
what is not visible from the code itself - why a transient failure is not logged
at Error, that `toleratedConnectionFailureLogLevel` must be called from within a
catch block, the shape of the libpq message that
`isTransientConnectionError` matches, and which exception types reach the
tolerated catches in `DatabasePostgreSQL`.

Also use `std::string_view::contains` instead of comparing `find` against `npos`,
which `readability-container-contains` flags in clang-tidy.

Review comment: #109472 (comment)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`toleratedConnectionFailureLogLevel` does not swallow the exception - it rethrows
the active one only to classify it by type, and the caller then logs it via
`tryLogCurrentException` at the returned level. The style check cannot see that,
so mark the trailing `catch (...)` with an `Ok` comment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@kssenii
kssenii enabled auto-merge August 7, 2026 10:44
Comment thread src/Databases/MySQL/DatabaseMySQL.cpp Resolved
04506_remote_database_unreachable_no_error_log failed on every run because
`mysqlxx::PoolWithFailover::get` swallows the per-replica
`mysqlxx::ConnectionFailed` and rethrows `DB::Exception` with the code
`ALL_CONNECTION_TRIES_FAILED`, so `toleratedConnectionFailureLogLevel` in
`DatabaseMySQL.cpp` fell through to the catch-all and kept logging the
tolerated `ATTACH` failure at Error. Classify that code as a tolerated
connection failure too, mirroring the PostgreSQL classifier which already
handles its rewrapped `POSTGRESQL_CONNECTION_FAILURE`.

#109472

Co-Authored-By: Claude Fable 5 <[email protected]>
kssenii and others added 2 commits August 8, 2026 12:12
`mysqlxx::ConnectionLost` is a sibling of `mysqlxx::ConnectionFailed` under
`mysqlxx::Exception`, not a subclass, and it is not a `DB::Exception` either, so
`mysqlToleratedConnectionFailureLogLevel` let it fall through to the catch-all and
kept logging it at Error. That is the case where the server accepts the socket and
then goes away during the `INFORMATION_SCHEMA` query (`mysqlxx::Query` turns
`CR_SERVER_LOST` / `CR_SERVER_GONE_ERROR` into `ConnectionLost`), which is exactly
the tolerated "remote became unavailable" path this pull request is about. Classify
it as a connection failure too, mirroring the PostgreSQL side, which already treats
a raw `pqxx::broken_connection` that way.

The classifier moves out of the anonymous namespace and is renamed to
`mysqlToleratedConnectionFailureLogLevel` so that the new
`gtest_mysql_tolerated_connection_failure` can pin every shape it has to
recognize; the name keeps it distinct from the file-local helper of the same
purpose in `DatabasePostgreSQL.cpp`.

#109472

Co-Authored-By: Claude Opus 5 <[email protected]>
`isTransientConnectionError` matched `could not translate host name` and `Name or
service not known`, so a typoed or nonexistent host - a permanent misconfiguration -
took the Warning path in `postgres::PoolWithFailover`, and an attached database with
an invalid host left no Error-level record in the server log.

Only `Temporary failure in name resolution` (`EAI_AGAIN`, the resolver itself was
unreachable) stays transient; `EAI_NONAME` now falls through to the non-transient
default like any other unrecognized wording.

#109472

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bbf97ae3f with master 3e5c1bc8a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 701.98 MiB 698.96 MiB -3.02 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +7.7 s (+7%) in total before that adjustment.

Job report

`BorrowedObjectPool::tryBorrowObject` leaves `dest` untouched when it times out
(`base/base/BorrowedObjectPool.h:79-84`), so on the timeout path of
`connectionReestablisher` the `ConnectionPtr` is still null and
`connection->getInfoForLog()` dereferenced it. Whenever the pool was exhausted and
every slot was borrowed, the background reconnect was undefined behavior.

Name the replica with the pool's own `connection_info.host_port` instead - the same
string `getInfoForLog` would have returned, but available without a borrowed
connection. The equivalent site in `get` already logs without touching `connection`.

Pre-existing since 1511446, not introduced by this pull request.

#109472 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>

# A system.tables scan reaches DatabasePostgreSQL::getTablesIterator, which tolerates the failure.
${CLICKHOUSE_CLIENT_QUIET} --query_id "${PG_SCAN_QUERY_ID}" -q \
"SELECT count() FROM system.tables WHERE database = '${PG_DB}' SETTINGS show_remote_databases_in_system_tables = 1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

DatabaseMySQL::getTablesIterator is still the odd one out here: it calls fetchTablesIntoLocalCache without any tolerance boundary (src/Databases/MySQL/DatabaseMySQL.cpp:179-190), and fetchTablesWithModificationTime builds MySQLSource from mysql_pool.get() directly (src/Databases/MySQL/DatabaseMySQL.cpp:366-398). So a system.tables / system.columns scan over an unreachable MySQL database still rethrows ALL_CONNECTION_TRIES_FAILED instead of logging Warning and returning an empty iterator like the PostgreSQL engine now does.

With show_remote_databases_in_system_tables = 1 by default, the sibling MySQL metadata surface is still inconsistent. Please either make the MySQL iterator tolerant too, or narrow the scope and coverage so this unsupported path is explicit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added — DatabaseMySQL::getTablesIterator now wraps fetchTablesIntoLocalCache the same way DatabasePostgreSQL does, classifying the level through mysqlToleratedConnectionFailureLogLevel. You were right that the metadata surface was inconsistent: with show_remote_databases_in_system_tables = 1 a system.tables scan over an unreachable MySQL database aborted with ALL_CONNECTION_TRIES_FAILED. Enumeration is now best-effort, while the direct operations (empty, tryGetTable) keep throwing.

Also extended 04506_remote_database_unreachable_no_error_log with a MySQL system.tables probe — as you noted, it previously covered only the PostgreSQL scan plus the MySQL attach, so this path was unpinned. Verified closed-loop: with the guard reverted and rebuilt, the query fails with Code: 279 ... ALL_CONNECTION_TRIES_FAILED and both new assertions flip to 0, while the other eight stay at 1. (commit 0a8e378)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The current code no longer matches the "fixed" claim in this thread: src/Databases/MySQL/DatabaseMySQL.cpp still calls fetchTablesIntoLocalCache(local_context) unguarded, so an unreachable MySQL remote continues to propagate out of DatabaseMySQL::getTablesIterator instead of being logged and tolerated.

tiandiwonder and others added 3 commits August 13, 2026 06:53
…ator`

`DatabasePostgreSQL::getTablesIterator` already refuses to throw, so that a
`system.tables` / `system.columns` scan does not fail because one remote
database is down. The MySQL sibling called `fetchTablesIntoLocalCache`
unguarded, so with `show_remote_databases_in_system_tables = 1` such a scan
still aborted with `ALL_CONNECTION_TRIES_FAILED` instead of logging the
tolerated failure and returning what it had.

Wrap the fetch the same way, classifying the level through
`mysqlToleratedConnectionFailureLogLevel`. Enumeration stays best-effort;
the direct operations (`empty`, `tryGetTable`) keep throwing.

Extend `04506_remote_database_unreachable_no_error_log` with a MySQL
`system.tables` probe. It previously covered the PostgreSQL scan plus the
MySQL attach only, so this path was unpinned.

Co-Authored-By: Claude Opus 5 <[email protected]>
`Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6)` failed on
`test_mysql_database_engine::test_restart_server` and its `mysql57` twin, both with
`Query SHOW TABLES FROM test_restart did not fail`. That is this change's fault, and
the tests are right.

Their scenario partitions ClickHouse from MySQL **and restarts ClickHouse**, so
`local_tables_cache` is empty. Tolerating the fetch failure there does not serve
slightly stale data - it reports an empty table list, turning "cannot reach MySQL"
into "this database has no tables". An error is the better answer, which is exactly
what the test was written to pin.

There is no way to keep both: `SHOW TABLES FROM db` is `SELECT name FROM
system.tables WHERE database = 'db'`, the same `getTablesIterator` call the added
stateless assertion made, and both had an empty cache. So drop the tolerance rather
than weaken a deliberate contract - `DatabasePostgreSQL` doing the same thing is
precedent for the shape, not a reason to believe it is right there either.

Nothing else changes: the log-level demotions this pull request is actually about
stay, on the `ATTACH` probe, the failover logger and `getCreateTableQueryImpl`, and
`04506` still pins them (its MySQL `ATTACH` group and the PostgreSQL groups). Only
the two `mysql_scan_*` assertions that depended on the swallow are removed.

Co-Authored-By: Claude Opus 5 <[email protected]>
The branch added for permanent connection failures was the only one in this
callback without the `interval_milliseconds >= 1000` guard that the transient,
`Poco::Exception` and catch-all branches all use. `ReplicasReconnector` re-enters
the callback once per `dictionary_background_reconnect_interval`, so a dictionary
with `background_reconnect = 1` and a shorter interval - 100 ms, say - turned one
bad password or missing database into an error line every cycle. That is the log
flood this pull request exists to remove, reintroduced on a new path.

Apply the same guard. `dictionary_background_reconnect_interval` defaults to
1000 ms and the guard is `>= 1000`, so a permanent failure is still reported at
error level in the default configuration; it goes quiet only when an operator
picks a sub-second interval, which already silences the other three branches.

`04506_remote_database_unreachable_no_error_log` is unchanged and still passes:
its PostgreSQL assertions cover `getTablesIterator` and the background cleaner,
not this callback.

Co-Authored-By: Claude Opus 5 <[email protected]>
@kssenii
kssenii added this pull request to the merge queue Aug 20, 2026
Merged via the queue into master with commit b3a24eb Aug 20, 2026
514 of 517 checks passed
@kssenii
kssenii deleted the fix-remote-db-unreachable-log-level branch August 20, 2026 08:01
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@tiandiwonder @kssenii — title/description suggestions:

Description (currently incomplete):

  • Why: The body does not mention the null-pointer-dereference fix at src/Core/PostgreSQL/PoolWithFailover.cpp:46, and does not state that in the background reconnector a permanent failure now logs at Error once per dictionary_background_reconnect_interval (default 1000 ms) where it previously logged at Warning.

  • Suggested addition:

    Also fixes a null-pointer dereference on the tryBorrowObject timeout branch of postgres::PoolWithFailover::connectionReestablisher: tryBorrowObject returns false without touching connection, so the old connection->getInfoForLog() in that log line dereferenced a null unique_ptr. The replica is now named from shared_pool->connection_info.host_port.

    Note on the background reconnector: for a PERMANENT failure the new Error branch is re-entered once per dictionary_background_reconnect_interval (default 1000 ms), so a misconfigured PostgreSQL dictionary now produces one Error line per second where it previously produced one Warning per second.

Ignore if intentional.

@clickgapai

Copy link
Copy Markdown
Contributor

@tiandiwonder @kssenii — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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