Skip to content

Fix a permanent hang on macOS in libc time zone functions under profiler signals - #125369

Merged
Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:darwin-libc-timezone-lock-shim
Oct 13, 2026
Merged

Algunenano merged 2 commits into
ClickHouse:masterfrom
groeneai:darwin-libc-timezone-lock-shim

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117253
Related: #112267

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):

Fixed a permanent hang of the server on macOS, where threads that format a time (for example while signing S3 requests, reporting an exceeded quota or reloading a dictionary) could wait forever on the C library's internal time zone lock while the query profiler was enabled.

Description

On 26.9 (macOS), a server running queries with the default query profiler can hang permanently inside libc's time functions. Seen in Fast test (arm_darwin) on #117253: three threads wait in strftime_l -> _st_tzset_basic -> _pthread_rwlock_lock_slow (S3 request signing, throwQuotaExceed, and ExternalLoader calculateNextUpdateTime), no thread holds the lock, and every later CREATE / DROP DATABASE blocks behind them.

macOS libc guards its time zone state with a private pthread_rwlock (lcl_rwlock), taken by strftime, localtime(_r), mktime, strptime, tzset and a few others. It is the psynch rwlock that loses wakeups when its waiters are interrupted by signals (FB24027930), and the profiler signals every registered thread. #112267 replaced pthread_rwlock_* for code linked into the binary, but libsystem_c binds its own lock to the system implementation through the two-level namespace.

base/darwin-compatibility/libc_timezone_shim.c defines the 16 public libc functions that take that lock; each calls the real one (dlsym(RTLD_NEXT)) under one recursive mutex. It is force-loaded with the rwlock shim, so every caller in the binary (cctz, the AWS SDK and other contribs) binds to it, and at most one of these threads is inside libc's time zone code at a time, so none of them waits on that lock. Calls made inside Apple frameworks are not covered, the same boundary as #112267. Cost: these calls no longer run concurrently on macOS; they take microseconds, and ClickHouse's date and time functions do not use them. Linux is unaffected.

There is no test, as for #112267: the hang needs libc's writer path, which no query can trigger, and CI runs only the fast test on macOS. In a cross-built arm64 binary these functions are no longer imported from libSystem (8 before), and the cctz and AWS SDK call sites branch to the new definitions.


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

Version info

  • Merged into: 26.10.1.2257-master (included in 26.10 and later)

groeneai and others added 2 commits October 12, 2026 09:22
macOS libc guards its time zone state with a private pthread_rwlock
(`lcl_rwlock` in Libc stdtime/FreeBSD/localtime.c), taken by strftime(_l),
wcsftime(_l), strptime(_l), localtime(_r), ctime(_r), mktime, timelocal,
time2posix, posix2time, tzset and tzsetwall. It is the psynch rwlock that
loses wakeups when its waiters are interrupted by signals (FB24027930), and
the macOS query profiler signals every registered thread. The pthread_rwlock
shim from ClickHouse#112267 does not reach it, because libsystem_c binds to libpthread
through the two-level namespace.

Seen in Fast test (arm_darwin) on ClickHouse#117253: S3 request signing
(Aws::Utils::DateTime::ToGmtString), EnabledQuota::Impl::throwQuotaExceed and
ExternalLoader::LoadingDispatcher::calculateNextUpdateTime (holding the
ExternalLoader mutex) all wait in strftime_l -> _st_tzset_basic with no holder.

Define these 16 functions in the force-loaded darwin-compatibility archive.
Each resolves the libc function with dlsym(RTLD_NEXT) and calls it under one
recursive mutex, so at most one thread of the binary is inside libc's time
zone code and none waits on its rwlock. errno is preserved across the mutex,
because a contended Darwin mutex retries an interrupted __psynch_mutexwait /
__psynch_mutexdrop and can leave EINTR behind on success.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the libc_timezone_shim.c header and narrow the recursive-mutex comment to what recursion actually guarantees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings; 1 full pass).

# Sev Finding Verdict Evidence / action
1 ⚠️ getdate reaches the libc time zone lock internally but is not wrapped DISAGREE No code in the binary calls it: 0 imports of _getdate in the CI arm64 and x86_64 Darwin binaries of #117253 and in this tree's arm64 build. Wrapping it is one line if a caller ever appears.
2 ⚠️ No proof that the final Mach-O binds to the wrappers DISAGREE Same-tree arm64 relink with CI's ld64: 0 of the 16 names imported (8 without the new object), and the cctz::detail::FormatTM and Aws::Utils::DateTime::ToGmtString calls branch to the in-binary _strftime (dyld stub without it). On x86_64, CI's own binary already binds this force-loaded archive's pthread_rwlock_* definitions. All 16 names are exported unsuffixed by libsystem_c for arm64 and x86_64, and a failed lookup aborts at server start, so Fast test (arm_darwin) is the runtime check.
3 💡 The recursive-mutex comment overstates signal-handler safety AGREE Comment narrowed in a comment-only commit: recursion only avoids a self-deadlock on this mutex.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-10:20261012-092400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Not at runtime: there is no macOS host here, and the hang needs libc's time zone writer path, which no query can trigger. The hung state is in the lldb dump of the failing job (3 waiters in _st_tzset_basic, no holder). Deterministic proof of the mechanism instead: a same-tree arm64 Darwin relink with and without the new object (next rows). Fast test (arm_darwin) on this PR is the runtime check.
b Root cause explained? macOS libc takes a private psynch pthread_rwlock (lcl_rwlock) in strftime, localtime(_r), mktime, strptime, tzset and others. A psynch rwlock waiter interrupted by a signal can miss its wakeup and wait forever (FB24027930), and the macOS query profiler signals every registered thread. The pthread_rwlock_* replacement from #112267 cannot reach this lock: libsystem_c binds it to libpthread through the two-level namespace.
c Fix matches root cause? Yes. Every in-binary call into those 16 libc functions is serialized by one mutex, so no thread of ours ever waits on the defective lock. Libc's own lock is not replaced (it is not ours, the same rule as #112267). No timeout, retry or signal masking.
d Test intent preserved / new tests added? No in-tree test, as for #112267: Darwin-only link-level code, no Darwin unit-test job in CI, and the trigger is not reachable from SQL, so a stateless test could only be a probabilistic hang detector.
e Both directions demonstrated? Yes, at the binding level on the same tree. Without the object, the binary imports 8 of these functions from libSystem, and the cctz::detail::FormatTM and Aws::Utils::DateTime::ToGmtString calls go through the dyld stub. With it, it imports 0, and both call _strftime defined in the binary. The CI binary of #117253 matches the "without" side.
f Fix is general across code paths? Yes. All 16 public entry points that take the lock are wrapped, not only the 3 call sites in the dump, so the ~20 contribs that call them are covered. Not covered: calls made inside Apple frameworks, the same boundary as #112267. Functions that take no time zone lock (gmtime(_r), timegm, asctime(_r)) are left alone.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for types. Checked on both Darwin architectures: arm64 is built and linked, x86_64 is compiled with -Wall -Wextra -Wpedantic -Werror. TSan Darwin builds still exclude darwin-compatibility. Other platforms are unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or protocol change.
i Invariants and contracts preserved? errno reaches the caller as with a direct call: it is saved and restored around the mutex, because a contended macOS mutex can leave EINTR. The mutex is a leaf: only libc runs under it, so it cannot form a lock-order cycle with ClickHouse mutexes. It is recursive, for a signal handler on a thread already inside. dlsym runs before the lock is taken.

Session id: cron:clickhouse-impl-slot-5:20261012-083600

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fc33df0]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL IGNORED

AI Review

Summary

This PR extends the Darwin compatibility shim by force-loading wrappers around the libc strftime/strptime/localtime/mktime/tzset family so calls from ClickHouse binaries are serialized before they enter macOS libc's private time-zone pthread_rwlock, preventing the permanent hang reported in Fast test (arm_darwin). I reviewed the current diff, PR metadata, prior discussion, and the relevant Darwin libc call sites; the wrapper set matches the lock-taking public entry points, the CMake wiring is consistent with the existing pthread_rwlock interposition, and I did not find a remaining correctness or safety issue in the changed code.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-build-system Build system (CMake, compilation, platform builds). label Oct 12, 2026
@Algunenano Algunenano self-assigned this Oct 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fc33df08e with master 8503774e7 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fc33df0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Finish Workflow / Post Hooks new_tests_check.py: No new tests have been added. This is a Bug Fix without a test, as disclosed in the description: the shim is macOS-only and Bugfix validation runs on Linux, so no CI test can satisfy the hook PR-caused by design and owned by this PR (#125369): the resolution is the reviewer's decision to merge over the hook or to change the category

Fast test (arm_darwin), the only CI job that runs the shim, passed (13088 tests OK, 0 failed). Every other check is green or skipped, and CH Inc sync succeeded.

Session id: cron:clickhouse-maint-slot-15:20261012-204200

@Algunenano Algunenano left a comment

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.

I've been talking with Claude about alternatives to avoid playing this whack-a-mole game with Apple's libraries (BTW, they've never replied to the original ticket), and maybe we could replace sampling on Darwin and not use signals.

I think I'll just merge this to reduce the impact (but it's likely some other functions will appear and cause troubles) and experiment with a different sample.

@Algunenano
Algunenano added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit bb844df Oct 13, 2026
175 of 178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 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 comp-build-system Build system (CMake, compilation, platform builds). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants