Repository navigation
Log tolerated connection failures to remote MySQL/PostgreSQL databases as warnings instead of errors - #109472
Conversation
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]>
|
Workflow [PR], commit [bbf97ae] Summary: ✅
AI ReviewSummaryThis PR demotes tolerated remote MySQL/PostgreSQL connection failures from Findings
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 113/121 (93.39%) · Uncovered code |
| 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
| { | ||
| 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()); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (8 of 43)
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_officialFlagged queries (2 of 22)
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
|
… 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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 78/81 (96.30%) · Uncovered code |
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]>
| /// 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`. |
There was a problem hiding this comment.
Let's remove/trim some of the comments, it basically repeats the code / self-explanatory
There was a problem hiding this comment.
Done in c336d82119c "Trim the log-level comments" — sorry for not replying at the time.
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]>
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]>
`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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units24 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. |
`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" |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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.
…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]>
|
@tiandiwonder @kssenii — title/description suggestions: Description (currently
Ignore if intentional. |
|
@tiandiwonder @kssenii — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
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 thegetTablesIteratorline above; the report shows green now because the check passed on a later rerun — which is exactly the flaky-victim pattern).Problem. A
DatabasePostgreSQLorDatabaseMySQLpointed 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:system.tables/system.columnsscan that touches the database logs an error (DatabasePostgreSQL::getTablesIterator:Code: 614. DB::Exception: ... Connection to ... failed);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 test04210_show_remote_databases_in_system_tables(added in #104416) leavesPostgreSQL/MySQLdatabases pointed at the unroutable192.0.2.1during the check's restart window, and since #109082 made remote databases visible tosystem.tablesscans 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 sosystem.tablesscans do not fail) andDatabasePostgreSQL::removeOutdatedTables(the cleaner reschedules and continues) usetryLogCurrentExceptionwith the defaultLogsLevel::error; the same for theDatabaseMySQLconstructor catch onATTACHandDatabaseMySQL::getCreateTableQueryImplwiththrow_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 DATABASEwith 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_logattachesPostgreSQLandMySQLdatabases pointing at an unreachable host, exercises the tolerated paths (attach probe,system.tablesscan, background cleaner), and asserts throughsystem.text_logthat 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):
Workflow [PR]
Sync PR [sync-upstream/pr/109472]