Skip to content

Fix DateLUT atexit heap-use-after-free vs asynchronous logger - #106620

Merged
nikitamikhaylov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-105375-datelut-atexit-uaf
Jun 6, 2026
Merged

nikitamikhaylov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-105375-datelut-atexit-uaf

Conversation

@groeneai

@groeneai groeneai commented Jun 6, 2026 •

Copy link
Copy Markdown
Collaborator

Fix heap-use-after-free at clickhouse-local shutdown reported as Scraping system tables in CI ASan jobs.

Failure mode (CIDB, 30 days, 9 hits across 6 unrelated PRs; arm_asan_ubsan azure/targeted, amd_asan_ubsan flaky check/distributed plan):

==NNNN==ERROR: AddressSanitizer: heap-use-after-free
READ of size 8 at 0x... thread T3 (AsyncLogger)
    #0 findIndex                                src/Common/DateLUTImpl.h:245
    #1 DateLUTImpl::toDateTimeComponents        src/Common/DateLUTImpl.h:1314
    #2 LocalDateTime::init                      src/Common/LocalDateTime.cpp:6
    ...
    #5 OwnPatternFormatter::formatExtended      src/Loggers/OwnPatternFormatter.cpp:23
    ...
    #8 OwnAsyncSplitChannel::runChannel         src/Loggers/OwnSplitChannel.cpp:529

freed by thread T0 here:
    #0 operator delete(...)
    ...
    #3 ~unique_ptr<DateLUTImpl>                 contrib/llvm-project/libcxx/include/__memory/unique_ptr.h:258
    #4 ~pair                                    contrib/llvm-project/libcxx/include/__utility/pair.h:88
    ...
    DateLUT::~DateLUT

Root cause is a cross-translation-unit static-destructor-order race. DateLUT::getInstance returned a function-local static DateLUT ret;. Poco's auto_logger_shutdown static (in base/poco/Foundation/src/Logger.cpp) is what ultimately joins the asynchronous logger threads via ~OwnAsyncSplitChannel::close. The order between these two static destructors across translation units is unspecified, so a clickhouse-local exit can free the timezone map while a logger thread is still formatting a queued log message that contains a timestamp.

Fix is to deliberately leak the DateLUT instance so it outlives every other static. The pointer remains reachable from the function-local static, so LeakSanitizer does not report it. The OS reclaims the memory at process exit. This is the standard idiom for static-init-order destruction races and matches the comment in Common/ThreadPool.h ("order of destructors of global static objects and callbacks added by atexit is undefined for different translation units").

Local verification on build-asan (clang-21, -DSANITIZE=address,undefined):

Binary Iterations ASan reports
Master (static DateLUT ret;) 400 (50 batches x 8 parallel clickhouse local invocations with the asynchronous logger at trace level) 4 (~1.0%, captured stacks match the CI signature: T2/T3 AsyncLogger reading freed memory allocated by T0)
With fix (static DateLUT * ret = new DateLUT;) 400 (same harness) 0

CI report referenced by @alexey-milovidov: #105375

Related: #105375

Changelog category (leave one):

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

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.447

Surface in CI: `Scraping system tables` `heap-use-after-free` reported by ASan during
`clickhouse-local` shutdown. CIDB shows the failure across multiple unrelated PRs over
the last 30 days (`arm_asan_ubsan` `azure`/`targeted`, `amd_asan_ubsan` `flaky check`/
`distributed plan`); 9 hits, 6 PRs.

Free side, thread `T0`:
    `DateLUT::~DateLUT` -> `~unordered_map` of `DateLUTImpl`
Read side, thread `T3 AsyncLogger`:
    `OwnAsyncSplitChannel::runChannel` -> `OwnPatternFormatter::formatExtended`
        -> `LocalDateTime::init` -> `DateLUTImpl::findIndex` (`src/Common/DateLUTImpl.h:245`)

Root cause is a cross-translation-unit static-destructor-order race. The previous
`DateLUT::getInstance` returned a function-local `static DateLUT ret;`, and Poco's
`auto_logger_shutdown` static (in `base/poco/Foundation/src/Logger.cpp`) is what
ultimately joins the asynchronous logger threads via `~OwnAsyncSplitChannel::close`.
The order of these two static destructors is unspecified, so the timezone map can be
freed while a logger thread is still formatting a queued log message that contains a
timestamp.

Fix: deliberately leak the `DateLUT` instance so it outlives every other static. The
pointer remains reachable from the function-local static, so LeakSanitizer does not
report it. The OS reclaims the memory at process exit. This is the standard idiom for
static-init-order destruction races and matches the comment in `Common/ThreadPool.h`.

