Skip to content

Fix a crash at shutdown when a static still owns an S3 client - #133151

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:s3-client-cache-registry-never-destroyed
Nov 20, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:s3-client-cache-registry-never-destroyed

Conversation

@groeneai

@groeneai groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

Fixes a crash at server shutdown when keeper_server.s3_snapshot is added by a configuration reload while Keeper OpenTelemetry tracing (opentelemetry_start_keeper_trace_probability) is enabled.

Description

On 26.3.63.123 and 26.8.37.168 (official images) and on master, a server with embedded Keeper, opentelemetry_span_log and opentelemetry_start_keeper_trace_probability = 1 exits with SIGSEGV at shutdown after keeper_server.s3_snapshot is added by SYSTEM RELOAD CONFIG. An ASan+UBSan build reports:

unique_ptr.h:545:12: runtime error: applying non-zero offset 8 to null pointer
DB::S3::ClientCacheRegistry::unregisterClient <- DB::S3::Client::~Client <- ~KeeperSnapshotManagerS3
<- ~KeeperDispatcher <- std::shared_ptr<DB::KeeperDispatcher>::~shared_ptr <- __funcs_on_exit <- exit

~S3::Client unregisters from ClientCacheRegistry, a function-local static. Statics are destroyed in reverse order of construction, so a client owned by a static constructed before the registry is destroyed after it, and unregisterClient searches a destroyed unordered_map. Here the owner is the KeeperDispatcher cached in a static in KeeperSpans.cpp (built by the first traced Keeper request): it keeps snapshot_s3 and its client alive until exit, while the reload creates the process's first S3 client, and so the registry, after it.

The registry is now never destroyed, the idiom of UntrackedMemoryRegistry (#120386). It stays reachable through the static pointer, so LSan does not report it. Fixing the registry rather than the KeeperSpans cache covers every static owner of a client, including transitive ones.

Validation: the server scenario below exits 139 on master, 26.3 and 26.8 (an ASan+UBSan master build exits 134 with the report above) and 0 with the fix; without the reload, or with Keeper tracing off, 26.8 exits 0. No public issue or CI report exists.

Server reproduction
  1. Embedded Keeper (one node) with <zookeeper> pointing at it and <pass_opentelemetry_tracing_context>1</pass_opentelemetry_tracing_context>; opentelemetry_span_log configured; default profile opentelemetry_start_trace_probability = 1, opentelemetry_start_keeper_trace_probability = 1; no S3 disk, table or collection.
  2. SYSTEM RECONNECT ZOOKEEPER, then a ReplicatedMergeTree CREATE and INSERT (spans carrying raft.role appear in system.opentelemetry_span_log).
  3. Add <keeper_server><s3_snapshot><endpoint>http://127.0.0.1:1/snapshots/</endpoint><access_key_id>x</access_key_id><secret_access_key>y</secret_access_key></s3_snapshot></keeper_server> and run SYSTEM RELOAD CONFIG (KeeperSnapshotManagerS3: S3 client was updated; the endpoint is never contacted).
  4. Stop the server with SIGTERM: master exits 139 after Application: shutting down; with this PR it exits 0.

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

Version info

  • Merged into: 26.12.1.99-master (included in 26.12 and later)

@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; 1 finding, 0 on the re-run) plus my own cold review (1 finding).

# Sev Finding Verdict Evidence / action
1 💡 Classify the crash as Critical Bug Fix DISAGREE The crash needs a configuration reload that adds keeper_server.s3_snapshot while Keeper tracing is on, and happens only at shutdown; Bug Fix fits (exit 139 on 26.3.63.123 and 26.8.37.168)
2 💡 Changelog entry should be in the present tense (docs/changelog_entry_guidelines.md) AGREE, fixed Entry now starts with "Fixes"
3 💡 The comment in ClientCacheRegistry::instance() says a static's client can "outlive static destruction"; it is destroyed after the registry, during static destruction AGREE, noted-not-blocking Comment wording only

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

Session id: cron:clickhouse-review-slot-9:20261120-070505

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @zvonand, could you review this? ClientCacheRegistry was a destructible function-local static, so an S3 client owned by a static built before it (the KeeperDispatcher cached in KeeperSpans.cpp, when keeper_server.s3_snapshot arrives by a config reload) unregistered from the destroyed registry at exit; the registry is now never destroyed, the UntrackedMemoryRegistry idiom.

@groeneai

groeneai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The server scenario in the description exits 139 on master, 26.3.63.123 and 26.8.37.168; an ASan+UBSan master build exits 134 with unique_ptr.h:545:12: runtime error: applying non-zero offset 8 to null pointer.
b Root cause explained? ~S3::Client unregisters from ClientCacheRegistry, a destructible function-local static. A static that owns a client before the registry is first built (the KeeperDispatcher cached in KeeperSpans.cpp, when the S3 snapshot client arrives by a reload) is destroyed after the registry, and unregisterClient searches a destroyed unordered_map whose bucket array is null while its bucket count is kept.
c Fix matches root cause? Yes. The registry must outlive every registrant, and registrants can be owned by arbitrary statics, so the registry is now never destroyed (the UntrackedMemoryRegistry idiom). No guard at the crash site, no reordering of statics.
d Test intent preserved / new tests added? No new test: the death test was removed at the reviewer's request. No existing test changed.
e Both directions demonstrated? Yes. Server scenario: exit 139 on master (134 under ASan+UBSan), 0 with the fix.
f Fix is general across code paths? Yes. Every registry access goes through instance(), so both Client constructors, ~Client, getOrCreateCacheForKey (Keeper, backups, disks) and clearCacheForAll are covered. The other registries unregistered on teardown are already immortal (UntrackedMemoryRegistry) or unregistered in shutdown() during context shutdown (StreamingStorageRegistry).
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for data types (object lifetime). Any static owner, at any ownership depth, is covered because the fix is on the registry side.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or runtime behaviour change; only the registry is no longer freed at process exit.
i Invariants and contracts preserved? Yes. Register/unregister refcounting is unchanged (ClientCacheRegistryRefcount passes); the mutex and maps outlive every caller; ~Client's error handling is unchanged; LSan treats the object as reachable.

Session id: cron:clickhouse-impl-slot-6:20261120-051205

@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [15e8723]

Summary: ✅


AI Review

Summary

The change keeps S3::ClientCacheRegistry alive until process exit, allowing clients retained by static owners, including KeeperDispatcher, to unregister safely during shutdown. No actionable findings at 15e8723d44dbe7ade85d1d26eb7319f8964ca878. The PR documents failing and passing server reproductions; removal of the dedicated lifetime test was explicitly requested by a maintainer.

Missing context / blind spots
  • ⚠️ No build or runtime tests were run locally; runtime evidence comes from the reported reproductions. The CI finish report records the missing-new-tests check and an earlier review-threads gate failure that skipped the full suite. The sole current thread is resolved, but this report does not establish a passing full-suite run.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors labels Nov 20, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Nov 20, 2026
@azat
azat requested a review from kssenii November 20, 2026 08:38
@clickhouse-gh

clickhouse-gh Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 15e8723d4 with master 22d16f0a8 (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

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

Job report

Comment thread src/IO/S3/tests/gtest_aws_s3_client.cpp Resolved
`S3::Client::~Client` unregisters from `ClientCacheRegistry::instance()`,
which was a destructible function-local static. Statics are destroyed in
reverse order of construction completion, and the registry is built by
the first S3 client of the process. A static that already owned an S3
client before that point is destroyed after the registry, and its
`~Client` then calls `find` on a destroyed `unordered_map`: libc++ frees
the nodes and nulls the bucket array but keeps `bucket_count`, so `find`
loads from `nullptr + 8 * idx` (SIGSEGV; UBSan "applying non-zero offset
8 to null pointer" at unique_ptr.h:545).

Such an owner exists: `ZooKeeperOpentelemetrySpans::maybeFinalizeImpl`
caches `static const auto keeper_dispatcher = getKeeperDispatcher();`, a
strong reference that keeps `KeeperDispatcher::snapshot_s3` and its
`S3::Client` alive until static destruction. With Keeper tracing on, the
static is built by the first traced Keeper request; adding
`keeper_server.s3_snapshot` by a configuration reload then creates the
first S3 client, and so the registry, after it. Measured: the official
26.3.63.123 and 26.8.37.168 images and master exit with SIGSEGV at
shutdown; without the reload, or with Keeper tracing off, they exit 0.

Allocate the registry once and never delete it, as
`UntrackedMemoryRegistry::instance()` does for the same hazard. It stays
reachable through the static pointer, so LSan does not report it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai
groeneai force-pushed the s3-client-cache-registry-never-destroyed branch from 49ddd02 to 15e8723 Compare November 20, 2026 09:28
@azat azat added the ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads label Nov 20, 2026
@azat
azat enabled auto-merge November 20, 2026 12:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 15e8723

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) expected for this PR: it carries pr-bugfix and ships no test, because the regression test was removed on review request (r4640320972); the hook accepts that only with the ci-skip-new-tests-check label, which I cannot add PR-caused by design and owned by this PR (#133151): the resolution is the ci-skip-new-tests-check label
Mergeable Check, PR praktika rollups of the row above PR-caused by design and owned by this PR (#133151): the resolution is the ci-skip-new-tests-check label

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261120-143035

@alexey-milovidov alexey-milovidov added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Nov 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 20, 2026
Merged via the queue into ClickHouse:master with commit 4aa16c6 Nov 20, 2026
765 of 768 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 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-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. ignore-unresolved-threads Do not limit CI and block merge on unresolved review threads pr-improvement Pull request with some product improvements 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.

5 participants