Skip to content

Wait for background tasks before each storage memory checkpoint - #121545

Open
groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:storage-memory-profiler-wait-background-tasks
Open

groeneai wants to merge 10 commits into
ClickHouse:masterfrom
groeneai:storage-memory-profiler-wait-background-tasks

Conversation

@groeneai

@groeneai groeneai commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

The Storage memory check could attribute a finished mutation task to either side of a heap-profile checkpoint. mutations_sync = 2 waits until the mutation is applied, but the background executor can retain and destroy its task later. This produced equal-and-opposite allocation changes in adjacent scenarios and failed otherwise unrelated pull requests.

Before each checkpoint, the profiler now pauses scheduling on all four MergeTreeBackgroundExecutor instances, waits for every already accepted task and foreground task-slot reservation to be released, and keeps scheduling paused through the jemalloc refresh and heap dump. The wait uses the executor's condition variable and a 30-second deadline: there is no polling or sleep, and a new task cannot enter after the idle observation.

Task scheduling transfers the producer's reference through BackgroundJobsAssignee into the executor before accepted work can run. This makes an idle executor imply that the task objects accepted through an assignee have also been destroyed, rather than merely that the executor released its own references.

Deterministic executor tests verify that the checkpoint wait includes task destruction, that trySchedule remains blocked until the checkpoint guard is released, and that a scheduling caller held after enqueue no longer retains the completed task.

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

The Storage memory check now takes heap-profile checkpoints only after background executor work is destroyed and while new scheduling is fenced.


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

`Storage memory check` reds green PRs. On ClickHouse#113201 at 996e0be, a PromQL-lexer-only diff that
cannot touch MergeTree, `05_multiple_tables.sql` reported master=+183,456, PR=+250,512,
change=+67,056 bytes (36.6%):
https://github.com/ClickHouse/ClickHouse/actions/runs/35584353906/job/106535103120

`04_add_projection.sql` ends with MATERIALIZE PROJECTION ... SETTINGS mutations_sync = 2.
StorageMergeTree::waitForMutation returns when the mutation is applied, signalled from inside
the task's own step; the task object itself is destroyed later, on the executor thread, in
MergeTreeBackgroundExecutor::routine's release_task. The profiler measured immediately after
each scenario file, so a task still alive at the after_04 dump inflated that delta by +X and
its release deflated after_05 by the same -X. The job only fails on a positive change
(ci/jobs/storage_memory_check.py), so the cancelling half was always silently OK, and whichever
arm lost the race decided which scenario turned red.

Measured from the production report for 996e0be: 04 = -67,120, 05 = +67,056, sum -64, with
every large 04 row the same stack negated in 05 (two Settings copies at 16,648 bytes each,
ThreadGroup::ThreadGroup, MutateTask, MutationsInterpreter): 60,960 of 67,056 bytes, 90.9%.
Over the last 1,440 CI runs with data, 8 of 68 scenario FAILs have that shape, 7 at 04/05 and
one at 01/02.

The profiler now waits for all four background executors to report zero outstanding tasks
before every heap dump. Zero implies the memory is already freed: the metric is incremented in
TaskRuntimeData's constructor at schedule time and decremented in its destructor, after
resetTask() has destroyed the task, so it also covers pending tasks that never started.
src/Storages/MergeTree/tests/gtest_executor.cpp already asserts this metric is zero as a
quiescence predicate. The wait is bounded at 30 seconds and then throws TIMEOUT_EXCEEDED, so a
genuine leak or hang fails the job loudly instead of being measured; the normal case costs no
measurable time (96 s against 97 s for the whole sequence).

Excluding the mutation stacks instead would blind the check to real regressions in mutation
code, which is what it exists to catch. It is also unnecessary: once the transient task is
gone, the genuine content of these two scenarios is +192 and +1,008 bytes, both below
STORAGE_CHANGE_THRESHOLD_BYTES, so no threshold and no exclusion list needs widening.

