Skip to content

ThreadPool: wake most recently idle worker thread (LIFO) when scheduling a job to reduce memory fragmentation - #100177

Merged
alexey-milovidov merged 97 commits into
masterfrom
lifo-thread-pool-scheduling
Jun 13, 2026
Merged

alexey-milovidov merged 97 commits into
masterfrom
lifo-thread-pool-scheduling

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

When a new job is scheduled, the thread pool now wakes the most recently idle thread (LIFO order) instead of an OS-determined arbitrary thread. This concentrates work on fewer OS threads, which:

  1. Reduces memory fragmentation from jemalloc per-thread caches (tcache). Previously, work spread across many threads caused each to accumulate its own allocator cache, leading to excessive memory retention (e.g. 26 GiB instead of 4-5 GiB for two-level GROUP BY queries).

  2. Improves CPU cache locality, as recently-active threads have warmer caches.

  3. Allows excess idle threads to be naturally freed by the existing max_free_threads mechanism, releasing their allocator caches.

Implementation: each worker thread now has a per-thread condition variable. Idle threads push themselves onto a LIFO stack and wait on their individual CV. The scheduler pops the most recently idle thread and signals it directly. The shared new_job_or_shutdown condition variable is removed.

Note: this changes only which worker thread is woken to run a job; the job queue order is unchanged (jobs are still served in priority/FIFO order).

#10818

Changelog category (leave one):

  • Performance Improvement

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

When a new job is scheduled in ThreadPool, wake the most recently idle worker thread (LIFO) instead of an arbitrary one. This reduces memory fragmentation from per-thread allocator caches. The order in which jobs are processed is not changed.

Note: I found the reasoning doubtful, so I set it as a draft for now.
Update: this is actually very good.

Version info

  • Merged into: 26.6.1.759

When a new job is scheduled, the thread pool now wakes the most recently
idle thread (LIFO order) instead of an OS-determined arbitrary thread.
This concentrates work on fewer OS threads, which:

1. Reduces memory fragmentation from jemalloc per-thread caches (tcache).
   Previously, work spread across many threads caused each to accumulate
   its own allocator cache, leading to excessive memory retention (e.g.
   26 GiB instead of 4-5 GiB for two-level GROUP BY queries).

2. Improves CPU cache locality, as recently-active threads have warmer
   caches.

3. Allows excess idle threads to be naturally freed by the existing
   `max_free_threads` mechanism, releasing their allocator caches.

Implementation: each worker thread now has a per-thread condition variable.
Idle threads push themselves onto a LIFO stack and wait on their individual
CV. The scheduler pops the most recently idle thread and signals it directly.
The shared `new_job_or_shutdown` condition variable is removed.

#10818

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6555f83]

Summary: ✅


AI Review

Summary

This PR changes ThreadPool job dispatch to wake the most recently idle worker thread through a per-worker condition variable and an intrusive idle stack, with regression coverage for LIFO concentration, worker self-removal, and limit shrink behavior. The current code addresses the prior lost-wakeup, lifetime, allocation, and shrink-collapse concerns, and the remaining performance trade-offs are documented in the PR discussion.

Final Verdict

Status: ✅ Approve

No required actions.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Mar 20, 2026
Comment thread src/Common/ThreadPool.h Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Surprisingly, it shows benefits (more than 2x) in at least one test...

@alexey-milovidov

Copy link
Copy Markdown
Member Author

It is also faster on at least one test.

alexey-milovidov and others added 2 commits March 20, 2026 10:51
…CATIONS_IN_SCOPE`

The worker function runs under `DENY_ALLOCATIONS_IN_SCOPE`, but
`idle_thread_stack.push_back(this)` can trigger a `std::vector`
reallocation. Fix by pre-reserving capacity to `max_threads` in the
constructor and in `setMaxThreads` when it increases.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…CATIONS_IN_SCOPE`

The worker function runs under `DENY_ALLOCATIONS_IN_SCOPE`, but
`idle_thread_stack.push_back(this)` can trigger a `std::vector`
reallocation. Fix by pre-reserving capacity to `max_threads` in the
constructor and in `setMaxThreads` when it increases.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/ThreadPool.h Resolved
alexey-milovidov and others added 6 commits March 20, 2026 11:14
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eads)`

The `idle_thread_stack.reserve(max_threads)` call in the `ThreadPoolImpl`
constructor caused a ~24 GiB memory tracker drift during server startup.
The 80 KB allocation (10000 pointers for the GlobalThreadPool) triggered
a jemalloc allocation path change that caused subsequent allocations to
be tracked without corresponding frees being tracked, leading to
`MEMORY_LIMIT_EXCEEDED` errors in CI before the MemoryWorker could
correct the tracker.

Fix: remove the pre-reserve calls and instead use `ALLOW_ALLOCATIONS_IN_SCOPE`
around the `push_back` in the worker function. The vector will grow
naturally with amortized O(1) push_back, and the rare reallocations
are explicitly allowed.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…eads)`

The `idle_thread_stack.reserve(max_threads)` call in the `ThreadPoolImpl`
constructor caused a ~24 GiB memory tracker drift during server startup.
The 80 KB allocation (10000 pointers for the GlobalThreadPool) triggered
a jemalloc allocation path change that caused subsequent allocations to
be tracked without corresponding frees being tracked, leading to
`MEMORY_LIMIT_EXCEEDED` errors in CI before the MemoryWorker could
correct the tracker.

Fix: remove the pre-reserve calls and instead use `ALLOW_ALLOCATIONS_IN_SCOPE`
around the `push_back` in the worker function. The vector will grow
naturally with amortized O(1) push_back, and the rare reallocations
are explicitly allowed.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Common/ThreadPool.cpp Resolved
alexey-milovidov and others added 6 commits March 21, 2026 10:10
The targeted CI job re-runs previously failed tests with `--count 10`.
These tests were not idempotent:

- `test_replication_credentials`: data accumulated across re-runs because
  tables were never truncated. Add `TRUNCATE TABLE` at the start of each
  test function.

- `test_block_structure_mismatch`: same issue — duplicate rows from
  repeated inserts. Add `TRUNCATE TABLE` before inserting.

- `test_version_update`: `CREATE TABLE test` failed with "Table already
  exists" on the second run. Add `DROP TABLE IF EXISTS` before creating.

- `test_group_array_element_size`: same — `tab3` and `tab4` not dropped
  between runs. Add `DROP TABLE IF EXISTS` before creating.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The targeted CI job re-runs previously failed tests with `--count 10`.
These tests were not idempotent:

- `test_replication_credentials`: data accumulated across re-runs because
  tables were never truncated. Add `TRUNCATE TABLE` at the start of each
  test function.

- `test_block_structure_mismatch`: same issue — duplicate rows from
  repeated inserts. Add `TRUNCATE TABLE` before inserting.

- `test_version_update`: `CREATE TABLE test` failed with "Table already
  exists" on the second run. Add `DROP TABLE IF EXISTS` before creating.

- `test_group_array_element_size`: same — `tab3` and `tab4` not dropped
  between runs. Add `DROP TABLE IF EXISTS` before creating.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The initial cleanup (TRUNCATE/DROP) was insufficient because tests also
modify config files and server state that persists across re-runs:

- `test_replication_credentials`: `test_different_credentials` and
  `test_credentials_and_no_credentials` modify `credentials1.xml` via
  `replace_config`. On re-run the modified config persists, changing
  replication behavior. Fix: restore original credentials config and
  `SYSTEM RELOAD CONFIG` at the start of each test. Also use
  `CREATE DATABASE/TABLE IF NOT EXISTS` in `_fill_nodes`.

- `test_group_array_element_size`: `test_max_exement_size` ends with
  config at `11` instead of `10`, so on re-run `replace_in_config("10",
  "11")` is a no-op and assertions fail. Fix: restore original config
  via `replace_config` + `restart_clickhouse` at test start.

- `test_version_update`: use `DROP TABLE IF EXISTS test SYNC` to ensure
  ZooKeeper metadata is cleaned up for the `ReplicatedReplacingMergeTree`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The initial cleanup (TRUNCATE/DROP) was insufficient because tests also
modify config files and server state that persists across re-runs:

- `test_replication_credentials`: `test_different_credentials` and
  `test_credentials_and_no_credentials` modify `credentials1.xml` via
  `replace_config`. On re-run the modified config persists, changing
  replication behavior. Fix: restore original credentials config and
  `SYSTEM RELOAD CONFIG` at the start of each test. Also use
  `CREATE DATABASE/TABLE IF NOT EXISTS` in `_fill_nodes`.

- `test_group_array_element_size`: `test_max_exement_size` ends with
  config at `11` instead of `10`, so on re-run `replace_in_config("10",
  "11")` is a no-op and assertions fail. Fix: restore original config
  via `replace_config` + `restart_clickhouse` at test start.

- `test_version_update`: use `DROP TABLE IF EXISTS test SYNC` to ensure
  ZooKeeper metadata is cleaned up for the `ReplicatedReplacingMergeTree`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `test_concurrent_ttl_merges`: Add `DROP TABLE IF EXISTS ... SYNC`,
  `SYSTEM DROP REPLICA ... FROM ZKPATH`, and `SYSTEM START TTL MERGES`
  at the start of each test to clean up state from previous runs
- `test_cluster_discovery/test_auxiliary_keeper`: Restart nodes that may
  have been left stopped, and drop `tbl` table on all nodes before re-run
- `test_keeper_remove_rejoin_leader`: Increase `wait_until_connected`
  timeout from 30s to 60s after leadership transfer (ASan builds are slow)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- `test_concurrent_ttl_merges`: Add `DROP TABLE IF EXISTS ... SYNC`,
  `SYSTEM DROP REPLICA ... FROM ZKPATH`, and `SYSTEM START TTL MERGES`
  at the start of each test to clean up state from previous runs
- `test_cluster_discovery/test_auxiliary_keeper`: Restart nodes that may
  have been left stopped, and drop `tbl` table on all nodes before re-run
- `test_keeper_remove_rejoin_leader`: Increase `wait_until_connected`
  timeout from 30s to 60s after leadership transfer (ASan builds are slow)

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

This improves performance among many tests with almost no degradation.

@alexey-milovidov

Copy link
Copy Markdown
Member Author
Screenshot_20260321_194720 Screenshot_20260321_194735 Screenshot_20260321_194757 Screenshot_20260321_194817 Screenshot_20260321_194834 Screenshot_20260321_194856 Screenshot_20260321_194915 Screenshot_20260321_194930

@alexey-milovidov
alexey-milovidov marked this pull request as ready for review March 21, 2026 18:53

@alexey-milovidov alexey-milovidov left a comment

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.

The code LGTM

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Performance comparison analysis (SHA 6e1a7cdc1170)

I cross-referenced every slower change ≥1.10× against 30 days of master-only perf runs (pull_request_number = 0) to separate genuine regressions from the chronically-noisy tests.

Most "slower" entries are flaky/unstable on master, not caused by this PR — e.g. uniq_with_key*, hash_table_sizes_stats*, array_reduce (47/1165 slower on master), set_index (20/1167), join_convert_outer_to_inner (17/1167), formats_columns_nullable (29/136), aggregation_by_partitions, compact_part_subcolumns (171 unstable), decimal_aggregates #18 (26 unstable), insert_select_squashing_variant (76 unstable).

Genuine regressions (never slower on master, decent sample)

AMD (Sapphire Rapids)

Mag Query Master slower/total
1.21× insert_parallel #0 — INSERT INTO t SELECT * FROM numbers_mt(1e9) 0/584
1.10× memory_cache_friendliness #0 0/584
1.10× parallel_final #25 0/229
1.11× apply_patch_parts_merge #2 0/583

ARM (Graviton 4)

Mag Query Master slower/total
1.40× group_by_fixed_keys #13 0/839 (6 unstable)
1.40× group_by_fixed_keys #7 0/816 (8 unstable)
1.24× vectorize_aggregation_combinators #0 — countMerge over countState() FROM zeros(1e9) 0/1169
1.16× min_max_index_with_cast #0 0/823
1.10× aggregation_by_partitions #8 0/696

Interpretation

All genuine regressions share one trait: they are maximally-parallel aggregation / parallel-insert queries. That is exactly the workload the LIFO change trades against — concentrating jobs on the most-recently-used worker threads reduces the number of concurrently active threads, which is the very mechanism that reduces per-thread allocator fragmentation. So these look like the inherent CPU-parallelism cost of LIFO concentration, not a defect — the flip side of the memory wins this PR targets (#10818).

The wins are large and also new in this PR: classification +8.15× / +3.12×, grace_hash_join +2.59×, order_by_single_column +1.75×, plus many order_with_limit, group_array_moving_sum, and (on AMD) group_by_fixed_keys / hash_table_sizes_stats_small improvements.

Suggestion

Either accept these as the documented parallelism-vs-locality trade-off, or consider preferring the most-recently-idle thread only when the pool isn't already saturated, so wide aggregations still fan out across cores while bursty/short work concentrates.

🤖 Generated with Claude Code

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Trace-log deep-dive of the two genuine regressions

Downloaded logs.tar.zst for the relevant perf shards (SHA 6e1a7cdc1170) and diffed system.trace_log (CPU) master (left) vs this PR (right). Caveat: the trace dumps captured different numbers of runs per side, so I use the perf framework's normalized client_time/OSCPUVirtualTime for magnitudes and rely on thread-spread + hotspot identity (both run-count-robust) for the mechanism.

insert_parallel #0 (AMD, 1.21×) — parallelism loss, not a code-path regression

metric master PR ratio
client_time (wall) 0.260 s 0.315 s +21%
OSCPUVirtualTime (total CPU) 1.96 M µs 2.15 M µs +9.6%
InsertedRows 1e9 1e9 same
  • Distinct worker threads with CPU samples: master 129 → PR 14 (despite the PR trace capturing more runs). The parallel INSERT … numbers_mt(1e9) that master fans out across ~60+ pool threads/run is concentrated onto ~3-4 threads/run.
  • Same hotspots on both binaries — memcpy ← DB::Squashing::squash (INSERT block assembly) and NumbersRangedSource::generate. No new or changed hot function.
  • Wall +21% with only +9.6% more CPU, and CPU/wall efficiency dropping 0.55→0.49 → classic under-parallelization, not extra algorithmic work.

vectorize_aggregation_combinators #0 (ARM, 1.24×) — overhead-dominated micro-benchmark

metric master PR ratio
client_time (wall) 0.0455 s 0.0563 s +24%
OSCPUVirtualTime 45 k µs 56 k µs +24%
UserTime 44.6 k µs 55.6 k µs +25%
memory_usage 243632 243632 same
  • Here CPU ≈ wall (both +24%) and concurrency is ~2 threads on both sides (RealTime/wall ≈ 2), so this is not parallelism loss.
  • The query is countMerge(countState() FROM zeros(1e9)) — the aggregation itself is trivial; CPU is dominated by pipeline-executor scheduling (DB::ExecutingGraph::updateNode, devector<Node*>, progress/trace callbacks), not Aggregator. The PR's CPU shifts toward ExecutingGraph::updateNode (top leaf, ~7.4% vs 5.9%).
  • It's an overhead-dominated micro-benchmark (≈11 ms absolute delta) that is sensitive to processor-scheduling order, which the LIFO worker-wake change perturbs. No algorithmic regression in the aggregation path.

Bottom line

Neither genuine regression is a code-path/algorithmic regression — in both, the hot functions are unchanged. insert_parallel is straightforward parallelism loss from concentrating a wide INSERT onto far fewer worker threads (129→14); vectorize_aggregation_combinators is a tiny overhead-dominated query whose pipeline-scheduling cost shifts with the new wake order. Both are consistent with the LIFO concentration trade-off rather than a defect.

🤖 Generated with Claude Code

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged the latest master (the branch was ~746 commits behind and red) — clean merge, no conflicts in the ThreadPool code.

Verified after the merge:

  • Built clickhouse + unit_tests_dbms (ARM) successfully.
  • All 11 ThreadPool gtests pass, including the 4 LIFO tests (LIFOStartsManyBlockingJobs, LIFONotifyWithThreadSelfRemoval, LIFOSchedulesOnMostRecentlyIdleThread, ShrinkMaxThreadsRetiresExcessWithoutCollapsingIdlePool).
  • All 75 scheduler/resource gtests pass, including the 21 SchedulerWorkloadResourceManager tests that were the source of the earlier TSan hang reports.

The previous red CI was unrelated to this change:

  • Stateless 04295_04278_materialized_cte_in_union_runtime_set — the known ParallelReplicas UNKNOWN_TABLE flake, already fixed on master (now in the branch via this merge).
  • Performance Comparison entries (optimize_functions_to_subcolumns, query_interpretation_wide_join, tpcds #57) failed with both ::old and ::new — the queries error on the base and PR build alike, i.e. broken perf tests on master, not regressions from this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage for the current head (51105504140) — both red checks are unrelated to this PR (which only changes which idle worker thread is woken; job order is unchanged):

  • Stress test (arm_debug): Logical error: Table A.B not found in catalog raised from QueryPlan::deserialize via DistributedPlanExecutor / StatelessTaskExecutor. The same failure appears in stress tests across dozens of PRs and on master-only runs (pull_request_number = 0) on 2026-06-10 in the CI database, so it is a master-wide issue in distributed plan deserialization, not caused by this change.
  • Performance Comparison (amd_release, 4/6): all entries fail as both ::old and ::new slower (optimize_functions_to_subcolumns, array_index_low_cardinality_strings, apply_patch_parts_steps, hash_table_sizes_stats) — the master binary itself is slower than the historical baseline, and the same tests fail the same way on master-only runs on 2026-06-11. Across all 12 perf shards: 59 faster / 34 slower / 43 unstable out of 3854 queries, no significant changes attributable to the PR.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100177&sha=51105504140ccb6beebe8924eb88823f120bda7f&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. (I found no existing open issue for Table A.B not found in catalog in QueryPlan::deserialize / StatelessTaskExecutor.)

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Thanks. The Table A.B not found in catalog stress failure is a known master-wide regression that is already fixed, so no separate PR is needed.

Root cause: PR #106020 (multistage distributed queries, merged 2026-06-09 15:25Z). Worker-side distributed-plan deserialization (QueryPlan::deserialize -> DistributedPlanExecutor / StatelessTaskExecutor) re-resolves each ReadFromMergeTree source by database.name; if the table is concurrently dropped it raised a LOGICAL_ERROR (which aborts in debug/sanitizer builds) instead of a normal recoverable exception. This is STID 3215-370f, with sibling signatures 3215-3416 (arm_release) and 7594-555f / 7594-416d (std::terminate in ~DistributedQueryPlanExecutorRemote). davenger and Algunenano root-caused it.

Fix: PR #106944 "Fix logical error when table is dropped before distributed plan task deserialization", merged 2026-06-10 14:56:05Z, which closed the auto-generated issue #106906 (Logical error: Table A.B not found in catalog (STID: 3215-370f)) - that is why you found no open issue. PR #106020 was subsequently fully reverted by #107122 (merged 2026-06-11 01:37:09Z), so the code path is gone from master entirely.

Verification (CIDB): master-only (pull_request_number = 0, head_ref = 'master') catalog-family hits since the #106944 merge = 0, and since the #107122 revert = 0. This PR's failing stress check is from a run whose merge-base predates those merges; re-running CI on a head rebased past 2026-06-11 01:37Z will clear it.

Performance Comparison (amd_release): agreed, not attributable to this PR. The entries fail as both ::old and ::new slower, i.e. the master baseline itself regressed against the historical reference, and the same shows on master-only runs.

Session: cron:clickhouse-worker-slot-4:20260612-001500

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master (38e34458c94) to refresh CI past the fix/revert of the unrelated stress failure. As @groeneai confirmed above, the Table A.B not found in catalog (STID 3215-370f) stress failure came from #106020 (merged 2026-06-09), which was fixed by #106944 and then fully reverted by #107122 (merged 2026-06-11 01:37Z) — the buggy distributed-plan deserialization path is gone from master. The previous red run had a merge-base of 2026-06-09 that predated those merges; this re-merge brings the buggy path out, so the stress check should now be clean. The Performance Comparison entries were already confirmed not attributable to this PR (both ::old and ::new slower = master baseline drift). Merge is clean (only src/Common/ThreadPool.{cpp,h} + LIFO gtest changed); built unit_tests_dbms and all 35 ThreadPool/LIFO/scheduler-resource gtests pass locally.

@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 232/233 (99.57%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit e78a4da into master Jun 13, 2026
166 of 167 checks passed
@alexey-milovidov
alexey-milovidov deleted the lifo-thread-pool-scheduling branch June 13, 2026 19:15
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 13, 2026
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Jun 13, 2026
…uest`

`ResourceGuard::Request` is reused per thread via the `Request::local()`
thread-local instance. Its `exception` member is set by `failed()` but was
never cleared on reuse, so a thread that had previously run a failed resource
request kept a stale `exception`. A subsequent request scheduled on that thread
could be granted via `execute()` (no exception set), yet `Request::wait()` would
still observe the stale `exception` and throw `RESOURCE_ACCESS_DENIED`
("Resource request failed: ... Scheduler queue with resource request is about to
be destructed"), even though that request had actually been granted.

This can surface to users as a query spuriously failing with
`RESOURCE_ACCESS_DENIED` when a workload's queue is restructured/dropped (e.g.
`CREATE WORKLOAD`/`ALTER`/`DROP`) fails one request and the same worker thread
is then reused for another request that is in fact granted.

Clear `exception` in `Request::enqueue()` (the reuse reset point) so a granted
request can never observe a previous request's failure. Genuinely failed
requests still throw: `failed()` sets `exception` and `wait()` throws as before;
the value is only reset when the request is reused for a new enqueue.

Related: ClickHouse#100177

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov pushed a commit to andremm/ClickHouse that referenced this pull request Jul 2, 2026
…rowsOnZeroChecksum

The test deliberately exercises the zero-checksum guard in
`getBackupDataFileName`, which throws `DB::Exception(LOGICAL_ERROR, ...)`.
On non-debug, non-sanitizer builds (e.g. `Unit tests (amd_llvm_coverage)`)
the test passes, but `Exception::~Exception()` then logs the exception
through `ForcedCriticalErrorsLogger` because `LOGICAL_ERROR` is treated
as an "important" error code unless `markAsLogged` has been called. The
resulting `Code: 49. DB::Exception: Backup checksum should not be zero
(test.bin). (LOGICAL_ERROR)` line plus its full stack trace ends up on
the gtest binary's stderr after the test's `[ OK ]` line.

When an unrelated test in the same `unit_tests_dbms` binary later hangs
(e.g. `SchedulerWorkloadResourceManager.DropNotEmptyQueueLong` per the
report linked below), the wrapping `gdb -batch ... -ex run` runner times
out, kills the binary mid-suite, and `gtest.json` is never written. The
Praktika `from_gtest` parser then has nothing to parse and falls back to
log-scraping, which surfaces the leaked `Backup checksum should not be
zero` stack trace as a fake `-FunctionsStress` failure in CIDB. Sixteen
hits across `Unit tests (amd_llvm_coverage)` on PRs ClickHouse#100177, ClickHouse#105784,
ClickHouse#96100 over the past 60 days follow this pattern; the underlying
contributor is the chronic `SchedulerWorkloadResourceManager` /
`FunctionsStress` family hang, not the backup test.

Replace `EXPECT_THROW(..., Exception)` with an equivalent `try` block
that calls `markAsLogged` on the caught exception, mirroring the pattern
already used in `executeQuery.cpp` (commit 64a4caa "Mark fuzzer
exceptions as logged to prevent ForcedCriticalErrorsLogger") to suppress
the stray stack trace. Verified locally: built `unit_tests_dbms` in
release mode (`-O3 -DNDEBUG`, `ENABLE_TESTS=1`, no sanitizer) and
confirmed the pre-fix binary prints a 17-frame stack trace to stderr on
this test, while the post-fix binary runs the test silently with
`[ OK ]` and no trace.

Related: ClickHouse#100177

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…rowsOnZeroChecksum

The test deliberately exercises the zero-checksum guard in
`getBackupDataFileName`, which throws `DB::Exception(LOGICAL_ERROR, ...)`.
On non-debug, non-sanitizer builds (e.g. `Unit tests (amd_llvm_coverage)`)
the test passes, but `Exception::~Exception()` then logs the exception
through `ForcedCriticalErrorsLogger` because `LOGICAL_ERROR` is treated
as an "important" error code unless `markAsLogged` has been called. The
resulting `Code: 49. DB::Exception: Backup checksum should not be zero
(test.bin). (LOGICAL_ERROR)` line plus its full stack trace ends up on
the gtest binary's stderr after the test's `[ OK ]` line.

When an unrelated test in the same `unit_tests_dbms` binary later hangs
(e.g. `SchedulerWorkloadResourceManager.DropNotEmptyQueueLong` per the
report linked below), the wrapping `gdb -batch ... -ex run` runner times
out, kills the binary mid-suite, and `gtest.json` is never written. The
Praktika `from_gtest` parser then has nothing to parse and falls back to
log-scraping, which surfaces the leaked `Backup checksum should not be
zero` stack trace as a fake `-FunctionsStress` failure in CIDB. Sixteen
hits across `Unit tests (amd_llvm_coverage)` on PRs ClickHouse#100177, ClickHouse#105784,
ClickHouse#96100 over the past 60 days follow this pattern; the underlying
contributor is the chronic `SchedulerWorkloadResourceManager` /
`FunctionsStress` family hang, not the backup test.

Replace `EXPECT_THROW(..., Exception)` with an equivalent `try` block
that calls `markAsLogged` on the caught exception, mirroring the pattern
already used in `executeQuery.cpp` (commit 64a4caa "Mark fuzzer
exceptions as logged to prevent ForcedCriticalErrorsLogger") to suppress
the stray stack trace. Verified locally: built `unit_tests_dbms` in
release mode (`-O3 -DNDEBUG`, `ENABLE_TESTS=1`, no sanitizer) and
confirmed the pre-fix binary prints a 17-frame stack trace to stderr on
this test, while the post-fix binary runs the test silently with
`[ OK ]` and no trace.

Related: ClickHouse#100177

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

Labels

memory When memory usage is higher than expected pr-performance Pull request with some performance 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.

8 participants