Skip to content

Report the owner query_ids and hold count in RWLock re-entrancy errors - #110971

Merged
evillique merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/rwlock-reentrant-error-diagnostics
Aug 18, 2026
Merged

evillique merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/rwlock-reentrant-error-diagnostics

Conversation

@groeneai

@groeneai groeneai commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

When an RWLockImpl::getLock() re-entrancy assertion fires (RWLock is already locked in exclusive mode / Cannot acquire exclusive lock while RWLock is already locked), the error message now names the other query_ids currently owning the lock and how many locks the requesting query_id already holds, to make such lock-ordering errors diagnosable.

Description

Related: #110893

The two fast-path re-entrancy assertions in RWLockImpl::getLock() fire when the requesting query_id is already present in owner_queries, but their messages named nothing at all - so the only artifact of a rare lock-ordering error was the bare sentence. That is the case for the CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE re-entrant deadlock seen under stress, which has no local reproducer.

Both messages now report:

  • the set of owner query_ids, with a count next to any query_id held by more than one thread - i.e. who else is holding the lock, which is not recoverable from anything else in the log;
  • the number of locks the requesting query_id already holds - an owner count above one shows the re-entrancy is across sibling threads of the same query rather than a single nested acquisition;
  • the query_id itself. This is the lock key passed to getLock(), not the ambient query_id: callers pass getInitialQueryId() on some paths (InterpreterSelectQuery, InterpreterInsertQuery), getCurrentQueryId() on others, and RWLockImpl::NO_QUERY from background threads, so it is not redundant with the log-line prefix.

The requester thread id is deliberately not printed: OwnPatternFormatter already prefixes every line with [ thread_id ], and the holder TID - the one worth pivoting from into a thread dump - is not tracked. Locks taken with NO_QUERY never enter owner_queries, hence the wording "owner query_ids" rather than "owners".

Behaviour-neutral: two error strings, plus getOwnerQueryIdsDescription() refactored to share the new formatOwnerQueryIds() helper. No new bookkeeping on the lock hot path; the public getOwnerQueryIds() API is unchanged. All 8 Common.RWLock* unit tests pass.

Version info

  • Merged into: 26.8.1.1672 (included in 26.8 and later)

…sages

The two RWLockImpl::getLock() fast-path assertions ("RWLock is already locked
in exclusive mode" and "Cannot acquire exclusive lock while RWLock is already
locked") are thrown when the requesting query_id is already an owner. Their
messages carried no context about who holds the lock, which makes the rare
CREATE OR REPLACE re-entrant deadlock (surfaced under stress) hard to diagnose:
there is no local reproducer and the only artifact is the exception text.

Add the requesting query_id, the requesting thread id, the number of locks the
requesting query_id already holds, and the full set of owner query_ids to both
messages. The requesting thread id can be correlated with the per-thread stack
dump BaseDaemon prints in the same fatal log to identify the holding thread,
and an owner count > 1 shows the query_id is held by multiple (sibling) threads.

Behavior-neutral: it only enriches two already-existing error strings. The owner
list is formatted by a small helper; the throw sites call it while
internal_state_mtx is already held, and the public getOwnerQueryIdsDescription()
keeps its short critical section (copy under the lock, then format). No new
bookkeeping on the lock hot path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? N/A - this is a behavior-neutral diagnostic (not a bug fix). The assertion path is exercised by the existing Common.RWLockRecursive unit test.
b Root cause explained? For the investigation being served: the rare CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE re-entrant deadlock (Cannot acquire exclusive lock while RWLock is already locked) has no local reproducer; the only artifact is the exception text, which carried no owner info. This PR does not claim to fix that; it makes the message identify the holder.
c Fix matches root cause? N/A - not a fix. Targeted diagnostic at the exact throw site.
d Test intent preserved / new tests? All 8 Common.RWLock* unit tests pass unchanged (behavior neutral). No new test: the change only alters two error-message strings; asserting exact LOGICAL_ERROR text would be brittle and there is no user-observable behavior to assert via SQL.
e Demonstrated both directions? N/A - no behavior change (message-only).
f General, not a narrow patch? Both re-entrancy throw sites in getLock() are updated consistently (Write-while-exclusive and Write-while-locked). No sibling throw site missed.
g Generalizes across inputs/wrappers? N/A - no type/engine-specific logic.
h Backward compatible? Yes. No setting/format/protocol/ABI change; getOwnerQueryIds() public API unchanged. No SettingsChangesHistory entry needed.
i Invariants/contracts preserved? Yes. The owner list is formatted by a free helper; the throw sites call it while internal_state_mtx is already held (no re-lock), and the public getOwnerQueryIdsDescription() keeps its short critical section (copy under the lock, then format). No new allocation on the lock hot path.

Session id: cron:clickhouse-author-slot-1:20260719-050200

@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 full pass + 1 delta recheck; behavior-neutral diagnostic change).