Validated locally by driving the job's own comparison code (analyze_heap_profiles,
compute_cross_version_diff and the significance rule) over two heap-profile sets, with a
local-only patch that delays release_task to widen the race deterministically. Unfixed, with
the delay on the master arm only, scenario 05 FAILs and 236 cross-diff rows are master-arm-only
releases summing 194,752 bytes, of which 120,816 are the mutation-task stacks. Fixed, same
forcing: 2 rows and 544 bytes, and zero from the mutation stacks. Same-binary timeout A/B: a
40 s delay exits 1 with "Background tasks did not finish in 30 seconds" at the after_03
checkpoint, a 300 ms delay exits 0 over all nine, and the unfixed binary under the same 40 s
delay exits 0, so the error comes from the drain observing a live task and not from the
scaffold. A 5 s delay costs the fixed binary 107 s against the unfixed binary's 98 s,
reproduced twice, so the wait is real.

The master arm binary comes from the merge base, so this takes effect on both arms only once
it is on master.

Requested by @ alexey-milovidov on
ClickHouse#113201 (comment)
Related: ClickHouse#121364, which fixes a different arm of the same job.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 22, 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; 2 findings; bounded: 1 full pass +
1 fix round + 1 delta recheck), plus my own cold read of the diff taken before opening the
validation evidence.

# Sev Finding Verdict Evidence / action
1 ⚠️ The drain does not make the checkpoint quiescent: an assignee on BackgroundSchedulePool can trySchedule a new task after the counters read zero and before dumpProfile DISAGREE Real but not red-producing, and no better remedy exists at this layer. A task in that window has only been constructed and queued, while the 60,960 of 67,056 bytes that dominate the measured pair are allocated during executeStep. Scenario 04's master-side delta lies inside a 3,728-byte band in 1,434 of 1,439 CI runs and all 5 exceptions pair 1:1 with the 5 low 05 draws this PR removes, so a window able to inject measurable mass would have widened that band; significance needs both > 1,024 B and > 1.0% (storage_memory_check.py:317-319). Preventing the scheduling is not available: SYSTEM STOP MERGES is merges_blocker.cancel() (StorageMergeTree.cpp:3699) and scheduleDataProcessingJob returns at :2215 before selectPartsToMutate at :2228, so it would also stop the MATERIALIZE mutations that 03 and 04 exist to measure. Declared as a residual in the PR body, not hidden.
2 ⚠️ No deterministic evidence that the drain blocks on a live finished task or exercises its timeout path DISAGREE All three legs exist on Build-ID-verified binaries; the reviewing model reads the diff, not the validation record. Forced delay at the top of release_task (local scaffold, never committed): unfixed, scenario 05 shows 236 master-arm-only release rows summing 194,752 bytes of which 120,816 are the production mutation-task stacks; fixed, 2 rows and 544 bytes with zero mutation content. Timeout: same binary, 40,000 ms exits 1 with Background tasks did not finish in 30 seconds, 300 ms exits 0 over all nine checkpoints, and the unfixed binary under the same 40,000 ms exits 0, so the error comes from the drain and not from the scaffold. An injected 8 MiB-per-table retention stays 99.2-100.5% visible through the drain. The scaffold is needed because the unforced race fires in about 5 of 1,440 runs per arm.
3 💡 The comment on the metric says it is decremented "after the task object is destroyed"; the destructor body decrements before its own member is destroyed AGREE Noted, not blocking. release_task calls resetTask() (MergeTreeBackgroundExecutor.cpp:292) before dropping the last reference at :317-320, which the commit message states explicitly; the only path that skips resetTask() runs synchronously inside DROP TABLE and completes before any checkpoint.

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

Declared limits, so they are read as limits and not as claims:

  • BackgroundSchedulePool is not drained: its tasks are periodic and re-arm, so a zero-wait would never converge.
  • The 01/02 carrier in the breadth table is inferred from its conserved sums; its stacks were never measured, because that report has since been overwritten by a re-run.
  • The local A/B runs a Debug build whose per-run variance is far above the 1,024-byte threshold, so the local verdict for scenario 05 does not clear; the oracle is the presence or absence of the conserved pair (194,752 to 544 bytes, and 120,816 to 0 from the mutation stacks). Scenario 04's local number is unusable in both directions because of about 28.8 MB of one-time first-touch initialization, so the 04 half of the pair is claimed from the production report only.
  • The master arm binary comes from the merge base, so this takes effect on both arms only once it is on master.

@clickhouse-gh clickhouse-gh Bot closed this Sep 22, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: a local-only patch sleeping at the top of release_task (CH_SCAFFOLD_RELEASE_DELAY_MS=300) holds a finished task past the point mutations_sync = 2 returns, and with it on the master arm only the job's own comparison code reports the conserved pair and a 05_multiple_tables.sql FAIL on every run. Scaffolding, not in this PR.
b Root cause explained? mutations_sync = 2 returns when the mutation is applied, not when the background task that ran it is destroyed later on the executor thread in MergeTreeBackgroundExecutor::routine; the profiler dumps immediately after each scenario file, so a task still alive at after_04 inflates that delta and its release deflates after_05 by the same amount, and only a positive change fails.
c Fix matches root cause? Yes: the checkpoint is made quiescent, in the measuring instrument. No threshold widened, no stack-prefix exclusion, no scenario edited; excluding the mutation stacks would blind the check to real regressions in mutation code.
d Test intent preserved / new tests added? Nothing is weakened, the drain only delays the measurement. No test file: the change is confined to an example binary with no SQL-visible behaviour, so the oracle is an A/B of the job's real comparison code against a forced race plus a retained-allocation control that must stay visible.
e Both directions demonstrated? Yes, with the job's own comparison code. Unfixed, master arm forced: the conserved pair is present and 05 FAILs. Fixed, same forcing: scenario 05's master-arm-only releases go from 194,752 bytes over 236 rows to 544 bytes over 2, and the mutation-task stacks from 120,816 to 0. The local 05 verdict itself does not clear (a Debug build's variance is far above the 1,024-byte threshold), so the oracle is the pair's presence or absence. Same-binary timeout A/B: 40 s forcing exits 1 with Background tasks did not finish in 30 seconds, 300 ms exits 0 over all nine checkpoints, and the unfixed binary under 40 s exits 0.
f Fix is general across code paths? All four background executors are drained (merges/mutations, moves, fetches, common), since they share the TaskRuntimeData increment/decrement contract and so the same exposure; both measurement sites are treated identically and the drain sits in the loop, so the unmeasured warm-up pass is covered. 07_many_parts.sql's existing SYSTEM STOP MERGES is left alone: it suppresses merge selection, the other half.
g Fix generalizes across inputs? Not type-shaped: the input space is the scenario set and the executor set, and the drain is unconditional, so scenarios with no background work read zero and return immediately (96 s versus 97 s unfixed).
h Backward compatible? Yes: no setting, no SettingsChangesHistory.cpp entry, no format or on-disk change, a private method of an example binary. Worst case is a bounded 30 s stall per checkpoint, well inside the job's 1800 s subprocess timeout.
i Invariants and contracts preserved? The drain waits, it never cancels or reschedules, so what is measured is unchanged. Zero implies the memory is already freed: the metric is decremented by ~TaskRuntimeData, after resetTask() has destroyed the task. No self-deadlock: the decrement happens on executor threads and the main thread holds no storage lock between scenario files. Before any storage exists the metrics are zero and it is a no-op, and a genuine leak or hang surfaces as TIMEOUT_EXCEEDED and a job ERROR rather than a memory FAIL.

Session id: cron:clickhouse-impl-slot-6:20260922-050300

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a319420]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_binary) DROPPED
Build (amd_release) DROPPED

AI Review

Summary

The PR fences all four background executors during storage heap checkpoints and transfers task ownership through BackgroundJobsAssignee. The three earlier inline findings are addressed in a319420be2a925b9dcc2f43a577df4af2cba541c. One new Major remains: exception cleanup in the checkpoint test can hang the unit-test process.

Findings

⚠️ Majors

  • src/Storages/MergeTree/tests/gtest_executor.cpp:270: SchedulingPauseWaitsForTaskDestruction starts a task blocked on finish_task, then creates an async thread without failure cleanup. If std::async throws, the countdown is skipped and the latches are destroyed before the executor joins its blocked worker. An allocation failure at line 293 similarly joins the async worker while it still waits on release_pause. Declare synchronization objects before the executor and ensure exception cleanup releases both waits before their respective joins.

