Skip to content

Fix several critical bugs around ThreadPoolCallbackRunnerLocal usage - #95818

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:ThreadPoolCallbackRunnerLocal
Feb 10, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:ThreadPoolCallbackRunnerLocal

Conversation

@Algunenano

@Algunenano Algunenano commented Feb 2, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC) or LOGICAL_ERROR

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

Fix several critical bugs around ThreadPoolCallbackRunnerLocal usage

This PR addresses critical memory safety bugs around ThreadPoolCallbackRunnerLocal usage throughout the codebase. The code issue is that when lambdas capture local variables by reference ([&]) and an exception occurs during the enqueue loop, stack unwinding happens before the destructor's waitForAllToFinish() is called, causing use-after-scope bugs when worker threads access destroyed stack variables.

Fixes #95739
I'll do the same for the usages in private too

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.2.1.513

@clickhouse-gh

clickhouse-gh Bot commented Feb 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d391a5]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan, targeted) failure
01511_alter_version_versioned_collapsing_merge_tree_zookeeper FAIL cidb IGNORED
00910_zookeeper_custom_compression_codecs_replicated_long FAIL cidb IGNORED
02265_column_ttl FAIL cidb IGNORED
02444_async_broken_outdated_part_loading FAIL cidb IGNORED
02427_mutate_and_zero_copy_replication_zookeeper FAIL cidb IGNORED
03100_lwu_01_basics FAIL cidb IGNORED
BuzzHouse (amd_msan) failure
Logical error: Unexpected return type from A. Expected B. Got C. Action: (STID: 1611-343c) FAIL cidb, issue ISSUE EXISTS
Finish Workflow failure
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py failure IGNORED

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Feb 2, 2026
for (const auto & table_name : table_infos | boost::adaptors::map_keys)
/// Using a lambda with references is fine, since it only uses `this` and `it.first` which is part of table_infos (`this`)
/// So they will outlive runner even if an exception is thrown
for (const auto & it : table_infos)

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.

This was fine, but I changed it so it was clear where the ownership comes from. Having operator| with boost made things more complex to understand

runner.enqueueAndKeepTrack(
[=, &tables, &mutex, this]
/// Ensure tables and mutex (capture by reference) outlive runner
DB::ThreadPoolCallbackRunnerLocal<void> runner(pool, DB::ThreadName::DATALAKE_REST_CATALOG);

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.

This fixes a critical bug. tables and mutex had a shorter live than runner, so in case of an exception they would be destroyed before ~runner was called.

}
}

ThreadPoolCallbackRunnerLocal<void> runner(pool, ThreadName::PLAIN_REWRITABLE_META_LOAD);

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.

This also fixes another critical issue. Log was used by reference but it had a shorter life span than runner

/// remote_layout_mutex: Same
/// In any case we have a try {} catch (...) around runner usage, so exceptions will call runner.waitForAllToFinish() first
/// Thus the order of destruction of the variables is not important
runner.enqueueAndKeepTrack([remote_path, object_path = file->getPath(), metadata = file->metadata, &log, &settings, this, &remote_layout, &remote_layout_mutex]

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.

Same than above

/// is called first and all tasks stopped before local variables are being destroyed.
ThreadPoolCallbackRunnerLocal<void> runner(pool, ThreadName::MERGETREE_PREWARM_CACHE);

/// Created first, so it outlives runner

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.

Another critical issue here. enough_space would be destroyed before runner

for (size_t row = 0; row < rows; ++row)
{
auto key = static_cast<USearchIndex::vector_key_t>(index_size + row);
/// Passing add_vector_to_index by refence is safe because it outlives the runner

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.

Another critical issue. This one closes #95739


const auto & disks = data_volume->getDisks();

const auto & paths = getDataPaths();

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.

Another critical issue here. These variables would be destroyed before runner in case of an exception


missing_parts.clear();

std::mutex missing_parts_mutex; /// Must be created before runner, so it outlives it

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.

And another one. The mutex needs to outlive fetch_partition_runner

@Algunenano
Algunenano requested a review from Copilot February 2, 2026 16:13

Copilot AI left a comment

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.

Pull request overview

This PR addresses critical lifetime bugs in ThreadPoolCallbackRunnerLocal usage across the codebase. The issue stems from C++ stack unwinding behavior during exceptions: variables declared after the runner are destroyed before it, causing use-after-scope bugs when tasks reference them.

Changes:

  • Reordered variable declarations to ensure captured references outlive ThreadPoolCallbackRunnerLocal instances
  • Added explicit capture lists to lambdas instead of implicit [&] captures
  • Added explanatory comments documenting lifetime requirements
  • Enhanced threadPoolCallbackRunner.h with comprehensive safety warnings and deleted overloads to catch std::reference_wrapper at compile-time

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/Common/threadPoolCallbackRunner.h Added safety documentation and compile-time checks for reference captures
src/Storages/StorageDistributed.cpp Moved paths and last_increment declarations before runner creation
src/Storages/StorageReplicatedMergeTree.cpp Moved missing_parts_mutex before runner and made lambda captures explicit
src/Storages/StorageBuffer.cpp Made lambda captures explicit to avoid implicit reference captures
src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp Moved runner creation after lambda definition
src/Storages/MergeTree/MergeTreeData.cpp Made lambda captures explicit and added lifetime documentation
src/Storages/System/StorageSystemDetachedParts.cpp Added comment explaining safe reference capture
src/Interpreters/InterpreterDropQuery.cpp Made lambda captures explicit with lifetime documentation
src/Interpreters/DatabaseCatalog.cpp Removed implicit [&] capture
src/Interpreters/ClusterProxy/distributedIndexAnalysis.cpp Made lambda captures explicit
src/Interpreters/Aggregator.cpp Made lambda captures explicit with lifetime documentation
src/Disks/IDisk.cpp Added comments explaining recursive capture safety
src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp Moved runner creation after variable declarations
src/Dictionaries/PolygonDictionaryUtils.h Scoped runner with braces and made captures explicit
src/Databases/DatabaseReplicated.cpp Made lambda captures explicit with lifetime documentation
src/Databases/DatabaseBackup.cpp Scoped runner with braces to control lifetime
src/Databases/DataLake/RestCatalog.cpp Scoped runner with braces ensuring tables and mutex outlive it
src/Backups/BackupsWorker.cpp Made lambda captures explicit with lifetime documentation
src/Backups/BackupFileInfo.cpp Added comment explaining safe reference captures
src/Backups/BackupEntriesCollector.cpp Changed iteration pattern to avoid boost adaptors and made captures safer
src/AggregateFunctions/UniqExactSet.h Added comment explaining safe reference usage

/// When creating a runner on stack, you MUST make sure that it's created (and destroyed) before local objects captured by task lambda.

/// ============================================================================
/// CRITICAL SAFETY WARNING: DO NOT CAPTURE LOCAL VARIABLES BY REFERENCE!

Copilot AI Feb 2, 2026

Copy link

Choose a reason for hiding this comment

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

Corrected 'refernce' to 'reference' in line 360 comment.

Copilot uses AI. Check for mistakes.
for (size_t row = 0; row < rows; ++row)
{
auto key = static_cast<USearchIndex::vector_key_t>(index_size + row);
/// Passing add_vector_to_index by refence is safe because it outlives the runner

Copilot AI Feb 2, 2026

Copy link

Choose a reason for hiding this comment

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

Corrected 'refence' to 'reference'.

Suggested change
/// Passing add_vector_to_index by refence is safe because it outlives the runner
/// Passing add_vector_to_index by reference is safe because it outlives the runner

Copilot uses AI. Check for mistakes.
Comment thread src/Storages/StorageBuffer.cpp Outdated
if (runner)
{
runner->enqueueAndKeepTrack([&]()
/// Pasing buf as a reference is fine since it's a reference to this, which outlives the runner

Copilot AI Feb 2, 2026

Copy link

Choose a reason for hiding this comment

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

Corrected 'Pasing' to 'Passing'.

Copilot uses AI. Check for mistakes.
@Algunenano

Copy link
Copy Markdown
Member Author

Please also review the changes in the sync PR, there are more fixes there

@Algunenano
Algunenano added this pull request to the merge queue Feb 10, 2026
Merged via the queue into ClickHouse:master with commit 9e5869e Feb 10, 2026
127 of 130 checks passed
@Algunenano
Algunenano deleted the ThreadPoolCallbackRunnerLocal branch February 10, 2026 11:12
@Algunenano

Copy link
Copy Markdown
Member Author

The main fix that was causing issues was introduced in #96259, so I'm going to remove backports from this as there aren't reports of issues

@Algunenano Algunenano removed the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Feb 10, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Feb 10, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Feb 10, 2026
@clickhouse-gh clickhouse-gh Bot added the ready-for-backport PR is eligible for backporting (merged 7+ days ago, not reverted) label Mar 27, 2026
@maxknv maxknv removed the ready-for-backport PR is eligible for backporting (merged 7+ days ago, not reverted) label Mar 27, 2026
@clickhouse-gh clickhouse-gh Bot added the ready-for-backport PR is eligible for backporting (merged 7+ days ago, not reverted) label Mar 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-critical-bugfix pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo ready-for-backport PR is eligible for backporting (merged 7+ days ago, not reverted)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stack-use-after-scope in MergeTreeIndexVectorSimilarity.cpp

6 participants