Repository navigation
Fix clickhouse-local hang in shutdown when system logs are configured - #103874
Conversation
…Logs` flush `SystemLogs::flushImpl` calls `BaseDaemon::instance().flushTextLogs()` to drain the async logger before iterating system log queues. `BaseDaemon::instance()` is `dynamic_cast<BaseDaemon &>(Poco::Util::Application::instance())`, so when the application is `ClientApplicationBase`-derived (e.g. `clickhouse-local`, `clickhouse-client`) the cast throws `std::bad_cast`. The exception escapes `SystemLogs::flushAndShutdown` -> `DatabaseCatalog::shutdownImpl` -> `Context::shutdown`, leaving the saving threads alive. When the holder of the last `Context` reference drops it, `~ContextSharedPart` runs `~SystemLogs` -> `~SystemLog<T>`. `queue` lives in `SystemLogBase<T>` and `saving_thread` in `ISystemLog`, so member destruction tears down the `SystemLogQueue` and its condition variables before the saving thread has been joined. `pthread_cond_destroy` then blocks forever because the saving thread is still parked in `pop()` waiting on `flush_event`. Meanwhile the periodic saving-thread flushes that fire after `~Application` has already nulled `_pInstance` show up as `Null pointer: _pInstance` from `Context::getConfigRef()` -> `Application::instance().config()` (via `InterpreterCreateQuery::createTable` -> `UserDefinedSQLFunctionFactory::empty` -> `Context::getUserDefinedSQLObjectsStorage`), which is the symptom reported on the docs check. Two fixes: * `SystemLogs::flushImpl` now calls a small `flushAsyncTextLogsIfPossible` helper that uses `BaseDaemon::tryGetInstance` (a `dynamic_cast<BaseDaemon *>` internally) and skips the call when the application is not a `BaseDaemon`, so flushing on `clickhouse-local`/`clickhouse-client` is a no-op instead of raising `std::bad_cast`. * `SystemLogBase<T>` now has an explicit destructor that calls `stopFlushThread()`, joining the saving thread before any of the queue's condition variables can be destroyed. This is defence-in-depth so that any future path that bypasses `flushAndShutdown` cannot reproduce the same hang. Reproduction with the affected docs config (~30 system log sections, `SELECT 1`) on master: query takes 54+ s and the process hangs in `pthread_cond_destroy` from `~SystemLogQueue<FilesystemCacheLogElement>`. With this change the same invocation completes in ~3.2 s (the residual time is the cost of constructing every configured `SystemLog`) and exits cleanly. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103843&sha=41c0a8a98f6f189f2c3c7025a979112c40ce7220&name_0=PR&name_1=Docs%20check PR: #103843 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Workflow [PR], commit [2cd6c11] Summary: ✅ AI ReviewSummaryThis PR fixes shutdown hangs outside ClickHouse Rules
Final Verdict
|
|
The only CI failure is |
|
@groeneai, why did performance test fail? Please investigate, fix, and send a separate PR. |
|
@alexey-milovidov — investigated. Chronic The single failing job is
Both Cross-PR analysis (CIDB, last 14 days, shard 5/6 only,
The exact same tests fail on PRs touching completely unrelated code: Kafka2 direct read (#100276), RocksDB stats race (#101108), Decimal/JIT (#103809), Iceberg upgrade (#100407), Recommendation: chronic noise on — @groeneai (session: cron:clickhouse-ci-task-worker:20260504-031500) |
| template <typename LogElement> | ||
| SystemLogBase<LogElement>::~SystemLogBase() | ||
| { | ||
| stopFlushThread(); |
There was a problem hiding this comment.
~SystemLogBase runs after ~SystemLog has already destroyed derived members, but the flushing thread executes SystemLog::savingThreadFunction and touches derived state (e.g. log, flush_policy). Calling stopFlushThread here means the thread can still run while those members are already destructed, which is a UAF/data-race hazard on exceptional shutdown paths.
Could we stop/join the thread from ~SystemLog (or another derived-level hook that runs before derived members are destroyed) and keep the base destructor passive? That preserves the intended safety net without relying on post-destruction lifetime.
…mLogBase` `SystemLog<T>::savingThreadFunction` reads derived-class members (`log`, `flush_policy`, `table_id`, ...). Joining from `~SystemLogBase` ran after those members were already destroyed, so the saving thread could observe freed state on the bypassed-shutdown path the previous commit was guarding against. Move the join to `~SystemLog<T>`, which executes before any of `SystemLog`'s own members are destroyed. The base destructor stays implicit, since no class derives from `SystemLogBase` directly. Reviewer: #103874 (comment)
LLVM Coverage Report
Changed lines: 100.00% (12/12) · Uncovered code |
|
Hi — this PR may need backporting to Affected code: Why: User-visible hang affecting all If this should be backported, consider adding |
@clickgapai No it does not. You can check when the issue was introduced and see it's not present in any release |
|
You're right — I was wrong. I checked the actual release branches:
The two Adding that call on master makes the latent Sorry for the noise. |
PR ClickHouse#103917 narrowed the `wrong_metadata_wide` allowlist to the specific corrupted-filename signature emitted by `02538_alter_rename_sequence` after the `getFileNameForRenamedColumnStream` `substr(0, N)` bug (issue ClickHouse#102259, fix in PR ClickHouse#102689). The same bug also surfaces on `02555_davengers_rename_chain`'s `wrong_metadata` table, but with a different column/stream pair, so the narrow regex did not catch it and the upgrade check began failing on unrelated PRs. Add the matching narrow signatures: * `No stream (ba1.bin) file checksum for column b` — the chained rename `a -> a1 -> b` produces `<new=b><old=a1>.bin = ba1.bin` for column `b`. This `<column><stream>` combination is unique to that test and that bug. * Loosen `wrong_metadata_wide` to `wrong_metadata` in the secondary `Detaching broken part` regex so it matches both narrow and wide table variants. The other two substrings (`Detaching broken part` + `backward incompatibility`) keep the allowlist scoped to the same symptom. Verified against the failing log (https://s3.amazonaws.com/clickhouse-test-reports/PRs/103874/49885046aba0893d06655439d554aeac6998469e/upgrade_check_amd_release/upgrade_error_messages.txt): all six lines are filtered, while synthetic unrelated errors (other tables, generic detach notices, log lines that mention the table name in passing) pass through. Source PR with the failing run: ClickHouse#103874
SystemLogs::flushImplcallsBaseDaemon::instance().flushTextLogs()to drain the async logger before iterating system log queues.BaseDaemon::instance()isdynamic_cast<BaseDaemon &>(Poco::Util::Application::instance()), so when the application is aClientApplicationBase(e.g.clickhouse-local,clickhouse-client) the cast throwsstd::bad_cast. The exception escapesSystemLogs::flushAndShutdown->DatabaseCatalog::shutdownImpl->Context::shutdown, leaving every saving thread alive.When the last
Contextreference goes away,~ContextSharedPartruns~SystemLogs->~SystemLog<T>.queueis declared inSystemLogBase<T>andsaving_threadinISystemLog, so member destruction tears down theSystemLogQueueand its condition variables before the saving thread has been joined.pthread_cond_destroythen blocks forever on the saving thread parked inpop(). The periodic saving-thread flushes that fire after~Applicationalready nulled_pInstancesurface asNull pointer: _pInstancefromContext::getConfigRef()->Poco::Util::Application::instance().config()(viaInterpreterCreateQuery::createTable->UserDefinedSQLFunctionFactory::empty->Context::getUserDefinedSQLObjectsStorage), which is the symptom reported on the docs check.Two fixes:
SystemLogs::flushImplnow calls a smallflushAsyncTextLogsIfPossiblehelper that usesBaseDaemon::tryGetInstance(adynamic_cast<BaseDaemon *>internally) and skips the call when the application is not aBaseDaemon, so flushing onclickhouse-local/clickhouse-clientis a no-op instead of raisingstd::bad_cast.SystemLogBase<T>now has an explicit destructor that callsstopFlushThread(), joining the saving thread before any of the queue's condition variables can be destroyed. Defence-in-depth so any future path that bypassesflushAndShutdowncannot reproduce the same hang.Reproduction with the docs-job config (~30 system log sections,
SELECT 1) on master: query takes 54+ s and the process hangs inpthread_cond_destroyfrom~SystemLogQueue<FilesystemCacheLogElement>. With this change the same invocation completes in ~3.2 s (residual time is the cost of constructing every configuredSystemLog) and exits cleanly.CI report (PR #103843, Docs check): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103843&sha=41c0a8a98f6f189f2c3c7025a979112c40ce7220&name_0=PR&name_1=Docs%20check
Closes #103915
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a hang in
clickhouse-localshutdown when system logs (such astext_logorfilesystem_cache_log) are configured.SystemLogs::flushImplwas callingBaseDaemon::instance().flushTextLogs(), which throwsstd::bad_castoutsideclickhouse-serverand left the saving threads running untilpthread_cond_destroyblocked the destruction of the system log queues.Documentation entry for user-facing changes
Version info
26.5.1.271