💡 Nits

  • src/Storages/MergeTree/tests/gtest_executor.cpp:140: CI already reports six missing [[nodiscard]] attributes on the new helpers' getStorageID, getPriority, and getQueryId overrides. Address the existing clang-tidy report. No inline finding was added for this CI-reported issue.
Missing context / blind spots
  • ⚠️ No configured local build or test binary was available, so the new executor tests were reviewed statically, not executed. A successful focused run after fixing cleanup would close this validation gap.
Final Verdict

Status: ⚠️ Request changes

Make the checkpoint test release its blocked workers and preserve synchronization-object lifetimes on exception paths.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 22, 2026
@groeneai
groeneai requested review from qoega and tavplubix September 22, 2026 10:51
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 3830e91b4d9e4667e978726aa027bdf151b547e2 with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3d3569d

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 the previous release leaves AggregateFunction(countResample(10, 5, 1), ...) tables that the upgraded server refuses to attach: Code: 69 ... The range given in function countResample is empty (ARGUMENT_OUT_OF_BOUND), logged by AsyncLoader::worker #121590 (external, merged into 26.9, not yet in a published release: see below)
Upgrade check (amd_release) / The mutation submitted before the upgrade was not finished the runner's system.mutations probe returns an empty result on that startup, and an empty probe is reported as an unfinished mutation instead of as a failed probe #121315 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above, no independent leaf #121590 and #121315, as above

Neither row belongs to this diff, which touches only src/Examples/storage_memory_profiler.{cpp,h} and cannot affect the upgrade path. Both are fleet-wide and new, measured in CIDB over 30 days: the attach failure on 16 distinct PRs, first row ever at 2026-09-21 23:39 UTC; the probe row on 46 distinct PRs since 2026-09-20 22:22 UTC. The 162 cancelled conclusions on this head are a superseded earlier attempt, not failures to own; the live attempt completed with the three reds above and nothing else.

One caveat on the first row, so nobody tries to clear it by merging master. #121590 rewrites the previous release's 05079 and 05211 on the 26.9 branch, so it is absent from master by construction: the tree this job actually built (74487ade1ae0, the confirmed checkout of job 106759823771) scores 0 for the fix, and so does live master, while the fix commit itself scores 1. The upgrade check clones the newest published 26.9 release, today v26.9.2.8-stable, and compare(4d46c03d0066...v26.9.2.8-stable) is behind by 9 commits, so that release predates the fix. The row clears when the next 26.9 patch release is published.

Session id: cron:our-pr-ci-monitor:20260923-010313

groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Nov 12, 2026
ThinLTO inlining and identical-code folding can attribute equal live allocations to different container or column specializations. Anchor cross-build stacks at the stable ClickHouse caller so the differential flamegraph does not show balanced allocation plumbing as regressions and improvements.

Observed in https://s3.amazonaws.com/clickhouse-test-reports/PRs/121083/30a51e18fa3534743e68311fb456773acefb760d/pr/storage_memory_check/storage_memory_report.html

Related: ClickHouse#121083
Related: ClickHouse#121545
@clickhouse-gh clickhouse-gh Bot added comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. and removed comp-testing Test content only (no production code). labels Nov 19, 2026
ASSERT_TRUE(executor->trySchedule(std::make_shared<BlockingExecutableTask>(task_started, finish_task, task_destroyed)));
task_started.wait();

auto pause = std::async(

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.

[Major] Unblock the test workers on exception paths

The task accepted at line 267 is already waiting on finish_task when this std::async starts. If creating the async thread throws std::system_error (for example, thread exhaustion), the countdown at line 289 is skipped. Unwinding then destroys the latches before executor, whose destructor joins the worker still waiting on finish_task. This can hang the entire unit-test process and leaves the worker referring to destroyed synchronization objects. There is another blocking unwind if the allocation at line 293 throws: destroying the async future joins its worker before anything releases release_pause.

Declare the latches before the executor and add cleanup that releases each outstanding wait before its corresponding future/executor joins, including when async creation itself fails. Moving the declarations alone does not unblock the workers.

This branch has not been deployed

No deployments
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 comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants