Skip to content

Make a dangling DataPartsAnyLock token a compile-time error - #121376

Merged
azat merged 2 commits into
ClickHouse:masterfrom
groeneai:lifetimebound-data-parts-any-lock
Sep 22, 2026
Merged

azat merged 2 commits into
ClickHouse:masterfrom
groeneai:lifetimebound-data-parts-any-lock

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120093

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

Binding a DataPartsAnyLock token to a reference that outlives its parts lock is now a compile-time error. No user-visible change.

Description

DataPartsAnyLock (src/Storages/MergeTree/MergeTreeData.h) is the token that 14 MergeTreeData members accept as the caller's proof that it holds data_parts_mutex. Its two converting constructors take the lock by const &, so the token's lifetime was not tied to the lock's, and this compiled silently:

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

Guaranteed elision materialises the token directly and extends it to the end of the enclosing block, while the DataPartsSharedLock 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 turns that spelling into:

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

The token now also keeps the address of the lock it was built from. Emscripten's clang 24, which the wasm64 build uses, verifies such an annotation instead of trusting it, and rejects it while the token stores nothing. The pointer is never dereferenced, so the token still carries no runtime meaning.

I measured both directions under clang-21, under the CI-pinned clang-22, and under clang 24 in the container the wasm64 job uses: the spelling above is clean without the attribute and an error with it, a full build is clean, and the 24 src/ translation units that can construct a token are clean.

Nothing else needed changing: every mention of the type outside its own definition is a const DataPartsAnyLock & parameter, so a conversion can only happen in call-argument position, where the token and the lock are destroyed together.

@ azat asked for this in #120093 (comment):

clang::lifetimebound make sense, please open PR and assign me

No test is added: the only effect is a compiler diagnostic, and the tree has no negative-compile harness to run one in.


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

Version info

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

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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 21, 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), plus my own cold review
of the resulting header: no blockers, no majors, 3 nits.

# Sev Finding Verdict Evidence / action
1 💡 The measurement sentence let "clang-21 and clang-22" distribute over the full-build clause, but the full build ran under clang-21 only AGREE Reworded before publication: the full build is attributed to clang-21, the 24 translation units to both compilers
2 💡 No code comment states the invariant the attribute encodes, and the class stores nothing, so a later reader could take the attribute for a no-op DISAGREE The explanation lands in the commit message instead, which states the invariant, the elision mechanism and the leading-position constraint in full. Not raised as follow-up work either: there is no user-reachable consequence
3 💡 No test pins the new contract DISAGREE Not constructible: the contract is a compiler diagnostic, there is no negative-compile harness in ci/ or tests/, CMakeLists.txt:169 blocks build-time try_compile, and stateless tests run against a server binary with no compiler present. Stated in the description instead

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

One addition to the description's reasoning: I re-ran the "no existing site has the dangling shape"
closure against current master as well as this branch, and it is a plain text census, so it also
covers the release-only and sanitizer-only blocks that a debug build never compiles.

Session id: cron:clickhouse-review-slot-11:20260921-142100

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

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b3d1cd9]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
The mutation submitted before the upgrade was not finished by the new server (see mutation_across_upgrade.txt) FAIL cidb
Error message in clickhouse-server.log (see upgrade_error_messages.txt) FAIL cidb

AI Review

Summary

This PR turns DataPartsAnyLock into a compiler-checked proof token by annotating its two converting constructors with [[clang::lifetimebound]] and by storing a non-dereferenced pointer so newer Clang versions can verify the lifetime claim. I did not find an unresolved correctness, safety, performance, or PR-metadata issue in the current diff, and the changed constructors appear to cover the full construction surface of DataPartsAnyLock as it exists today.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit b3d1cd9.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 2/2 (100.00%) · 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 21, 2026
@groeneai
groeneai requested a review from azat September 21, 2026 15:05
@azat azat self-assigned this Sep 21, 2026
@azat
azat enabled auto-merge September 21, 2026 15:14
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit b3d1cd9dbc38cdb97311e6830e3e8325090d71eb was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Build (wasm64) compiles with Emscripten 6.0.5, whose clang is 24.0.0git, and its
lifetime-safety analysis checks [[clang::lifetimebound]] instead of trusting it:
it looks for something in the constructed object that can refer to the annotated
parameter. The token stored nothing, so there was nothing to find, and every
translation unit including the header failed under -Werror:

    src/Storages/MergeTree/MergeTreeData.h:153:24: error: could not verify that
    the return value can be lifetime bound to an unnamed parameter
    [-Werror,-Wlifetime-safety-lifetimebound-violation]

Keeping the address of the lock the token was built from makes the annotation a
claim the compiler can check, and the diagnostic the annotation exists for is
unchanged: binding a token to a reference that outlives its lock is still
rejected, now by -Wdangling and also by -Wlifetime-safety-use-after-scope. The
pointer is never dereferenced, so the token still carries no runtime meaning,
and [[maybe_unused]] keeps -Wunused-private-field quiet (I checked that the
warning does fire without it).

Measured in the container that job uses (clickhouse/binary-builder, em++ 6.0.5,
clang 24): the three objects it reported build clean and all 24 src/ translation
units that construct a token are clean, while the previous shape fails the same
three objects with the two errors above. Under the CI-pinned clang-22 the full
build is clean, clang-tidy is clean, and the dangling spelling is still an error.
Moving the constructor bodies out of the header does not help: the diagnostic
fires on the definition instead.

Suppressing -Wlifetime-safety-lifetimebound-violation in cmake/warnings.cmake,
next to the four lifetime-safety diagnostics already disabled there for clang 23
and newer, also goes green. I did not do that: the annotation genuinely was
unverifiable, and the suppression would hide the same mistake in every future
annotation.

Co-Authored-By: Claude Opus 5 <[email protected]>
auto-merge was automatically disabled September 21, 2026 20:38

Head branch was pushed to by a user without write access

@groeneai

Copy link
Copy Markdown
Collaborator Author

Build (wasm64) went red on this branch and it was my diff. That job compiles with Emscripten 6.0.5, whose clang is 24.0.0git, and its lifetime-safety analysis verifies [[clang::lifetimebound]] instead of trusting it. With the token storing nothing there was nothing for it to verify:

src/Storages/MergeTree/MergeTreeData.h:153:24: error: could not verify that the return value can be lifetime bound to an unnamed parameter [-Werror,-Wlifetime-safety-lifetimebound-violation]

b3d1cd9 keeps the address of the lock the token was built from, which makes the annotation checkable. The pointer is never dereferenced, so the token still has no runtime meaning, and the check you approved is unchanged: the dangling spelling is still rejected, now by -Wdangling and also by -Wlifetime-safety-use-after-scope. Measured in the container that job uses: the three objects it failed on build clean, all 24 token-constructing translation units are clean, and the previous shape still fails the same three objects.

The alternative was to suppress -Wlifetime-safety-lifetimebound-violation in cmake/warnings.cmake, next to the four lifetime-safety diagnostics already disabled there for clang 23 and newer. That is green as well and I can switch to it if you prefer, but it would hide the same mistake in any future annotation.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b3d1cd9

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) false red, not from this diff: the pre-upgrade phase runs the PREVIOUS release's suite, and v26.9's own 05211_backup_log_zero_byte_data_file creates Log-family tables typed AggregateFunction(countResample(10, 5, 1), UInt64, UInt64). --upgrade-check implies --fake-drop, so those tables outlive the restart and the new binary correctly refuses the empty-range parameterisation, giving Code: 69 ARGUMENT_OUT_OF_BOUND in AsyncLoader::worker once per leftover table a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Upgrade check (amd_release) / The mutation submitted before the upgrade was not finished by the new server (see mutation_across_upgrade.txt) one and the same cause: StorageSystemMutations::fillData iterates databases with skip_not_loaded = false, so it waits on the failed table load and rethrows, and the runner's system.mutations probe returns empty instead of 1. mutation_across_upgrade.txt is itself empty in this run a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Mergeable Check and PR are the praktika aggregators reflecting that single Upgrade check (amd_release) red, not independent failures, so they are resolved by the rows above. CH Inc sync passed on this head.

This PR changes one header, src/Storages/MergeTree/MergeTreeData.h, and touches nothing aggregate-function or upgrade related. All 27 Build (*) legs are green on this head, Build (wasm64) included, so the compile-time property this change exists for holds on every flavour.

Session id: cron:our-pr-ci-monitor:20260922-030126

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for both Upgrade check (amd_release) rows here is open: #121484.

The previous release's own 05211_backup_log_zero_byte_data_file types five Log family tables with countResample(10, 5, 1) and restores a copy of each. --upgrade-check implies --fake-drop, so they survive into the upgrade restart, where the new server refuses each one (#119728, an approved backward incompatible change) and logs the <Error>. The same failed load is what empties mutation_across_upgrade.txt: system.mutations iterates every database at skip_not_loaded = false, so waitLoad rethrows and the runner's probe reads nothing.

@azat
azat enabled auto-merge September 22, 2026 14:23
@azat
azat added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit c911d10 Sep 22, 2026
174 of 176 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 22, 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 groeneai-origin-review-human PR origin: human review feedback on a groeneai PR 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.

3 participants