Skip to content

Fix TOCTOU race in vertical merge cancellation - #99628

Merged
Avogar merged 13 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-99578
Mar 20, 2026
Merged

Avogar merged 13 commits into
ClickHouse:masterfrom
Daedalus-Icarus:fix/issue-99578

Conversation

@Daedalus-Icarus

@Daedalus-Icarus Daedalus-Icarus commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #99578

Summary

A TOCTOU race between SYSTEM STOP MERGES and SYSTEM START MERGES could let a vertical merge continue after the horizontal stage processed zero rows, triggering:

"Number of rows in source parts (1000) excluding filtered rows (0) differs from number of bytes written to rows_sources file (0). It is a bug."

The is_cancelled() check in executeImpl and the checkOperationIsNotCanceled check in finalize could see different states of the global merges blocker if it was cleared between the two calls. Fix by latching the cancellation into the per-task is_cancelled flag so that finalize reliably throws.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix a rare logical error exception during vertical merge when SYSTEM STOP MERGES and SYSTEM START MERGES are executed concurrently.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No documentation changes needed (bug fix only).

Version info

  • Merged into: 26.4.1.52

@CurtizJ CurtizJ added the can be tested Allows running workflows for external contributors label Mar 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5e0db44]

Summary: ✅


AI Review

Summary

This PR fixes a TOCTOU race in MergeTask cancellation handling during vertical merges by latching cancellation state before finalization checks, and adds a regression test for the SYSTEM STOP MERGES / SYSTEM START MERGES sequence. I did not find a high-confidence correctness, safety, or compatibility issue in the diff.

Missing context

  • ⚠️ No CI logs or benchmark results were provided in the review context, so this review is based on code and test changes only.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 16, 2026
@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

Thanks @CurtizJ


# Start OPTIMIZE in background – it will begin merging as soon as we
# unblock merges.
$CLICKHOUSE_CLIENT -q "OPTIMIZE TABLE ${TABLE} FINAL" &>/dev/null &

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.

Maybe you don't want to call optimize or optimize final at every loop?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, you are right. I'll check soon.

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 mean you keep the loop, but not call optimize at every iteration

@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

@PedroTadim I've changed. Can you please review this change?

@Daedalus-Icarus

Daedalus-Icarus commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @PedroTadim I can't find what the issue is. I think my change is good. Could you please review this PR one more time?

@Daedalus-Icarus

Daedalus-Icarus commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @alexey-milovidov @PedroTadim
Could you please let me know what I should do?

@PedroTadim

Copy link
Copy Markdown
Member

Thanks @alexey-milovidov @PedroTadim Could you please let me know what I should do?

One of the runs says: Reason: Test runs too long (> 180s) the test has to be faster. Maybe less iterations?

Daedalus-Icarus and others added 5 commits March 18, 2026 14:11
Replace the bash test with a single SQL file to eliminate
per-statement `clickhouse-client` subprocess overhead that caused
timeouts under sanitizers. The test logic is preserved: accumulate
parts with 13 columns (vertical merge), rapidly toggle stop/start
merges, then verify data integrity.

#99628 (comment)

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

Replace the fragile cancellation-latching approach with a cleaner detection:
in `prepareVerticalMergeForAllColumns`, check if `rows_sources_count == 0`
with multiple source parts (and rows not fully accounted for by TTL filtering).
This means the horizontal stage was effectively cancelled by a racing
SYSTEM STOP/START MERGES, so throw `ABORTED` cleanly instead of hitting the
`rows_sources` assertion.

Also add `no-random-merge-tree-settings` and `no-random-settings` tags to
the test to prevent the flaky checker from overriding critical table settings
like `vertical_merge_algorithm_min_rows_to_activate`.

#99578

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

Copy link
Copy Markdown
Contributor Author

Hi @PedroTadim @alexey-milovidov I've done.
I think the integration test failures in "Integration tests (amd_llvm_coverage, 2/5)" are unrelated to this PR — all 200 errors are docker compose pull timeouts (180s) during cluster startup, a transient CI infrastructure issue. other tests passed successfully. Could you please review this again?

@Avogar Avogar self-assigned this Mar 19, 2026

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

The PR's rows_sources_count == 0 check only catches one symptom of the TOCTOU race. The same race exists in two more places:

  1. Partial horizontal writes: if is_cancelled() fires after some blocks were already processed, rows_sources_count > 0 but incomplete — the new guard doesn't fire, and the existing LOGICAL_ERROR at line 1312 still triggers.

  2. Vertical per-column stage: executeVerticalMergeForOneColumn (line 1585) checks isCancelled, returns false, then finalizeVerticalMergeForOneColumn calls checkOperationIsNotCanceled (line 1601) which sees the blocker cleared → proceeds → hits "Written 0 elements of column v1, but 1000 rows of PK columns". Running the PR's own test 1000 times in 16 threads reproduces this.

The root cause is that both isCancelled and checkOperationIsNotCanceled read the blocker's live atomic counter, and SYSTEM START MERGES can clear it between the two reads. The fix is to latch the cancellation at the two decision points:

// Horizontal stage (executeImpl, ~line 1218):
bool cancelled = ctx->is_cancelled();
if (cancelled || !global_ctx->merging_executor->pull(block))
{
    if (cancelled)
        global_ctx->merge_list_element_ptr->is_cancelled.store(true, std::memory_order_relaxed);
    finalize();
    return false;
}

// Vertical per-column stage (executeVerticalMergeForOneColumn, ~line 1585):
bool cancelled = global_ctx->isCancelled();
if (cancelled || !ctx->executor->pull(block))
{
    if (cancelled)
        global_ctx->merge_list_element_ptr->is_cancelled.store(true, std::memory_order_relaxed);
    return false;
}

Since checkOperationIsNotCanceled already checks merge_list_element_ptr->is_cancelled, the latch ensures it reliably throws ABORTED regardless of the blocker's current state. This closes the TOCTOU window for all cases, and the rows_sources_count == 0 check becomes unnecessary.

Daedalus-Icarus and others added 2 commits March 19, 2026 22:39
The previous `rows_sources_count == 0` check only caught one symptom of the
TOCTOU race between SYSTEM STOP/START MERGES. Two more cases remained:
partial horizontal writes and the vertical per-column stage.

The root cause is that `isCancelled` and `checkOperationIsNotCanceled` read
the blocker's live atomic counter, and SYSTEM START MERGES can clear it
between the two reads. Fix this by latching the cancellation at the two
decision points:

- `executeImpl`: capture `ctx->is_cancelled()` once, persist into
  `merge_list_element_ptr->is_cancelled` before calling `finalize`
- `executeVerticalMergeForOneColumn`: capture `global_ctx->isCancelled()`
  once, persist before returning

Since `checkOperationIsNotCanceled` already checks
`merge_list_element_ptr->is_cancelled`, the latch ensures it reliably throws
ABORTED regardless of the blocker's current state. The `rows_sources_count == 0`
check becomes unnecessary and is removed.

#99578

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

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 24.00% 24.00% +0.00%
Branches 76.40% 76.30% -0.10%

PR changed lines: PR changed-lines coverage: 95.24% (20/21, 0 noise lines excluded)
Diff coverage report
Uncovered code

@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

Hi @Avogar Could you review this again?

@Avogar
Avogar added this pull request to the merge queue Mar 20, 2026
Merged via the queue into ClickHouse:master with commit b35ebd0 Mar 20, 2026
159 checks passed
@Daedalus-Icarus

Copy link
Copy Markdown
Contributor Author

Thanks @Avogar @rschu1ze @PedroTadim

@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 20, 2026
filimonov added a commit to filimonov/ClickHouse that referenced this pull request Nov 7, 2026
…erge

The merge loop leaves on `is_cancelled`, then `finalize` re-reads the
action blocker in `checkOperationIsNotCanceled`. The blocker is a counter,
so a `SYSTEM START MERGES` between the two reads makes the recheck pass and
the merge commits a prefix of the rows with `error = 0`. The horizontal
path has no row-count assertion, so the data loss is silent.

Latch the observed cancellation into `merge_list_element_ptr->is_cancelled`
before leaving the loop, in both the horizontal and the vertical stage, so
the recheck throws `ABORTED` (236) and the merge is retried.

Backport of ClickHouse#99628
(a7425a1, first in 26.4.1).
Related: ClickHouse#99578

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 10, 2026
Stable 25.8 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 10, 2026
Antalya 26.3 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 10, 2026
Antalya 25.8 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 10, 2026
Stable 26.3 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 19, 2026
Stable 24.8 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
zvonand added a commit to Altinity/ClickHouse that referenced this pull request Nov 19, 2026
Stable 25.3 Backport of ClickHouse#99628 - Fix TOCTOU race in vertical merge cancellation
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-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

7 participants