Skip to content

Rename CurrentThread::getQueryContext to tryGetQueryContext - #99325

Merged
Algunenano merged 7 commits into
ClickHouse:masterfrom
Algunenano:rename-tryGetQueryContext
Mar 12, 2026
Merged

Algunenano merged 7 commits into
ClickHouse:masterfrom
Algunenano:rename-tryGetQueryContext

Conversation

@Algunenano

@Algunenano Algunenano commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

Follow-up for #99231

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Description

Renames CurrentThread::getQueryContext to tryGetQueryContext and ThreadStatus::getQueryContext to tryGetQueryContext.

The try prefix makes it explicit that the function may return nullptr (e.g. in background threads like S3Queue), following the existing ClickHouse convention for nullable return values. This makes unchecked dereferences like CurrentThread::tryGetQueryContext()->foo() immediately suspicious in code review.

🤖 Generated with Claude Code


Note

Medium Risk
Wide mechanical refactor across server/client/threading code paths; low algorithmic risk but touches query/thread context plumbing and adds hard failures when query context is unexpectedly missing (e.g., runtime filters), so regressions may surface in edge/background-thread scenarios.

Overview
Renames CurrentThread::getQueryContext()/ThreadStatus::getQueryContext() to tryGetQueryContext() and updates call sites to make nullable query-context access explicit.

Extracts CurrentThread::QueryScope into a standalone Common/QueryScope class and switches client/server request handlers, BlockIO, async insert flush, and various internal query execution paths to use it.

Reduces header coupling by introducing ThreadGroupSwitcher.h (getCurrentThreadGroup()), moving some inline implementations to .cpp (MemoryTrackerSwitcher, ResourceGuard::Request::wait, QueryStatus::updateProgress*), and tightening runtime-filter code to require/preserve a query context (passing it into BuildRuntimeFilterTransform, and throwing LOGICAL_ERROR if absent).

Written by Cursor Bugbot for commit 340848d. This will update automatically on new commits. Configure here.

Version info

  • Merged into: 26.3.1.629

@clickhouse-gh

clickhouse-gh Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [340848d]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan, s3) failure
Test script failed FAIL cidb, issue ISSUE EXISTS

AI Review

1) Summary

This PR primarily renames CurrentThread::getQueryContext to CurrentThread::tryGetQueryContext and extracts several previously inline/thread-scope utilities into .cpp files to reduce header coupling and compile-time impact. I reviewed the changed core paths (CurrentThread, QueryScope, ResourceGuard, ProcessList, runtime filter transform wiring, and broad call-site migrations) and found no new high-confidence correctness, safety, or performance regressions in the current PR head. High-level verdict: looks good to merge.

2) Missing context (if any)

  • CI is still in progress (PR report pending); no final CI artifact set available yet.
  • No dedicated benchmark report attached for this PR (likely not required, but absent).

3) Findings (by severity)

Blockers

  • None.

Majors

  • None.

No additional inline comments were posted because there are no new non-duplicate findings to report.

4) Tests & Evidence

  • Review evidence is static analysis of the full PR diff plus targeted inspection of high-risk files and call sites.
  • Changes are mostly API rename propagation (getQueryContext → tryGetQueryContext) and refactoring of implementation location (header → .cpp) with preserved logic.
  • Negative/error handling in newly touched runtime-filter code is present (BuildRuntimeFilterTransform::finish now explicitly checks for missing query_context and throws).
  • Suggested follow-up: rely on CI completion for final validation; no extra manual tests appear mandatory for this refactor-only scope.

5) ClickHouse Compliance Checklist (Yes/No + short note)

  • Data deletions logged? Yes — no new deletion paths introduced.
  • Serialization formats versioned? Yes — no serialization/protocol changes in this PR.
  • Experimental setting gate present? Yes — no new feature behavior requiring a new gate.
  • Settings exposed for constants/thresholds? Yes — no newly introduced magic thresholds affecting behavior.
  • Backward compatibility preserved? Yes — rename/refactor preserves behavior.
  • SettingsHistory.cpp updated for new/changed settings? N/A — no setting changes.
  • Existing tests untouched (only additions)? Yes — no test relaxations/deletions observed.
  • Docs/user-facing notes updated? N/A — user-facing semantics unchanged.
  • Core-area change got extra scrutiny? Yes — thread/query context and execution paths were specifically reviewed.

6) Performance & Safety Notes

  • Header hygiene improved by moving non-trivial definitions to .cpp (MemoryTrackerSwitcher, ResourceGuard::Request::wait, ManyAggregatedData destructor), which should reduce transitive compile costs.
  • Safety-wise, migrated nullable-context call sites are guarded in the modified hot spots I inspected.
  • No benchmark data provided; if needed, minimal reproducible check is compile-time comparison (full rebuild and touch-and-rebuild for affected headers) rather than runtime microbenchmarks.

7) User-Lens Review

  • The rename to tryGetQueryContext makes nullable semantics clearer and reduces accidental assumptions at call sites.
  • Runtime filter error reporting became more explicit when query context is absent, which is actionable for operators.
  • No surprising user-visible behavior changes detected.

8) Final Verdict

  • Status: Approve

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Mar 12, 2026
Comment thread src/Functions/FunctionApplyFilter.cpp Resolved
@Algunenano
Algunenano force-pushed the rename-tryGetQueryContext branch from b54a16e to 767eb93 Compare March 12, 2026 12:46
Algunenano and others added 4 commits March 12, 2026 14:02
The `try` prefix makes it explicit that the function may return nullptr
(e.g. in background threads like S3Queue), following the existing
ClickHouse convention for nullable return values. This makes unchecked
dereferences like `CurrentThread::tryGetQueryContext()->foo()` immediately
suspicious in code review.

Also renames `ThreadStatus::getQueryContext` to `tryGetQueryContext`
for consistency, since it returns `query_context.lock()` which may
be null.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ead`

`BuildRuntimeFilterTransform` and `FunctionApplyFilter` were fetching
the query context from the thread-local `CurrentThread` at execution
time, which is unsafe in executor threads that may lack a query context.

Follow the standard ClickHouse pattern: receive the context at
construction time and store it as a member. The context is captured
during pipeline building (which always runs in a query thread) and
passed to the transform constructor.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Remove `CurrentThread.h` from high-fan-out headers: `ProcessList.h`,
  `IQueryPlanStep.h`, `DDLWorker.h`, `TCPHandler.h`, `AggregatingTransform.h`,
  `ParallelParsingInputFormat.h`, `StorageTableFunction.h`, `parseSyslogLevel.h`,
  `EmbeddedRocksDBBulkSink.h`, `BlockIO.h`, `LocalConnection.h`,
  `StorageMaterializedView.h`, `HTTPHandler.h`
- Extract `QueryScope` from `CurrentThread` into standalone `Common/QueryScope.h`
  with its own `.cpp`, replacing the nested `CurrentThread::QueryScope` class
- Extract `getCurrentThreadGroup` free function into `Common/ThreadGroupSwitcher.h`,
  replacing `CurrentThread::getGroup()` in template headers:
  `threadPoolCallbackRunner.h`, `ParallelFormattingOutputFormat.h`,
  `HashedDictionaryParallelLoader.h`, `UniqExactSet.h`, `HashedDictionary.h`,
  `StatusRequestsPool.h`
- De-inline `MemoryTrackerSwitcher` ctor/dtor into `MemoryTrackerSwitcher.cpp`
- De-inline `ResourceGuard::Request::wait` into `ResourceGuard.cpp`
- De-inline `ManyAggregatedData` destructor into `AggregatingTransform.cpp`
- De-inline `QueryStatus::updateProgressIn/Out` into `ProcessList.cpp`
- Add explicit `CurrentThread.h` includes to `.cpp` files that relied on
  transitive includes through the trimmed headers

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ntext

`joinRuntimeFilter.cpp` creates `__applyFilter` with `nullptr` context at
query plan optimization time. Fall back to `CurrentThread::tryGetQueryContext`
at execution time when the stored context is null.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Algunenano
Algunenano force-pushed the rename-tryGetQueryContext branch from 767eb93 to 90cb994 Compare March 12, 2026 14:07
- Move `CurrentMetrics` extern declarations from `AggregatingTransform.h`
  to `AggregatingTransform.cpp` where the destructor now lives
- Move `ErrorCodes::RESOURCE_ACCESS_DENIED` from `ResourceGuard.h` to
  `ResourceGuard.cpp` where `wait` now lives
- Revert `FunctionApplyFilter` to not store `ContextPtr` member (style
  rule: avoid holding `ContextPtr` copies in Functions). Use
  `CurrentThread::tryGetQueryContext` at execution time instead.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Comment thread src/Common/QueryScope.cpp Resolved
Algunenano and others added 2 commits March 12, 2026 15:56
…ish`

`tryGetQueryContext` can return nullptr. Guard the dereference with an
explicit check before calling `getRuntimeFilterLookup`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
…lized

The move-assignment operator was overwriting `initialized` without
running cleanup (logging peak memory, detaching from thread group) if
the target was already active. Now mirrors the destructor logic before
taking ownership of the source state.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 23.90% 23.90% +0.00%
Branches 76.30% 76.30% +0.00%

PR changed lines: PR changed-lines coverage: 92.30% (635/688)
Diff coverage report
Uncovered code

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

I did not review everything carefully, but I like the idea

UPD: I looked through all of them...

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

LGTM

/// Also some race condition is possible, because collector_thread runs in parallel with
/// the destruction of the objects already created in this scope.
collector_thread = ThreadFromGlobalPool([thread_group = CurrentThread::getGroup(), this]
collector_thread = ThreadFromGlobalPool([thread_group = getCurrentThreadGroup(), this]

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.

BTW it will be nice to have some style check for lack of these

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll think of something in general as I keep doing more of this work. Now it's part of AI review to keep includes into account, but we should find a better way

@Algunenano
Algunenano added this pull request to the merge queue Mar 12, 2026
Merged via the queue into ClickHouse:master with commit 39e0335 Mar 12, 2026
159 of 160 checks passed
@Algunenano
Algunenano deleted the rename-tryGetQueryContext branch March 12, 2026 23:31
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 12, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jun 9, 2026
Adapt feature files to three API changes from the upstream refactor:
- Rename `getQueryContext` to `tryGetQueryContext` (on both `CurrentThread` and `ThreadStatus`)
- Replace `CurrentThread::QueryScope` with standalone `QueryScope` class and add `#include <Common/QueryScope.h>`
- Add missing `#include <Common/CurrentThread.h>` where transitive includes were removed

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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