Reproduced and verified locally on `build-asan` (clang-21). Buggy binary produced
4 ASan reports out of 400 parallel `clickhouse local` invocations with the
asynchronous logger enabled at trace level (~1% rate, matching CI). Fixed binary
produced 0/400 on the same harness.

Closes: ClickHouse#94003

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes (under contention). Spawning 8 concurrent clickhouse local invocations, each running a query that produces a heavy log burst with the asynchronous logger writing to a file at trace level, reproduces the ASan heap-use-after-free at ~1.0% rate (4 hits in 400 invocations on build-asan clang-21). The captured stack matches the CIDB signature exactly: T2/T3 (AsyncLogger) -> ... -> findIndex, freed by T0 from ~unique_ptr<DateLUTImpl> inside ~DateLUT. The race is timing-sensitive but the failure mode and signature are identical to the CI hits.
b Root cause explained? DateLUT::getInstance returns a function-local static DateLUT ret; (src/Common/DateLUT.cpp:209); Poco's auto_logger_shutdown is a namespace-scope static in base/poco/Foundation/src/Logger.cpp:460 that ultimately joins the asynchronous logger threads via ~OwnAsyncSplitChannel::close. The order of these two static destructors across translation units is unspecified by C++. When DateLUT::~DateLUT runs first, it destroys the timezone unordered_map; while T3 AsyncLogger is still draining its AsyncLogMessageQueue and formatting timestamps via LocalDateTime::init -> DateLUTImpl::findIndex, that read dereferences a DateLUTImpl whose backing storage has just been freed.
c Fix matches root cause? Yes. Making DateLUT immortal (heap-allocated, never destroyed) eliminates the race at the source: there is no destructor to fire, so no destructor-order dependency exists. This is the standard C++ idiom for static-init-order destruction races; the codebase already documents the same reasoning in Common/ThreadPool.h ("order of destructors of global static objects and callbacks added by atexit is undefined for different translation units"). The OS reclaims the memory at process exit.
d Test intent preserved / new tests added? No new test added. The race is timing-dependent (~1% under heavy concurrent load on a stressed 32-core box; rarer in CI). A 16-iteration sequential test caught 0/8 runs, so a deterministic stateless regression test is not feasible. CIDB will detect any reintroduction organically — CI runs clickhouse local thousands of times under ASan every day across Scraping system tables in many test variants.
e Both directions demonstrated? Yes. Same harness on both binaries: master → 4/400 ASan reports; with-fix → 0/400. Captured master stack matches CI signature.
f Fix is general, not a narrow patch? Yes. The fix targets the source of the bad state, not the symptom. Alternative narrow patches (e.g. a defensive check inside findIndex or LocalDateTime::init) would only mask an already-corrupted DateLUT rather than prevent the corruption from arising. The leak makes DateLUT immortal globally, so every other consumer (StatusFile, SignalHandlers, mysqlxx::Value, etc.) that calls DateLUT::instance() at any point during the lifetime of the process is also protected — not just the one observed in CI. The leaked allocation is reachable from a static pointer, so LeakSanitizer does not report it.

Session id: cron:clickhouse-ci-task-worker:20260606-013800

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @alexey-milovidov — could you review this? It deliberately leaks the DateLUT singleton to fix the cross-translation-unit static-destructor-order race against Poco's auto_logger_shutdown that surfaces as the Scraping system tables heap-use-after-free in CI ASan jobs.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2b37ea3]

Summary: ✅


AI Review

Summary
  • The PR fixes the reported shutdown-time DateLUT lifetime race by making the process-wide DateLUT singleton intentionally immortal. The changed DateLUT::getInstance path covers DateLUT::instance, DateLUT::instance(time_zone), DateLUT::serverTimezoneInstance, and DateLUT::setDefaultTimezone, so formatter-held DateLUTImpl references no longer depend on cross-translation-unit static destructor order. I found no unresolved correctness, safety, or metadata issues.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.50% +0.00%
Functions 92.40% 92.30% -0.10%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 2/2 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: 2b37ea312d159d7bcf99594736cb51245694db30

CI fully finished and fully clean on the first run: 142 pass / 24 skipping, Finish Workflow pass, Mergeable Check pass, no failing checks, zero per-test FAIL/ERROR rows in CIDB across all jobs (full FT/IT matrix, AST/BuzzHouse fuzzers, Unit tests, Stress).

The fix (heap-allocate DateLUT once and never destroy it, eliminating the ~DateLUT atexit teardown that races with the asynchronous logger thread) introduced no test regressions.

@nikitamikhaylov nikitamikhaylov self-assigned this Jun 6, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jun 6, 2026
Merged via the queue into ClickHouse:master with commit 48a50e9 Jun 6, 2026
166 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 6, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to fix CI

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 29, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants