Repository navigation
Read the global settings under a lock in Context::getReadSettings - #115659
Conversation
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.
Internal second-model review (click to expand)Reviewed independently across 4 rounds by a second model plus a cold code review, adjudicated
Deadlock was the main risk of locking a hot accessor, so it was checked from four sides: Session id: cron:clickhouse-review-slot-10:20260820-174200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260820-172300 |
|
Workflow [PR], commit [95e1f14] Summary: ✅
AI ReviewSummaryThis PR adds reader-side locking around Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit 95e1f14.
Changed lines: Changed C/C++ lines covered: 93/93 (100.00%) · Uncovered code |
|
cc @Algunenano @serxa, could you review this? |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units1281 translation units recompiled, 8050 s compile time in total, 1281 of them have a recent master baseline. |
CI finish ledger - 3869162Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Measured on the deduped check set (newest attempt per name): 172 unique names, 0 incomplete, Not a void run: The failing check is the validation harness reporting that it could not run, not a test verdict. I disambiguated the harness's own "either the PR changes submodule state, or the base branch
So this is base-branch drift in the validator, independent of the change under review, and it is 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.
CI finish ledger - 04c9964Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
175 check-runs at this commit, 0 incomplete, 2 failures, the rest success or skipped. The validator requires a newly added test to fail on the merge-base binary. That binary is never Bugfix validation (unit tests) job log Session id: cron:clickhouse-maint-slot-13:20260826-191600 |
|
Fixing PR for the sanitizer-only That job builds the merge-base "before" binary under |
|
@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? |
|
Measured. Build is RelWithDebInfo (-O3, clang-22) of this branch; the base arm is the same tree with this PR's How much locking is added, per query.
The shortest queries never reach 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 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.
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 Caveat, plainly: I could not resolve the change from zero. Code layout alone moves 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. |
|
@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.
|
@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 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 |
|
@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. |
CI finish ledger - 7cdb348Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260827-233000 |
|
@serxa Ready for review again. The bot feedback is adjudicated (#115659 (comment)) and CI has finished on CI is not literally green: two reds remain, and neither comes from this change.
|
|
Something prevents merging, check please @groeneai |
|
@serxa Not a conflict:
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 |
| auto profile = std::make_shared<SettingsProfile>(); | ||
| profile->setName("default"); | ||
| const UUID profile_id = access_control.insert(profile); | ||
| SCOPE_EXIT({ |
There was a problem hiding this comment.
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.
CI finish ledger - 33f5ca3CI 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.
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 Session id: cron:our-pr-ci-monitor:20260831-103000 |
`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.
|
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. |
|
@groeneai There is problem with reproducing the race so we get an error:
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. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@serxa Changed the category to |
|
@serxa CI on |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Related: #62025
Description
Context::getReadSettings()reads dozens of settings throughgetSettingsRef(), an unsynchronized inline accessor, while the writers on that path hold the exclusiveContext::mutex- a missing reader-side lock (thecheckSettingsConstraints/clampToSettingsConstraintsoverloads 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 areSettingFieldString, and the getter holds astd::string_viewinto the heapStringwhile a concurrent assignment can reallocate it, so the consequence exceeds a torn scalar.setDefaultProfiles()was the other half:applySettingsQuirks,adjustSettingsForMakeDistributedPlananddoSettingsSanityCheckClampran aftersetCurrentProfilereleased 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 documentedsystem_profilepath for background work - so a background thread opening a file during startup reaches it. The report came from a Keeper changelog reader racingsetDefaultProfiles, but the defect is inContext.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/clampToSettingsConstraintsoverloads reachingdoSettingsSanityCheckClampunder a shared lock only,reloadClusterConfigandsetClustersConfig,getBackupsThrottler, and 29 sites outsideContextreading the global settings viagetSettingsRef.Provenance and validation
Issue #62025 reports this same race, also on a
Stringsetting; it was closed by #62309, which reordered oneclickhouse-localcaller 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 aStringsetting and an integer one; it reports on the unpatched tree in 3 of 3 runs, naminggetReadSettingsas the read andsetSettingWithLockas the write, and is silent in 5 of 5 with the fix.SetDefaultProfilesRacecovers 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 throughs3_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::mutexis private and noContextmethod 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 suitestest_keeper_and_access_storage(which guards the startup orderingsetDefaultProfilestakes 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
lockSharedImplincrementsProfileEvents['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 119 -> 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 1never 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
26.10.1.1210-master(included in26.10and later)