Skip to content

Assert that a DataPartsAnyLock is constructed from a held parts lock - #120093

Closed
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/assert-data-parts-lock-token-held
Closed

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/assert-data-parts-lock-token-held

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119634

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

Debug and sanitizer builds now assert that a DataPartsAnyLock token is constructed from a parts lock that still owns its mutex. No user-visible change.

Description

DataPartsAnyLock is the token that 19 MergeTreeData members accept as the caller's proof that it holds data_parts_mutex. Both of its converting constructors discarded their argument:

DataPartsAnyLock(const DataPartsLock &) noexcept {}
DataPartsAnyLock(const DataPartsSharedLock &) noexcept {}

So the token proved only that a lock object existed in the caller's scope, never that it still owned the mutex. A released (DataPartsSharedLock::unlock() is public) or moved-from lock satisfied it silently, and the callee then read data_parts_by_state_and_info / data_parts_by_info unsynchronised.

This names the parameter in both constructors and asserts the lock still owns its mutex, reaching the private std::unique_lock / std::shared_lock through a new owns_lock() accessor. Those constructors are the only way a token can exist, since the class is final, has no default constructor and deletes copy and move, so the check covers every token use. chassert is active only under DEBUG_OR_SANITIZER_BUILD, so official stable builds are unaffected.

@ alexey-milovidov approved this shape and asked for it separately, in #119634 (comment):

The DataPartsAnyLock owns_lock assertion is a reasonable debug/sanitizer diagnostic; if you open it, do so as a separate small PR rather than here.

This is a diagnostic only, and it is deliberately not a fix for the race discussed there: that missing readLockParts() acquisition is on the private getStatus side.

I audited all 157 call sites of the lock-taking members and found no public site reaching the parts index with a token built from a lock it no longer holds, so I do not expect it to fire on existing paths. The one place a parts lock is released while still in scope, calculateColumnAndSecondaryIndexSizesLazily, builds no token afterwards; a breakpoint confirmed a SELECT count() over a JSON-column table enters that post-release branch with the assertion armed without aborting. I have not audited private code and make no claim about it.

Demonstration that the assertion is not vacuous

Driven by a throwaway gtest (not committed). Both violations were asserted twice, on the message and on KilledBySignal(SIGABRT).

With the assertion in place, both violations abort and the positive controls do not:

[ RUN      ] DataPartsAnyLockTmpDeathTest.ReleasedSharedLockAborts
[       OK ] DataPartsAnyLockTmpDeathTest.ReleasedSharedLockAborts (1038 ms)
[ RUN      ] DataPartsAnyLockTmpDeathTest.MovedFromExclusiveLockAborts
[       OK ] DataPartsAnyLockTmpDeathTest.MovedFromExclusiveLockAborts (967 ms)
[ RUN      ] DataPartsAnyLockTmp.LiveSharedLockYieldsToken
[       OK ] DataPartsAnyLockTmp.LiveSharedLockYieldsToken (0 ms)
[ RUN      ] DataPartsAnyLockTmp.LiveExclusiveLockYieldsToken
[       OK ] DataPartsAnyLockTmp.LiveExclusiveLockYieldsToken (0 ms)
[  PASSED  ] 5 tests.

As a mutation control, neutralising only the two chassert lines and rebuilding stops the aborts, which is what shows the assertion and nothing else is responsible:

gtest_tmp_data_parts_any_lock.cpp:105: Failure
Death test: { DB::SharedMutex m; DataPartsLock a(m, nullptr);
              DataPartsLock b(std::move(a)); DataPartsAnyLock t(a); (void)&t; }
    Result: failed to die.
[  FAILED  ] DataPartsAnyLockTmpDeathTest.ReleasedSharedLockAborts
[  FAILED  ] DataPartsAnyLockTmpDeathTest.MovedFromExclusiveLockAborts

The two violations are a released shared lock and a moved-from exclusive lock, which is the only way to make an exclusive lock non-owning since it has no public unlock().


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

`DataPartsAnyLock` is the token that 19 `MergeTreeData` members accept as the
caller's proof that it holds `data_parts_mutex`. Both of its converting
constructors discarded their argument, so the token proved only that a lock
object existed in the caller's scope, never that the object still owned the
mutex: a lock that had been released (`DataPartsSharedLock::unlock()` is
public) or moved from satisfied it silently, and the callee then read
`data_parts_by_state_and_info` / `data_parts_by_info` unsynchronised.