# Sev Finding Verdict Evidence / action
1 ⚠️ Refactor extended the internal_state_mtx critical section by formatting the owner list under the lock in getOwnerQueryIdsDescription(). AGREE — fixed Extracted a free formatOwnerQueryIds(map) helper. The public getter now does formatOwnerQueryIds(getOwnerQueryIds()) (copy under lock, then format unlocked); only the getLock() throw sites format under the already-held state_lock.
2 ⚠️ "The diff does not implement the promised diagnostic enrichment." DISAGREE Delta-scoping artifact: the recheck was run --delta against the already-enriched pre-revision commit, so it only saw the helper refactor. The actual PR diff vs master enriches BOTH messages — git diff origin/master shows +query_id, +getThreadId(), +owner_query_it->second, +current owners on both throw sites.
3 💡 Comment claimed a "shorter" critical section without evidence. AGREE — fixed Reworded to "Format the owners copied by getOwnerQueryIds() without holding internal_state_mtx." (no overclaim).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-1:20260719-050200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @tavplubix — could you review this? It's a behavior-neutral diagnostic change: the two RWLockImpl::getLock() re-entrancy assertions now include the requesting query_id, the requesting thread id, the owner count, and the owner query_id set, so the rare CREATE OR REPLACE re-entrant lock error seen under stress (which has no local reproducer) will self-report the holding thread in the fatal log. Related: #110893.

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [763c487]

Summary: ❌

job_name test_name status info comment
Stress test (amd_asan_ubsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue

AI Review

Summary

This PR makes the two RWLockImpl::getLock re-entrancy exceptions materially more diagnosable by reporting the requesting query_id, its existing hold count, and the current owner query_id set. I reviewed the current diff, the full src/Common/RWLock.cpp implementation, and the prior discussion, and I do not see a remaining correctness, concurrency, or PR-metadata issue in the current revision.

Final Verdict

✅ No blocking or major issues found in the current diff.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.00% -0.10%

Changed lines: Changed C/C++ lines covered: 17/23 (73.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d2ccbaf

This PR's diff is a behavior-neutral diagnostic change (RWLock re-entrancy assertion messages). Neither failure below is PR-caused; each has an owner.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / LazyMaterializingTransform row!=offsets (STID 4770-4443) LOGICAL_ERROR, chronic trunk bug (arrayJoin/vector-rescoring + ORDER BY LIMIT lazy-materialization offset accounting; 4 unrelated PRs/30d, 0 master this window, prior master hits 05-01/03-30) a fix task is created (investigating at full effort — fixing PR link to follow here)
Stress test (arm_release) + (arm_tsan) / Cannot start clickhouse-server server restart boot failure: Code 246 "Part all_2_3_1_0 intersects previous part all_1_2_2_1 and the transaction metadata could not be read" (partial write / SIGKILL mid-commit); 47 unrelated PRs/7d, 1 master a fix task is created (investigating at full effort — fixing PR link to follow here)
Mergeable Check / PR derivative fails only due to the two Stress failures above

Session id: cron:our-pr-ci-monitor:20260719-133000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the stress-restart Cannot start clickhouse-server / Code 246 "Part intersects previous part ... transaction metadata could not be read" boot failure (tables t_plt_reparent / t_plt_evict_reinsert): #110999. Not caused by this PR (it is a #100992-introduced object-storage-disk test issue); this PR's stress hit was collateral.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for LazyMaterializingTransform STID 4770-4443 created: #111003

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 18/23 (78.26%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 65cb446

Every failure below has an owner: a fixing PR (ours 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_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit deterministic under parallel replicas (3/3 reruns failed) #112385 (ours, open)
Stateless tests (arm_binary, parallel) / 02354_distributed_with_external_aggregation_memory_usage Code 241 on the INSERT at the CI 5G profile memory limit a fix task is created (investigating at full effort — fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260729-043000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 02354_distributed_with_external_aggregation_memory_usage Code 241 red: #112478

Comment thread src/Common/RWLock.cpp Outdated
throw Exception(ErrorCodes::LOGICAL_ERROR,
"RWLockImpl::getLock(): RWLock is already locked in exclusive mode "
"(requested by query_id '{}' from thread {}; this query_id already holds {} lock(s); current owners: {})",
query_id, getThreadId(), owner_query_it->second, formatOwnerQueryIds(owner_queries));

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.

optional: drop the requester thread id — it duplicates the log-prefix thread_id and the exception's own captured backtrace, and the holder TID (the one you'd actually pivot from into a thread dump) isn't tracked anyway.

same for the message at line 168. query_id (the lock key) + owner set + hold count are the parts that are genuinely new, so those are worth keeping.

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.

Done, and verified rather than taken on faith: OwnPatternFormatter::formatExtended writes [ thread_id ] {query_id} from ExtendedLogMessage (src/Loggers/OwnPatternFormatter.cpp:33-50, ExtendedLogMessage.cpp:36), so the requester TID was redundant. Dropped from both messages, and the now-unused base/getThreadId.h include with it.

Your point about the lock key holds up in the code too, so query_id stays: callers pass getInitialQueryId() on some paths (InterpreterSelectQuery.cpp:645, InterpreterInsertQuery.cpp:1042), getCurrentQueryId() on others (InterpreterDeleteQuery, InterpreterDropQuery), and RWLockImpl::NO_QUERY from background threads (MergeTreeCleanupThread.cpp:41).

One thing your comment made me look at: locks taken with NO_QUERY never enter owner_queries (guarded at RWLock.cpp:245 and :305), so "current owners" promised a completeness the map does not have. Reworded to "current owner query_ids", matching IStorage::tryLockTimed.

Rendered messages now:

RWLock is already locked in exclusive mode (requested for query_id 'q_probe',
which already holds 1 lock(s); current owner query_ids: q_probe)

Cannot acquire exclusive lock while RWLock is already locked (requested for
query_id 'q_probe2', which already holds 2 read lock(s); current owner
query_ids: q_other, q_probe2 (2))

All 8 Common.RWLock* unit tests pass.

@tiandiwonder

Copy link
Copy Markdown
Contributor

the description leads with adding query_id and thread id, but both are already standard log-line prefix fields (ExtendedLogMessage), so that framing undersells the change. the genuinely new info is the owner query_id set (who else holds the lock) plus the requester's held-lock count — worth reframing around those. one clarification worth adding: the in-message query_id is the lock key passed to getLock, which can differ from the ambient prefix query_id or be NO_QUERY, so it isn't redundant with the prefix even though the thread id is.

Per review on ClickHouse#110971: the requester thread id duplicates the log-line
prefix (OwnPatternFormatter writes `[ thread_id ] {query_id}` from
ExtendedLogMessage) and the exception's own backtrace, and the holder TID
is not tracked, so it is not the field you would pivot from into a thread
dump.

The in-message query_id is kept: it is the lock key passed to
RWLockImpl::getLock(), which is getInitialQueryId() on some paths,
getCurrentQueryId() on others and NO_QUERY in background threads, so it
can differ from the ambient prefix query_id. The requester's hold count
and the owner query_id set are also kept - they are the information not
available anywhere else.

The now-unused base/getThreadId.h include is removed.
Locks taken with NO_QUERY never enter owner_queries (RWLock.cpp:245 and
:305 both guard on query_id != NO_QUERY), so the printed map is the set of
named owners, not the complete holder set. "current owner query_ids"
matches the wording already used by IStorage::tryLockTimed and does not
promise completeness.
@groeneai groeneai changed the title Include owner query_id and thread in RWLock re-entrancy assertion messages Report the owner query_ids and hold count in RWLock re-entrancy errors Aug 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reframed the title and description around the owner query_id set and the requester's hold count, and added the clarification you asked for: the in-message query_id is the lock key passed to getLock(), which is getInitialQueryId() on some paths, getCurrentQueryId() on others and NO_QUERY from background threads, so it is not redundant with the prefix even though the thread id was.

New title: "Report the owner query_ids and hold count in RWLock re-entrancy errors".

The thread id is dropped from both messages per your inline comment (763c487), and "current owners" became "current owner query_ids" since NO_QUERY holders never enter owner_queries. Details in the thread on RWLock.cpp.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 763c487

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
Stress test (amd_asan_ubsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotNullIn' (STID 0250-41a5) chronic trunk LOGICAL_ERROR in IN-family set resolution, 103 unrelated PRs and 10 master runs in 30 days; issue #107619 #102308 (external, open)

CI state on this head: 176 check-runs, 151 success / 24 skipped / 1 failure, 0 queued or
in progress, Finish Workflow and Config Workflow both success, praktika reports 0 dropped
jobs (the run has real coverage).

Not caused by this PR: the diff is src/Common/RWLock.cpp only (assertion message strings),
which cannot affect IN-subquery set resolution. Merged #107924 is already an ancestor of this
head, so it does not cover this signature; #102308 owns the residual path.

@evillique
evillique added this pull request to the merge queue Aug 18, 2026
Merged via the queue into ClickHouse:master with commit a521cf1 Aug 18, 2026
178 of 180 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 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 pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants