Skip to content

Read the global settings under a lock in Context::getReadSettings - #115659

Merged
serxa merged 10 commits into
ClickHouse:masterfrom
groeneai:tsan-context-settings-race
Oct 1, 2026
Merged

serxa merged 10 commits into
ClickHouse:masterfrom
groeneai:tsan-context-settings-race

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Related: #62025

Description

Context::getReadSettings() reads dozens of settings through getSettingsRef(), an unsynchronized inline accessor, while the writers on that path hold the exclusive Context::mutex - a missing reader-side lock (the checkSettingsConstraints/clampToSettingsConstraints overloads are the exception, disclosed below). getWriteSettings() has the same shape, and the four throttler getters read their bandwidth setting the same way. Two of those settings are SettingFieldString, and the getter holds a std::string_view into the heap String while a concurrent assignment can reallocate it, so the consequence exceeds a torn scalar.

setDefaultProfiles() was the other half: applySettingsQuirks, adjustSettingsForMakeDistributedPlan and doSettingsSanityCheckClamp ran after setCurrentProfile released the mutex, so a reader-side lock alone would exclude nothing.

Free getReadSettings() falls back to the global context when there is no query context - the documented system_profile path for background work - so a background thread opening a file during startup reaches it. The report came from a Keeper changelog reader racing setDefaultProfiles, but the defect is in Context.

Both getters now take a shared lock over the settings extraction and release it before the calls that follow, because this mutex cannot be upgraded and the throttler getters re-enter it exclusively. The four bandwidths the throttler getters need are read in that region and passed in, so a short read query adds 2 shared acquisitions rather than 6; the getters still read them themselves for system.server_settings. setDefaultProfiles' trailing mutations move under the exclusive lock. The effective settings a server reports are byte-identical before and after.

Scope is narrow: it makes the reported pair race-free, not all access to the global settings. Still unsynchronized and not addressed here: the five checkSettingsConstraints/clampToSettingsConstraints overloads reaching doSettingsSanityCheckClamp under a shared lock only, reloadClusterConfig and setClustersConfig, getBackupsThrottler, and 29 sites outside Context reading the global settings via getSettingsRef.

Provenance and validation

Issue #62025 reports this same race, also on a String setting; it was closed by #62309, which reordered one clickhouse-local caller and left the accessor unsynchronized. This report is from an internal ThreadSanitizer stress run, with no public CIDB hits for the stack in 90 days: it is rare, and the argument is the mechanism.

Two tests in the existing gtest_context_race.cpp, neither carrying signal outside ThreadSanitizer. GetReadSettingsRace: reader threads calling both getters against a writer changing a String setting and an integer one; it reports on the unpatched tree in 3 of 3 runs, naming getReadSettings as the read and setSettingWithLock as the write, and is silent in 5 of 5 with the fix. SetDefaultProfilesRace covers the other half, where the trailing pass is the unlocked reader. Every lock added is pinned by an arm that deletes it and requires the matching test to report: getReadSettings' own, getWriteSettings' own (driven through s3_allow_parallel_part_upload, which only that getter reads), setDefaultProfiles', and the throttler getters'. The last of those is why the readers also call the four throttler getters directly: with the bandwidth arriving as an argument from the two settings getters, deleting all four of those locks left the test silent.

Since this locks a hot accessor, deadlock was the main concern. Context::mutex is private and no Context method calls either getter, so there is no reverse entry, and the callees inside the locked region do not take it. Dynamically, a server with embedded Keeper and all four bandwidth settings non-zero, so the throttler getters reach their exclusive branch, served 263,251 queries at 2920 QPS under mixed load with no hang.

Also green under ThreadSanitizer: Context.* (9), Coordination* (43), Threading.*SharedMutex* (12), and the Keeper suites test_keeper_and_access_storage (which guards the startup ordering setDefaultProfiles takes part in), test_keeper_session, test_keeper_incorrect_config, test_keeper_block_acl. An alternating A/B benchmark showed no measurable throughput change (base 3464 QPS, patched 3520, overlapping ranges).

Added locking is countable, since lockSharedImpl increments ProfileEvents['ContextLock']. On one Debug tree, three arms round-robined by restart with the Build ID asserted on each start, three repetitions per cell and every triple identical: SELECT 1 19 -> 19 -> 19, a primary-key point read 38 -> 44 -> 40, a small range scan 47 -> 53 -> 49, for master, the first revision of this PR, and the current one. SELECT 1 never reaches the getters, so it is the null control. QPS on short concurrent queries was measured separately at -0.46% (8 cores, c=24) and +1.66% (32 cores, c=192) net of that control, against -14.7%/-60.2% for a calibration arm with 100x the acquisitions.


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

Version info

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

Context::getReadSettings() read about 130 settings through getSettingsRef(),
an unsynchronized inline accessor, while every writer of those fields holds
Context::mutex exclusively. That is a missing reader-side lock, not an unlocked
writer. Context::getWriteSettings() had the identical shape, and the four query
throttler getters read their bandwidth setting the same way.

Two of the settings on that path (local_filesystem_read_method,
remote_filesystem_read_method) are SettingFieldString, and the getter holds a
std::string_view into the heap String while a concurrent assignment can
reallocate it, so the consequence is worse than a torn integer. A background
thread has no query context, so free getReadSettings() resolves to the global
context - the documented system_profile path for background work - which is the
object a settings change mutates. The report this comes from was a Keeper
changelog reader racing setDefaultProfiles at server startup.

setDefaultProfiles() was the other half: applySettingsQuirks,
adjustSettingsForMakeDistributedPlan and doSettingsSanityCheckClamp ran after
setCurrentProfile had released the mutex, so locking only the reader would have
excluded nothing.

Both getters now take a shared lock over the settings extraction and release it
before the cache and throttler getters, which take the same mutex exclusively;
ContextSharedMutex cannot be upgraded, so the release is required rather than
stylistic. The throttler getters' own bandwidth reads are synchronized the same
way, and setDefaultProfiles' trailing mutations move under the exclusive lock.
There is no behavior change: the effective settings a server reports are
byte-identical before and after.

Scope is deliberately narrow. Still unsynchronized and not addressed here: the
five checkSettingsConstraints/clampToSettingsConstraints overloads that reach
doSettingsSanityCheckClamp holding only a shared lock, reloadClusterConfig(),
getBackupsThrottler(), and nine call sites outside Context that read the global
settings directly.

Issue ClickHouse#62025 reports this same race on getReadSettings, also on a String
setting. It was closed by ClickHouse#62309, which reordered one clickhouse-local caller
and left the accessor itself unsynchronized.

The added test only carries signal under ThreadSanitizer: it reports the race on
the unpatched tree in 3 of 3 runs and is silent in 5 of 5 runs with the fix.
ThreadSanitizer reports races per memory address. The test only mutated
local_filesystem_read_method and s3_allow_parallel_part_upload, which are
distinct struct members from the four bandwidth settings the throttler
getters read, so deleting all four of the throttler getters' shared locks
left the test green. Only 1 of the 5 synchronization sites was pinned.

The writer now also toggles all four bandwidths, and all four are armed
non-zero at setup. Each of the five locks is now load-bearing: deleting
any one of them in isolation makes the test report a race naming that
exact function, at five distinct addresses.

Both write-side bandwidths being armed also means getWriteSettings'
release-before-exclusive structure is exercised, not just present.

The test comment previously claimed that every writer of the settings
block holds Context::mutex exclusively. That is not true: the
checkSettingsConstraints and clampToSettingsConstraints overloads hold
only a shared lock and still reach doSettingsSanityCheckClamp, which
writes settings. Narrowed to the writers this test actually exercises.
…e test

The change added six independently-deletable synchronization sites: the two
getters, the four throttler getters, and the exclusive scope over
setDefaultProfiles' trailing settings pass. The first five were each pinned by
their own mutation arm; the sixth had none, so removing that lock left every
test green.

setDefaultProfiles calls setCurrentProfile first, which under the exclusive
lock already runs applySettingsQuirks, adjustSettingsForMakeDistributedPlan
and doSettingsSanityCheckClamp. All three are idempotent, so on a resolved
profile the trailing pass re-runs them over already-normalized settings: it
reads the settings block and writes nothing. The racing side of the new test
is therefore a set of writers holding Context::mutex, not more readers, which
would only have produced a read-vs-read pair that ThreadSanitizer cannot see.

With the lock removed the test reports on max_read_buffer_size_local_fs, read
side inside setDefaultProfiles via doSettingsSanityCheckClamp and write side
inside setSettingWithLock. With the lock in place it is silent in five of five
runs, and the Context suite is green in declaration and shuffled order.

The fixture needs a resolvable profile: the unit-test AccessControl has no
storage, so setCurrentProfile would fail to look up 'default'. The config
omits background_profile so makeBackgroundContext reuses the system profile.
That function asserts on a process-wide static, so this is the only test in
the binary that may call setDefaultProfiles.

Also corrects two counts in the description that were wrong and cheap to
check: the getter reads 51 settings rather than about 130, and 27 sites
outside Context read the global settings unsynchronized rather than nine.

No change to src/Interpreters/Context.cpp.
…ings

The comment said the lock is released before "the cache and throttler
getters, which take it exclusively". That is true of the four throttler
getters but false of getPageCache() and getMMappedFileCache(), which take
ContextSharedPart::mutex, a different mutex, in shared mode.

Both calls still belong outside the settings lock, for two reasons now
stated: the throttler getters re-enter this mutex exclusively and it
cannot be upgraded, and holding it across a shared->mutex acquisition
would introduce a lock-order edge between the two mutexes where the file
currently has none in either direction (verified across all 68 bare-mutex
acquisition sites: the four functions that take both take them strictly
sequentially, every scope closing before the next opens).

Comment only. Code is token-identical.
The comment on the shared lock in Context::getReadSettings claimed the cache
getters take `shared->mutex`, "never held together with it". That is false:
Context::mutex is held across a shared->mutex acquisition on 14 paths, all
reaching it through getAccessControl - setUser, setSetting, setCurrentProfile,
setCurrentProfiles, applySettingsChanges, the five checkSettingsConstraints and
clampToSettingsConstraints overloads, checkMergeTreeSettingsConstraints and
getSettingsConstraintsAndCurrentProfiles. Nothing takes them in the reverse
order, so ctx -> shared is the established order in this file, and keeping the
cache getters outside the lock avoids no lock-order edge.

An earlier revision of the same comment was wrong in a different way, claiming
the cache getters take this mutex exclusively. Both wrong reasons came from
measuring lexically inside single function bodies, which cannot see a mutex
reached through a callee.

The code placement is correct and unchanged. The comment now claims only what
one command at the call site can check: the mutex cannot be upgraded, the four
throttler getters below re-enter it exclusively (Context.cpp:5644, :5673,
:5698, :5723), and nothing after the unlock reads this function's settings_ref
(last use :8634, unlock at :8638). The narrower phrasing matters because the
throttler getters do read settings under their own lock, so a blanket "the
calls after the unlock read no settings" would have been wrong again.

getWriteSettings' comment is untouched: that function calls no cache getter,
so it was already accurate.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Aug 20, 2026
@groeneai

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

Reviewed independently across 4 rounds by a second model plus a cold code review, adjudicated
against the recorded evidence. Findings raised: 7. Fixed: 2. Rejected with evidence: 3.
Final round: 0 findings from either reviewer.

# Finding Verdict
❌ The in-code comment (and the description) asserted that Context::mutex and shared->mutex are never held together. False in the forward direction: 14 methods hold Context::mutex across a shared->mutex acquisition, through getAccessControl and getSettingsConstraintsAndCurrentProfilesWithLock. Raised twice. Agreed, fixed. The comment now states only what is checkable at the site: this mutex cannot be upgraded, the throttler getters re-enter it exclusively, and nothing after the unlock reads the settings reference. Same correction applied to the description.
❌ The first cold review had certified that claim as accurate, having measured nesting only within single function bodies rather than through callees. Agreed, retracted. The transitive measurement gives 14 forward nestings; the claim is gone from the code and from the description.
⚠️ getBackupsThrottler() reads its bandwidth setting with the same missing lock. Not changed here. Its only callers are in BackupsWorker, so it is unreachable from either getter and from the reported path. Named in the description's scope paragraph rather than folded in, to keep this a lock-placement change.
⚠️ makeQueryContextForMerge / ForMutate write the workload setting unlocked. Not changed here. All six callers write to a task-local context they have just created and not yet shared, and no input was found that races it.
💡 Four comments in Context.cpp reference getLocalLock / getGlobalLock accessors that no longer exist. Not changed here. Documentation rot with no runtime effect. Their absence was verified directly, since a reader could otherwise believe the mutex is lockable from outside Context.

Deadlock was the main risk of locking a hot accessor, so it was checked from four sides:
the locked region contains only settings reads; no Context method calls either getter;
Context::mutex is private with no accessor, so no caller can already hold it; and
Context::mutex is never co-held with shared->mutex on this path in either order. The
setDefaultProfiles scope deliberately excludes setCurrentProfile above it and
createCopy below it, both of which take the same non-recursive mutex themselves.

Session id: cron:clickhouse-review-slot-10:20260820-174200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. TEST(Context, GetReadSettingsRace) under ThreadSanitizer: taskset -c 0-15 build-tsan/src/unit_tests_dbms --gtest_filter='Context.GetReadSettingsRace'. Reports the race in 3 of 3 runs on the unpatched tree, silent in 5 of 5 with the fix. Context.SetDefaultProfilesRace does the same for the setDefaultProfiles half.
b Root cause explained? Yes. Context::getReadSettings() reads 51 settings through getSettingsRef(), an unsynchronized inline accessor, while every writer of those fields holds the exclusive Context::mutex: a missing reader-side lock. Two of the settings it reads are SettingFieldString and the getter holds a std::string_view into the heap String, so a concurrent assignment can reallocate under it. Separately, setDefaultProfiles() ran applySettingsQuirks / adjustSettingsForMakeDistributedPlan / doSettingsSanityCheckClamp after setCurrentProfile had released the mutex, so a reader-side lock alone would have excluded nothing.
c Fix matches root cause? Yes. It synchronizes the access at the layer that owns the data. No widened bound, no tag, no defensive check, no reduced dataset. getReadSettings reads 51 distinct settings; the 14 of them a default server configuration exercises were compared before and after on a running server: byte-identical.
d Test intent preserved / new tests added? Yes. Two tests appended to the existing src/Interpreters/tests/gtest_context_race.cpp (no new file); the 7 tests already there still pass, and the suite is green shuffled as well as in declaration order. No test weakened or removed. Each test states its ThreadSanitizer-only nature in its comment rather than implying it. This change adds seven locks in seven functions; six are pinned by their own mutation arm (deleting any one of them makes the matching test report a race naming that exact function, at six distinct addresses). The seventh is getWriteSettings' own lock, exercised by the same test through s3_allow_parallel_part_upload, a setting only it reads.
e Both directions demonstrated? Yes. Base binary (build-id 6936e6830eb51d80…): 2 races, naming Context::getReadSettings as the read and Context::setSettingWithLock -> SettingsImpl::set as the write. Patched binary (999f66a8a38ad67e…): 0 races. Both binaries retained. Per-site direction as well: with the setDefaultProfiles lock deleted the new test reports on max_read_buffer_size_local_fs, read side naming Context.cpp:7677; restored, 5 of 5 silent, with the build-id returning to its pre-arm value.
f Fix is general across code paths? Yes. getWriteSettings() is fixed symmetrically, and all four query throttler getters are fixed, not only the two on the reported read path. The fifth sibling with the same shape, getBackupsThrottler(), was enumerated and shown not to be reachable from either getter (only BackupsWorker calls it, which requires a BACKUP query); left alone deliberately rather than widening the PR, and disclosed in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A by shape: a lock scope has no input matrix. The equivalent was still done: the test exercises both a String setting (the reallocation-shaped variant) and an integer one, and the throttler branch is covered both taken (bandwidth non-zero) and not taken (default 0).
h Backward compatible? Yes. No setting added and no default changed, so no SettingsChangesHistory.cpp row is required (verified: 0 added DECLARE(). No serialization or format change, no public API change, no user-visible behavior change.
i Invariants and contracts preserved? Yes. ContextSharedMutex is not recursive and cannot be upgraded, so the shared lock is released before any call that re-enters it: the four throttler getters each take it exclusively (Context.cpp:5644, :5673, :5698, :5723), and no other call after the unlock takes it. setDefaultProfiles takes one exclusive scope that excludes setCurrentProfile, which locks itself. No reverse entry exists: Context::mutex is private to Context (Context.h:762), and across all 627 method bodies no call to a cache or throttler getter happens while it is held (mutation-controlled: injecting one such call inside the locked region makes the scan report it). Release on exception paths is by RAII. Deadlock also checked dynamically with all four bandwidth settings non-zero so the throttler getters reach their exclusive-lock branch: 263,251 queries at 2920 QPS under mixed read, write and replicated-insert load with no hang, and non-zero throttler byte counters proving the branch was taken. The documented system_profile-for-background-threads contract is untouched.

Session id: cron:clickhouse-impl-slot-40:20260820-172300

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [95e1f14]

Summary: ✅


AI Review

Summary

This PR adds reader-side locking around Context::getReadSettings / getWriteSettings, threads the bandwidth values through the throttler helpers to avoid extra lock acquisitions, and moves the trailing setDefaultProfiles sanity pass back under Context::mutex. The main race fix looks reasonable, but the new SetDefaultProfilesRace gtest still mutates shared fixture state and does not restore it, so I would not merge it as-is.

Findings

⚠️ Majors

  • [src/Interpreters/tests/gtest_context_race.cpp:357] SetDefaultProfilesRace still shares the process-global ContextSharedPart from getContext().context, but its teardown only repairs AccessControl. After context->setDefaultProfiles(*config), the shared default / system / background / buffer profile-name fields stay mutated even though the temporary default profile is removed in the scope guard. That leaves later code able to observe getSystemProfileName() == "default" and then fail in setCurrentProfile("default"), making unit_tests_dbms order-dependent. Suggested fix: either run this test on an isolated global-context lifecycle, or extend the cleanup so it restores the shared profile-name fields together with the AccessControl state.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Make SetDefaultProfilesRace leave no shared global-fixture state behind before the test returns.

LLVM Coverage Report

Measured on commit 95e1f14.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 93/93 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @serxa, could you review this? Context::getReadSettings() and getWriteSettings() read the settings block through the unsynchronized getSettingsRef() while every writer on that path holds Context::mutex exclusively, so this adds the missing reader-side shared lock (released before the throttler getters, which re-enter the mutex exclusively) and moves setDefaultProfiles()' trailing settings pass under the lock.

Context::createCopy shares the fixture's ContextSharedPart, so the memory
storage and the `default` profile that SetDefaultProfilesRace inserts stayed
visible to the rest of unit_tests_dbms after the test. A later insert of a
`default` profile then failed with "cannot insert because settings profile
`default` already exists in `test_memory`". Reproduced by running the test
twice in one process; verified load-bearing by removing the cleanup again,
which restores the failure.

The cleanup clears the default profile name, removes the profile through
AccessControl::remove, then drops the storage. All three are needed:
MultipleAccessStorage::removeStorage sends no entity-removal notification and
that notification is what evicts the profile from the process-shared
SettingsProfilesCache, and removing the entity does not reset the cached
default profile id, which is otherwise still merged into every later
enabled-settings computation.

The other half, the process-global background_context_instance that
makeBackgroundContext consumes, is a ContextData class static rather than a
ContextSharedPart member, so it does not depend on how the test obtains its
Context. The test already documents that setDefaultProfiles can succeed at
most once per binary, and CI runs the binary once with no --gtest_repeat.

Reported by clickhouse-gh[bot] on ClickHouse#115659.
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 95e1f14df with master 8dc18243e (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3869162

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
Bugfix validation (unit tests) harness aborted inconclusive: submodule state differs between the merge-base and the checkout (contrib/aws-c-http), so the before-worktree cannot be populated at the merge-base revisions a fix task is created (fixing-PR link to follow on this PR)

Measured on the deduped check set (newest attempt per name): 172 unique names, 0 incomplete,
1 failure, the rest success or skipped. The raw check-run list matched total_count, so nothing
was silently truncated. Finish Workflow completed success.

Not a void run: Config Workflow = success and Style check = success.

The failing check is the validation harness reporting that it could not run, not a test verdict.
Its own message says so: "This is inconclusive - NOT a reproduction or a refutation." CIDB
carries 300,364 rows at this commit with 0 FAIL/ERROR; the only row for this check is a
job-level error with no test result attached.

I disambiguated the harness's own "either the PR changes submodule state, or the base branch
moved a submodule after the branch split" rather than accepting it:

  • This PR changes no submodule. Its diff is two files, src/Interpreters/Context.cpp and
    src/Interpreters/tests/gtest_context_race.cpp, and contains zero contrib/ paths.
  • Master moved it. contrib/aws-c-http was touched on master at 6d3cf8d9dc89
    (2026-08-20T09:02:04Z), after this branch split.

So this is base-branch drift in the validator, independent of the change under review, and it is
the pre-existing harness limitation already tracked with a fix task rather than a defect in this
PR. No Bugfix validation inversion applies here either: an inversion is test_status=FAIL with
the check concluding success, whereas this check never produced a test row at all.

Session id: cron:our-pr-ci-monitor:20260821-023000

The one conflict was the write_through_distributed_cache assignment in
Context::getWriteSettings. Master replaced the direct settings reads in both
getters with resolveReadThroughDistributedCache and
resolveWriteThroughDistributedCache, and master's version of that region still
had the two throttler assignments that this branch moves below the unlock, so
neither side could be taken whole.

Resolved additively: master's resolve call stays where master put it, inside
the locked region, and the throttler getters stay after lock.unlock(). Taking
master's side verbatim would have duplicated the throttler assignments and put
them back under the shared lock, which hangs, because all four throttler
getters re-enter Context::mutex exclusively and the mutex is not recursive.

Keeping the resolve call inside the lock is deliberate rather than incidental.
It reads getSettingsRef()[force_read_through_distributed_cache] on the
non-global path, so moving it after the unlock would add a new unsynchronized
read of the settings block on the exact path this change exists to
synchronize. The call also reaches getReadThroughDistributedCache and
getWriteThroughDistributedCache, which take shared->mutex, so the locked
region now nests shared->mutex inside Context::mutex. That direction is
already established in this file: 15 paths hold Context::mutex across a
shared->mutex acquisition, several with the outer lock held exclusively, and
nothing takes the two in the reverse order.

getReadSettings merged without a conflict and got the same shape.
gtest_context_race.cpp is unchanged on master, so its pre-existing tests
merged untouched.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 04c9964

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
Bugfix validation (unit tests) harness limitation, not a refutation: the before-binary is pinned to ASan+UBSan (ci/jobs/unit_tests_bugfix_validation_job.py:59) and both added gtests state they carry signal only under ThreadSanitizer (gtest_context_race.cpp:251, :332), so they pass on it by construction (fail: 0, passed: 9) a fix task is created (fixing-PR link to follow on this PR)
Finish Workflow / Post Hooks downstream of the row above: new_tests_check.py turns that FAIL into a hook failure same fix task
CH Inc sync pending CH Inc sync (private, not actionable by me)

Mergeable Check and PR are aggregate statuses rolling up the same two failures, not separate ones.

175 check-runs at this commit, 0 incomplete, 2 failures, the rest success or skipped.
Finish Workflow completed. Config Workflow and Style check are both green, so this is not a void
run, and the parent workflow run concluded failure with zero cancelled jobs, so no check silently
skipped its work. CIDB holds 304,101 rows at this commit with exactly 1 FAIL/ERROR, the
Post Hooks row above.

The validator requires a newly added test to fail on the merge-base binary. That binary is never
built with ThreadSanitizer and these tests detect a data race, so the requirement is unsatisfiable
for any TSan-only test. new_tests_check.py already exempts an inconclusive validator run from
blocking merge (:150, :216-230); this is the same class with no branch for it. In the last 180
days 11 PRs hit this same "failed to reproduce" verdict and 6 of them merged. I am not weakening or
deleting the tests to clear the gate, and the changelog category stays Bug Fix because the race is
user-visible.

Bugfix validation (unit tests) job log

Session id: cron:clickhouse-maint-slot-13:20260826-191600

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the sanitizer-only Bugfix validation (unit tests) refutation created: #116662

That job builds the merge-base "before" binary under amd_asan_ubsan only, so the TSan race this PR fixes cannot show up there and the pass is reported as Failed to reproduce the bug. #116662 makes a clean arm escalate to a TSan arm instead of refuting, and only the last arm reports FAIL.

@serxa serxa self-assigned this Aug 27, 2026
@serxa

serxa commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

@groeneai Seems reasonable, do we have any confirmation it doesn't lead to performance degradations? Functions you have added lock to are pretty common. We should check that QPS rates for very short concurrent queries does not degrade. Can you provide a manual test results?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured. Build is RelWithDebInfo (-O3, clang-22) of this branch; the base arm is the same tree with this PR's Context.cpp change reverse-applied. Build IDs 79fc391e (base) and 75073c3c (with the lock).

How much locking is added, per query. ProfileEvents['ContextLock'] counts every ContextSharedMutex acquisition, shared ones included, so this is observable rather than argued:

query base with the lock added
SELECT 1 19 19 0
PK point read, WHERE id = 4711 38 44 +6

The shortest queries never reach getReadSettings, so they add nothing. A short read query calls the two getters twice in total, and each call adds 3 shared acquisitions: one in the getter, one in each of the two throttler getters it calls. Confirmed at scale over a 15 s, c=192 point-read run: 51.4 acquisitions per query on base against 57.4 with the lock, so +6.0.

Two things bound the cost structurally. The six added acquisitions are reader acquisitions, and the writers of that mutex are startup and profile/DDL paths, so nothing blocks in steady state. And Context::mutex is a private member of Context (Context.h:774), not of ContextSharedPart, so a query takes it on its own query context and concurrent queries do not share that cache line.

QPS. One server position (same cores, same NUMA node, same port, same data), arms round-robined by restart, server CPU-saturated so QPS tracks CPU per query. SELECT 1 is the null control, since the change adds 0 acquisitions there. I also built a calibration arm doing 100x the added locking, 300 acquisitions per getter call instead of 3.

position arm SELECT 1 point read point read net of control
8 cores, c=24 base 20457 9725
this PR 20854 (+1.9%) 9868 (+1.5%) -0.5%
100x locking 22184 (+8.4%) 9117 (-6.3%) -14.7%
32 cores / 64 threads, c=192 base 58248 31781
this PR 57397 (-1.5%) 31845 (+0.2%) +1.7%
100x locking 61902 (+6.3%) 14649 (-53.9%) -60.2%

n = 4 and 3 restarts per arm, per-arm spread under 1%. So at c=192 the harness loses 54% of point-read QPS when the same mechanism is inflated 100x, and shows nothing for the actual change. Scaling that arm down linearly bounds this PR at 0.15% (c=24) and 0.61% (c=192), and both are upper bounds because contention grows superlinearly with acquisition rate.

Lock wait under the same 15 s, c=192 load: total ContextLockWaitMicroseconds 456 ms on base against 429 ms with the lock, mean 18.4 ns against 15.5 ns per acquisition. The 11% extra acquisitions did not increase total lock wait.

Caveat, plainly: I could not resolve the change from zero. Code layout alone moves SELECT 1 by 1.5 to 8% between separately linked binaries, which is bigger than the effect being measured. The defensible claim is under 1%, most likely around 0.15%.

If you would rather not spend even that, the two bandwidth reads in the throttler getters can be hoisted into the caller's existing lock region, which removes 4 of the 6 added acquisitions and is a pure refactor of this diff. Tell me and I will push it.

@serxa

serxa commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

@groeneai Yes, let's minimize locking

…ading them

getReadSettings and getWriteSettings already hold the shared settings lock, so
the four max_*_bandwidth values the throttler getters need are read there and
passed in. That removes 4 of the 6 shared acquisitions the reader-side lock added
per short read query. Measured with ProfileEvents['ContextLock'] on one Debug
tree, three arms round-robined by restart with the Build ID asserted on each
server start: a primary-key point read goes 38 (master) -> 44 (previous revision)
-> 40, a small range scan 47 -> 53 -> 49, and SELECT 1 stays at 19 on every arm
because it never reaches the getters.

The parameter is std::optional rather than a 0 sentinel because all four settings
default to 0, which is the hot path: with a sentinel a caller-provided 0 would
re-read under the lock and remove nothing. The getters still read the setting
under their own shared lock when nothing is passed, which is the path
system.server_settings takes.

Context.GetReadSettingsRace now also calls the four throttler getters directly.
Without that their own lock is exercised by no test at all: with all four of
those locks deleted the test was silent under ThreadSanitizer, and with the
direct calls it reports again. Each getter takes the shared lock and releases it
before taking the exclusive one, so the two never overlap.

Verified on a ThreadSanitizer build: GetReadSettingsRace and
SetDefaultProfilesRace are silent, and each lock site still reports when deleted
on its own - getReadSettings', getWriteSettings', setDefaultProfiles' and the
throttler getters'. All 9 Context.* tests pass. The assertions of
02703_max_local_read_bandwidth and 02703_max_local_write_bandwidth hold
identically before and after, and read 0 when no cap is set.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa Done in 7cdb348. Each settings getter now reads the two bandwidths it needs inside the shared lock it already holds and passes them to the throttler getters, so those no longer take the lock again: added ContextLock acquisitions per short read query go from 6 to 2. Measured on one Debug build with three arms round-robined by restart, a primary-key point read is 38 (master) -> 44 (previous revision) -> 40 and a small range scan 47 -> 53 -> 49; SELECT 1 stays at 19 on all three, since it never reaches the getters. The getters still read the setting themselves when nothing is passed, which is the system.server_settings path.

That needed one test change. With the bandwidth arriving as an argument, nothing exercised the getters' own lock any more: deleting all four of them left Context.GetReadSettingsRace silent under ThreadSanitizer. The readers now call the four getters directly as well, and it reports again. Both race tests are silent with the fix, each lock site still reports when deleted on its own, all 9 Context.* tests pass, and the 02703_max_local_read_bandwidth / 02703_max_local_write_bandwidth assertions are unchanged (they read 0 when no cap is set).

Comment thread src/Interpreters/Context.cpp Resolved
@serxa

serxa commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

@groeneai ping me when you resolve all the feedback from review bots, CI is green and you think PR is ready again for human review.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7cdb348

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
Bugfix validation (unit tests) the validator builds the merge-base "before" binary under AMD_ASAN_UBSAN, where the two gtests added here report fail: 0, passed: 9; the race they pin is only observable under TSan, which aborts 5/5 without the fix. The job therefore refutes a test that build cannot observe. #116662 (mine, open)
Stress test (arm_debug) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-4e52) chronic trunk defect in the GLOBAL IN set-build path, independent of this diff. True master hit the identical STID in the identical check today at 12:43:24Z on 1b725d0b, and the same error text appears on 20 distinct pull requests in the last 6 hours. #102308 (external, open)
Finish Workflow / Post Hooks new_tests_check.py reports the Bugfix validation (unit tests) result above; not an independent failure. #116662 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260827-233000

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa Ready for review again. The bot feedback is adjudicated (#115659 (comment)) and CI has finished on 7cdb3483.

CI is not literally green: two reds remain, and neither comes from this change.

@serxa serxa 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.

Seems reasonable

@serxa

serxa commented Aug 30, 2026

Copy link
Copy Markdown
Member

Something prevents merging, check please @groeneai

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa Not a conflict: mergeable is MERGEABLE. The master ruleset requires two status checks, Mergeable Check and CH Inc sync, and 0 approving reviews. CH Inc sync is success; Mergeable Check is failure, and its description names the whole blocker: Failed: Workflow Post Hook,Stress test (arm_debug).

Workflow Post Hook is new_tests_check.py. It blocks because Bugfix validation (unit tests) reported FAIL with "all touched unit tests PASS on the before-binary (merge-base without the fix)". That job builds the merge-base binary as BuildTypes.AMD_ASAN_UBSAN (ci/jobs/unit_tests_bugfix_validation_job.py:59), and the two gtests added here assert a data race, which only TSan observes: without the fix they abort 5/5 under TSan and report fail: 0, passed: 9 under ASan+UBSan. So the validator sees them pass on the before-binary and reads that as "the test does not catch the bug". This is deterministic rather than flaky, so re-running the job reproduces it. #116662 is the fix for exactly this case, and it is open with all checks green.

Stress test (arm_debug) failed 1 of 5 runs on Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-4e52). Not from this PR: over the last 5 days that signature hit this same check on 32 distinct PRs plus master itself (master report), and this PR touches only Context.cpp, Context.h and one gtest file. #102308 is the open fix. Mergeable Check exempts a failure that matches a known open issue; this one carries no such match, so an open fix PR alone does not exempt it.

So the stress red may clear on a re-run, the post-hook red will not: clearing that one needs #116662 merged and this PR re-run on a head containing it, otherwise the merge has to go in past Mergeable Check. I have not pushed anything so far, to avoid restarting CI for nothing. Tell me which route you want and I will do my part.

auto profile = std::make_shared<SettingsProfile>();
profile->setName("default");
const UUID profile_id = access_control.insert(profile);
SCOPE_EXIT({

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.

SetDefaultProfilesRace still leaves shared fixture state behind. Context::createCopy(getContext().context) shares the same ContextSharedPart, and setDefaultProfiles() writes shared->default_profile_name, shared->system_profile_name, shared->background_profile_name, and shared->buffer_profile_name there. This teardown only restores AccessControl, so after it removes the temporary default profile later code can still read getSystemProfileName() == "default" and paths like InterpreterSystemQuery then fail in setCurrentProfile("default") depending on test order. Please either build this test on a fresh Context::createShared() / Context::createGlobal() pair, or snapshot and restore the shared profile-name fields too.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 33f5ca3

CI is fully finished at this commit. Two jobs failed, both are the same harness limitation with the same owner, and neither is a defect in this diff or in its tests.

Check / test Reason Owner / fixing PR
Bugfix validation (unit tests) / Failed to reproduce the bug. The validator builds the before-binary under AMD_ASAN_UBSAN, where a TSan-only data race cannot be observed, so the two added gtests report fail: 0, passed: 9 there and the job records a refutation. Under TSan the same tests abort 5 of 5 on the before-binary. The job is set_allow_failure(True) at ci/defs/job_configs.py:1094, so it does not gate the merge by itself #116662 (ours, open)
Finish Workflow / python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py Not an independent failure: the post hook reads the Bugfix validation (unit tests) status above and refuses on it #116662 (ours, open)

Reports:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115659&sha=33f5ca3230bb24742d670ce5c08717cf2585a1fb&name_0=PR&name_1=Bugfix%20validation%20%28unit%20tests%29

This head is @ alexey-milovidov's master merge of 2026-08-30, so the two lines above are unchanged from the previous head and are recorded here only because the ledger is keyed by commit. The changelog category stays Bug Fix, and the two gtests are unchanged.

Session id: cron:our-pr-ci-monitor:20260831-103000

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Sep 20, 2026
`Bugfix validation (unit tests)` built the merge-base "before" binary under a single
build type (`BUILD_TYPE = BuildTypes.AMD_ASAN_UBSAN`, introduced by b5abadc and
never changed) and refuted the PR's regression gtest whenever every touched test passed
on it. A regression test whose asserted property is only observable under a different
sanitizer passes on that binary either way, so `main()` reported `Result.Status.FAIL` /
"Failed to reproduce the bug." and `new_tests_check.py:220-227` turned that into a red
`Finish Workflow` for a unit-only bugfix PR. The refutation was guaranteed by
construction and independent of whether the fix and the test were correct: the run could
not observe what it was asked to judge.

This is an asymmetry with the job's own siblings, not an oversight in the abstract.
`ci/jobs/scripts/bugfix_validation.py:9-10` already validates functional/integration
tests across `[amd_asan_ubsan, amd_tsan, amd_msan, amd_debug]` and passes if any arm
reproduces. Those validators can afford four because they download prebuilt master
binaries, while this job must build each arm cold (~1h, ~0% sccache hits, documented in
`configure_before_binary`), which is why its set was never widened.

Escalate lazily instead: keep ASan+UBSan as the first arm and try the next build type
only when an arm ran every touched test with none failing. The arms share one build
directory, emptied between them fail-closed, because configuring a different `SANITIZE`
value on top of the previous `CMakeCache.txt` builds one sanitizer while the report names
another. FAIL after the last arm still blocks, preserving the contract set by
0154e71 ("only on failed-to-reproduce"), and `new_tests_check.py` is untouched.

Each arm's `Result` carries its build type, which is a correctness requirement rather
than cosmetics: `Result.from_commands_run` derives the log path from the result name
(`{TEMP_DIR}/{normalize_string(name)}.log`), so two arms sharing a name write one file
and the second overwrites the configure and compile logs of the arm that started the
escalation.

`run_gtests` now pins `external_symbolizer_path`. A sanitizer report is symbolized before
the process aborts, and with no unversioned `llvm-symbolizer` on PATH the runtime falls
back to `addr2line`, which does not finish on the multi-GB binary: measured locally, two
runs of the TSan before-binary sat at 900 s and 420 s with no output while the writer
thread held `Context::mutex` inside `Addr2LineProcess::ReadFromSymbolizer`, and with the
option set the same run aborts in 8 s with a fully symbolized report.
`ci/docker/test-base/Dockerfile` creates that symlink deliberately, but this job runs in
binary-builder, which installs `llvm-symbolizer-<version>` and symlinks only
profdata/cov/bolt/merge-fdata.

Measured on ClickHouse#115659's two gtests overlaid on a tree without its fix: the TSan
before-binary aborts on a data race between `Context::getReadSettings` and
`SettingsImpl::set` in 8-9 s, 5 of 5 runs; ASan+UBSan reports `fail: 0, passed: 9`,
matching what CI reported; with the fix applied TSan is green 3 of 3. Fed through
praktika's own runner, the aborted run yields `Result.Status.FAIL` with the crashed test
recovered as `Context.GetReadSettingsRace`, which is the reproduction branch of `main()`.
One arm took 57.7 min against the job's 240-min timeout, and 14 of 3782 `Bugfix
validation (unit tests)` rows over 180 days (0.37%) reach a second arm.

Scope: ASan+UBSan and TSan. `amd_msan` and `amd_debug` stay excluded, so a regression
test that needs one of them is still refuted by a run that cannot observe it; adding
either is a one-element change to `BEFORE_BUILD_TYPES` plus a timeout increase.

ClickHouse#96868 validated bugfixes against multiple build types eagerly and was reverted three
hours later by ClickHouse#97011. This differs by escalating lazily on a job that already builds
cold, two arms rather than five, no S3 artifact dependency, and no change to job
scheduling or `ci/defs/`.

The eight new arms in `ci/tests/test_unit_tests_bugfix_validation.py` are mutation-proven:
removing the return after a reproduction, deleting the escalation, dropping the
refutation status, escalating from the "ran no touched test" branch, making the build-dir
reset best-effort, and collapsing the per-arm result names each redden their own arm.
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Dear @serxa, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@serxa serxa self-assigned this Sep 30, 2026
@serxa

serxa commented Sep 30, 2026

Copy link
Copy Markdown
Member

@groeneai There is problem with reproducing the race so we get an error:

Failed to reproduce the bug.
Touched unit tests on the before-binary (must fail): fail: 0, passed: 9
Failed to reproduce the bug: all touched unit tests PASS on the before-binary (merge-base without the fix). The added/changed test does not catch the bug the fix addresses.

Races are not 100% reproducible bugs. I believe we can change the category to "Not for change log" to avoid CI issues and make PR mergeable.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa Changed the category to Not for changelog. Editing the description alone does not start a new CI run, so I also merged master; the new run relabeled the PR pr-not-for-changelog and skipped every Bugfix validation job, which is what the Workflow Post Hook failure in Mergeable Check came from. The merge leaves the PR diff unchanged (same patch as the head you approved), and on the merged tree Context.* passes with 0 ThreadSanitizer reports. I will tag you when the run finishes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@serxa CI on 95e1f14d finished green: every check passed, including Mergeable Check and CH Inc sync. It is ready to merge from my side.

@serxa
serxa added this pull request to the merge queue Oct 1, 2026
Merged via the queue into ClickHouse:master with commit ce2659f Oct 1, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 1, 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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet pr-not-for-changelog This PR should not be mentioned in the changelog 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.

4 participants