Skip to content

Fix clickhouse-local hang in shutdown when system logs are configured - #103874

Merged
Algunenano merged 6 commits into
masterfrom
fix-system-log-shutdown-hang
May 5, 2026
Merged

Algunenano merged 6 commits into
masterfrom
fix-system-log-shutdown-hang

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 1, 2026 •

Copy link
Copy Markdown
Member

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 a ClientApplicationBase (e.g. clickhouse-local, clickhouse-client) the cast throws std::bad_cast. The exception escapes SystemLogs::flushAndShutdown -> DatabaseCatalog::shutdownImpl -> Context::shutdown, leaving every saving thread alive.

When the last Context reference goes away, ~ContextSharedPart runs ~SystemLogs -> ~SystemLog<T>. queue is declared 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 on the saving thread parked in pop(). The periodic saving-thread flushes that fire after ~Application already nulled _pInstance surface as Null pointer: _pInstance from Context::getConfigRef() -> Poco::Util::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. Defence-in-depth so any future path that bypasses flushAndShutdown cannot 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 in pthread_cond_destroy from ~SystemLogQueue<FilesystemCacheLogElement>. With this change the same invocation completes in ~3.2 s (residual time is the cost of constructing every configured SystemLog) 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):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a hang in clickhouse-local shutdown when system logs (such as text_log or filesystem_cache_log) are configured. SystemLogs::flushImpl was calling BaseDaemon::instance().flushTextLogs(), which throws std::bad_cast outside clickhouse-server and left the saving threads running until pthread_cond_destroy blocked the destruction of the system log queues.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.271

…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]>
@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2cd6c11]

Summary: ✅


AI Review

Summary

This PR fixes shutdown hangs outside clickhouse-server by avoiding BaseDaemon::instance() in SystemLogs::flushImpl and by joining system log flush threads in ~SystemLog before derived members are destroyed. The changes are targeted, align with the root cause, and I did not find correctness, safety, or compatibility regressions in the patched paths.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 1, 2026
Comment thread src/Common/SystemLogBase.cpp Resolved
Comment thread src/Common/SystemLogBase.cpp Resolved

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Now ok.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The only CI failure is Unit tests (asan_ubsan, function_prop_fuzzer) — FunctionsStress.stress aborting with Logical error: 'prev.thread_id == curr.thread_id' from RUsageCounters::incrementProfileEvents. This is unrelated to the changes in this PR (which only touch SystemLogBase/SystemLog) and matches the known open issue #103750.

Log: https://s3.amazonaws.com/clickhouse-test-reports/PRs/103874/f1b93b873aa079cd9c66eb13e1c8380d68fe98fa/unit_tests_asan_ubsan_function_prop_fuzzer/job.log

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, why did performance test fail? Please investigate, fix, and send a separate PR.

@groeneai

groeneai commented May 4, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated. Chronic Performance Comparison master_head noise — not caused by this PR.

The single failing job is Performance Comparison (arm_release, master_head, 5/6) — 18 failures, all in 3 tests:

Test Slower count
logical_functions_small (#9, #10, #11, #12, #13, #14, #15) 7
distinct_in_order (#6) 1
logical_functions_medium (#1) 1

Both ::old (master_head reference build) AND ::new (this PR's build) are flagged "slower" for every failing test. That signature means the regression lives in master — both builds rebuild from master, so PR-side changes can't be the cause. If the regression were introduced by this PR, only ::new rows would fail.

Cross-PR analysis (CIDB, last 14 days, shard 5/6 only, master_head reference):

Test Distinct unrelated PRs failing
logical_functions_small 30+
distinct_in_order 30+
logical_functions_medium 28+

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), fix-json-check-part (#103858), eliminate_redundant_join (#103254), even master itself (pull_request_number = 0). This PR's changes are confined to BaseDaemon::tryGetInstance / SystemLogs::flushImpl — no SELECT / function / read-path code is touched, so it cannot plausibly slow down logical_functions_* or distinct_in_order.

Recommendation: chronic noise on arm_release master_head 5/6. Re-trigger the job or proceed to merge — no fix PR needed from our side. We're already tracking this chronic perf-comparison pattern in our CI monitor.

— @groeneai (session: cron:clickhouse-ci-task-worker:20260504-031500)

Comment thread src/Common/SystemLogBase.cpp Outdated
template <typename LogElement>
SystemLogBase<LogElement>::~SystemLogBase()
{
stopFlushThread();

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.

~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)
@clickhouse-gh

clickhouse-gh Bot commented May 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (12/12) · Uncovered code

Full report · Diff report

@Algunenano Algunenano self-assigned this May 5, 2026
@Algunenano
Algunenano added this pull request to the merge queue May 5, 2026
Merged via the queue into master with commit 982a760 May 5, 2026
165 checks passed
@Algunenano
Algunenano deleted the fix-system-log-shutdown-hang branch May 5, 2026 08:08
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 5, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: SystemLogs::flushImpl and SystemLog<E>::~SystemLog (new) — core code present in all supported branches.

Why: User-visible hang affecting all clickhouse-local/clickhouse-client invocations when any text_log section is configured. BaseDaemon::instance() and SystemLogs::flushAndShutdown predate all supported releases (the SystemLog framework has been in ClickHouse since the earliest releases). The hang itself depends on the docs job-style config used in CI but the same fix is appropriate everywhere.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@Algunenano

Copy link
Copy Markdown
Member

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

@clickgapai No it does not. You can check when the issue was introduced and see it's not present in any release

@clickgapai

Copy link
Copy Markdown
Contributor

You're right — I was wrong. I checked the actual release branches:

  • v26.3.3.20-lts: programs/local/LocalServer.cpp does not call initializeSystemLogs().
  • v26.2.7.17-stable, v26.1.7.13-stable, v25.8.21.7-lts: same — no initializeSystemLogs() in LocalServer.cpp.
  • master (HEAD): programs/local/LocalServer.cpp:1189 now calls global_context->initializeSystemLogs();.

The two BaseDaemon::instance().flushTextLogs() call sites in SystemLogs::flushImpl do exist in 25.8/26.1/26.2/26.3 (introduced by #80125). But in clickhouse-local they were unreachable on those releases because text_log was never created — LocalServer never called initializeSystemLogs().

Adding that call on master makes the latent dynamic_cast<BaseDaemon&> reachable from clickhouse-local for the first time, and that's the regression #103874 fixes. Master-only, no backport needed.

Sorry for the noise.

maxknv pushed a commit to groeneai/ClickHouse that referenced this pull request May 6, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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.

Docs check fails on every PR: clickhouse-local hangs on shutdown when many system logs are configured

5 participants