Name the parameter in both constructors and assert that the lock still owns
its mutex, reaching the private `std::unique_lock` / `std::shared_lock`
member through a new `owns_lock()` accessor on each lock struct. The
constructors are the only way a token can come into existence, so the check
covers every token use: the class is final, has no default constructor, and
both its copy and move constructors are deleted.

This is a diagnostic only. `chassert` is active under
`DEBUG_OR_SANITIZER_BUILD` and compiles to `(void)sizeof(!(x))` in official
stable builds, so there is no user-visible behaviour change and no release
codegen change.

An audit of all 157 call sites of the lock-taking members found no public
site that reaches the parts index with a token built from a lock it no
longer holds, so this is not expected to fire on existing paths. The one
place a parts lock is released while still in scope,
`calculateColumnAndSecondaryIndexSizesLazily`, builds no token afterwards.

Related: ClickHouse#119634

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

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

Pre-publication review by an independent model (engine: codex; 0 findings), preceded by an independent
cold read of the resulting code that produced 4 items, none of them a blocker. No fix round was needed.

# Sev Finding Verdict Evidence / action
1 ⚠️ The description named the approving maintainer with a live @ handle, which would have pinged him a third time (the linked thread, and the line owed on it, already notify him) AGREE, fixed before publication Reference broken with a space. No source change
2 💡 The commit message calls calculateColumnAndSecondaryIndexSizesLazily "the one place a parts lock is released while still in scope", but MergeTreeData.cpp:3143 also resets the std::optional holder whose reference part_lock (:3007) remains in scope for the rest of the function DISAGREE on substance, recorded The lock object is destroyed there rather than released while in scope, and the only uses of part_lock are :3135 and :3138, both before the reset, so no token is constructed from it
3 💡 The assertion proves the lock is HELD, never that it is the RIGHT lock: a token built from one table's genuinely held lock and passed to another table's method still passes, and StorageReplicatedMergeTree.cpp:9904 has exactly that shape AGREE, deliberately not fixed here Carrying mutex identity would make the token stateful on a hot path and is a different defect class. Stated here rather than widening a 12 line diagnostic
4 💡 It ships with no committed test, and death tests do exist in the tree (18 EXPECT_DEATH/EXPECT_EXIT uses across 8 files), so "not testable" is not the reason AGREE, declined Test volume should match fix size, and fork based death tests inside the sanitizer unit test jobs are a flakiness risk in exchange for two chassert lines. The throwaway gtest that produced the abort, no abort, abort cycle is kept and can be committed if a reviewer wants it permanent

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

Two things worth a reviewer's time, both measured rather than argued:

  • Every route to a non owning lock is closed structurally, so no public path can reach the assertion.
    unlock() exists only on DataPartsSharedLock, and the only function in the tree taking it mutably is
    calculateColumnAndSecondaryIndexSizesLazily, whose single parts_lock.unlock()
    (MergeTreeData.cpp:8409) is followed only by a loop over an already copied DataParts and builds no
    token, in the function or in its four inline callers. No explicit std::move of either lock type exists.
    Both lock constructors acquire unconditionally in the member init list, with no defer_lock,
    try_to_lock or adopt_lock. All four std::optional holders (MergeTreeData.cpp:3006, :9745,
    :9746, :11163) are dereferenced only while they hold an owning lock. That covers roughly 82 token
    materialisation sites across 10 files, plus 12 pass through sites where a const DataPartsAnyLock &
    parameter is forwarded and nothing is constructed.
  • The shape already exists in the tree. MergeTreeMergePredicate.cpp:185 is
    chassert(merge_mutate_lock.owns_lock()); /// guards currently_merging_mutating_parts, the same
    assertion and the same comment form, and RefreshTask.cpp carries nine more chassert(lock.owns_lock())
    sites.

Private code is not auditable from here, and I make no claim about it. If the assertion fires there, that
is the diagnostic reporting the missing acquisition rather than a defect in this change.

Session id: cron:clickhouse-review-slot-48:20260914-214300

@clickhouse-gh clickhouse-gh Bot closed this Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12a0e3a]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, parallel) FAIL
05182_join_order_conflict_detector_cast_null_propagation FAIL cidb
Stateless tests (amd_tsan, s3 storage, parallel, selected tests) FAIL
05182_join_order_conflict_detector_cast_null_propagation FAIL cidb

AI Review

Summary

This PR adds owns_lock() accessors and debug/sanitizer chasserts in the DataPartsAnyLock converting constructors so a token can no longer be built from an already-unlocked or moved-from parts lock without tripping an assertion. That hardening is useful, but the token is still not tied to the source lock's lifetime, so the new check does not actually make it a sound proof that data_parts_mutex is still held when the callee consumes the token.

Findings

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.h:156-163] The new chassert(lock.owns_lock()) only validates the source lock at conversion time. A caller can still materialize const DataPartsAnyLock & token = readLockParts(); and use token in a later statement; the DataPartsSharedLock temporary is destroyed at the end of the first statement, so the later call reaches data_parts_indexes without holding data_parts_mutex even though these constructors already passed. Suggested fix: make the callee keep the real lock object alive (const DataPartsLock & / const DataPartsSharedLock & overloads, or another design that ties the token lifetime to the source lock) instead of validating only during conversion.
Final Verdict

Status: ⚠️ Request changes
Tie the DataPartsAnyLock contract to the actual lock lifetime, or switch these APIs to the real lock types directly, so the proof still holds when the token is consumed rather than only when it is created.

LLVM Coverage Report

Measured on commit 12a0e3a.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 4/6 (66.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 14, 2026
@groeneai
groeneai requested review from azat and hanfei1991 September 14, 2026 22:10
Comment on lines +156 to +163
DataPartsAnyLock(const DataPartsLock & lock) noexcept // NOLINT(google-explicit-constructor)
{
chassert(lock.owns_lock()); /// guards data_parts_indexes
}

DataPartsAnyLock(const DataPartsSharedLock & lock) noexcept // NOLINT(google-explicit-constructor)
{
chassert(lock.owns_lock()); /// guards data_parts_indexes

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.

DataPartsAnyLock is still a detached proof token here: the new chassert only checks that the source lock owns data_parts_mutex while the token is being constructed. A caller can still write const DataPartsAnyLock & token = readLockParts(); and use token later; the DataPartsSharedLock temporary dies at the end of the first statement, so the later call reaches data_parts_indexes without any held lock even though these constructors already passed. The fix needs to keep the real lock object alive at the callee boundary (const DataPartsLock & / const DataPartsSharedLock & overloads, or another design that ties the token lifetime to the source lock), not just assert during conversion.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is real and I am not disputing it. I measured it first: against the published head, const DataPartsAnyLock & token = data.readLockParts(); compiles, and clang-22 (the CI pin) reports nothing about it under this file's own flag set.

No such site exists in src/, though. All 43 mentions of the type are its own definition plus 38 const DataPartsAnyLock & parameters (19 declarations over 14 members); there is no variable, data member, reference or return type of that type in the tree. To make that a compiler check rather than a grep, I put [[clang::lifetimebound]] on both converting constructor parameters and rebuilt, with clang-22 and each unit's own flags, the 24 translation units that reference any of those 14 members. All 24 stay clean. The only failure is a throwaway file holding your exact spelling, which compiles clean without the attribute:

error: temporary bound to local reference 'token' will be destroyed at the end of the full-expression [-Werror,-Wdangling]
   14 |     const DataPartsAnyLock & token = data.readLockParts();

So the lifetime axis is coverable in this PR's footprint by two attribute tokens rather than a lifetime redesign, and I will add it if a reviewer asks. I have not, for one reason I cannot measure from here: with -Weverything -Werror the attribute turns that spelling into a build error, and this token exists for the private tree (72020e8fb693a, "Accept DataPartsAnyLock for others getActiveContainingPart() (required for private)"), which I cannot compile. Typed const DataPartsLock & / const DataPartsSharedLock & overloads would reverse that commit, so that is this PR's reviewers' call, not something I push on my own.

This PR stays a debug and sanitizer diagnostic; the race it came from is closed by taking readLockParts() in the private getStatus.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 12a0e3a56 with master e05544e98 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 4be746a69; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 12a0e3a

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
Stateless tests (amd_tsan, s3 storage, parallel, selected tests) / 05182_join_order_conflict_detector_cast_null_propagation plan-shape reference diff under the randomized MergeTree setting auto_statistics_types; the runner's own minimization on this lane reports 34/34 failures with the randomized settings and 0/34 without, culprit --auto_statistics_types uniq. Not caused by this PR, which touches only src/Storages/MergeTree/MergeTreeData.h: the same signature is on true master (21 rows over 11 shas) and on 32 other pull requests, all since 2026-09-14 18:54Z #120084 (external, open)
Stateless tests (arm_binary, parallel) / 05182_join_order_conflict_detector_cast_null_propagation same signature and same culprit setting on this lane: 213/213 failures with the randomized settings, 0/199 without, culprit --auto_statistics_types countmin #120084 (external, open)
Mergeable Check rollup of the rows above, no independent failure #120084 (external, open)
PR rollup of the rows above, no independent failure #120084 (external, open)

Session id: cron:our-pr-ci-monitor:20260915-030045

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

@azat azat self-assigned this Sep 19, 2026

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

This is useless, everything already checked at compile time, and this may create false-positive assumptions that it has some sense under it.

@azat azat closed this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, not reopening.

One correction on the premise: the acquisition is guaranteed by construction, but the token's lifetime is not checked at compile time. const DataPartsAnyLock & token = readLockParts(); compiles with no diagnostic under clang-22 with this tree's own warning flags, and the DataPartsSharedLock temporary it is built from is destroyed at the end of that statement, so the token outlives the lock. No site is written that way today: on master every use of the type outside its own definition is a const DataPartsAnyLock & parameter, so I agree the runtime assert buys nothing here.

If a compile-time check is ever wanted, [[clang::lifetimebound]] on the two converting constructors turns that spelling into a -Wdangling error, and it left the 24 translation units in src/ that use those overloads clean when I measured it. I cannot compile the private tree, so I am not opening that unasked.

@azat

azat commented Sep 21, 2026

Copy link
Copy Markdown
Member

clang::lifetimebound make sense, please open PR and assign me (and AFAICS we do not need private part for this)

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged. I am opening a separate PR on master that puts [[clang::lifetimebound]] on the two converting constructors of DataPartsAnyLock (src/Storages/MergeTree/MergeTreeData.h:153-154), compile-time only with no runtime assert, and I will re-measure the src/ translation units that use those overloads on current master before pushing. I will request your review on it and post the link in this thread.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #121376 with [[clang::lifetimebound]] on the two converting constructors, compile-time only, and requested your review.

Both directions measured on master, under clang-21 and the CI-pinned clang-22: const DataPartsAnyLock & token = readLockParts(); compiles clean without the attribute and fails with -Werror,-Wdangling with it, and the 24 src/ translation units that construct a token stay clean. No private part was needed.

ylw510 pushed a commit to ylw510/ClickHouse that referenced this pull request Sep 22, 2026
DataPartsAnyLock is the proof token that 14 MergeTreeData members accept as the
caller's evidence that it holds data_parts_mutex. Both converting constructors
take the lock by const & and store nothing, which gives clang no reason to
connect the constructed token's lifetime to the lock's, so -Wdangling analysis
stops at the constructor boundary and this compiles with no diagnostic:

    const DB::DataPartsAnyLock & token = data.readLockParts();

Guaranteed elision materialises the token directly (the deleted copy and move
constructors do not prevent it) and lifetime-extends it to the end of the
enclosing block, while the DataPartsSharedLock temporary it was built from is
destroyed at the semicolon. The token then certifies a lock that no longer
exists.

[[clang::lifetimebound]] on each constructor parameter declares the missing
connection, which turns that spelling into:

    error: temporary bound to local reference 'token' will be destroyed at the
    end of the full-expression [-Werror,-Wdangling]

No existing site has the dangling shape, so nothing else needed changing: every
use of the type outside its own definition is a const DataPartsAnyLock &
parameter. I measured both directions under clang-21 and the CI-pinned clang-22,
and the 24 src/ translation units that can construct a token stay clean under
both.

The two annotated constructors are the complete construction surface: the class
is final, deletes copy and move, and has no default constructor, factory or
friend. The attribute is diagnostic-only, with no effect on overload resolution,
mangling, codegen, ABI or runtime behaviour.

Leading attribute position is required because the parameters are unnamed. After
the reference the attribute appertains to the type rather than to the parameter
declaration, which clang rejects outright, and naming the parameters would need
[[maybe_unused]] under -Weverything -Werror.

Requested by @ azat in
ClickHouse#120093 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants