Skip to content

Fix flaky test_mutation_with_broken_projection - #107290

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-test_mutation_with_broken_projection
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-test_mutation_with_broken_projection

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #63002

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):

...

Description

test_broken_projections/test.py::test_mutation_with_broken_projection is a chronic flaky integration test (tracked in #63002). The first CHECK TABLE on the freshly created and inserted table returns 0 (broken) before anything is deliberately broken, so the test fails with assert 1 == 0.

This is not a projection-consistency bug. A committed (Active) data part is always fully consistent on disk, projections included: a merge attaches the new projection parts and finalizes the whole part (addProjectionPart -> finalizePart -> precommitTransaction, MergeTask.cpp:2084/2088/2100) before the part becomes visible, and the visibility flip is atomic under data_parts_lock in a NOEXCEPT_SCOPE (covered parts -> Outdated, merged part -> Active, MergeTreeData::Transaction::commit, MergeTreeData.cpp:8836-8903). (Thanks to @alexey-milovidov for catching the incorrect "transiently inconsistent committed part" explanation in the original description.)

Root cause of the spurious 0. On a healthy part the only route to CHECK TABLE = 0 is a thrown exception, and transient ZooKeeper/network errors are converted to CheckResult(false) -> 0 at two catch sites: StorageReplicatedMergeTree::checkDataNext (StorageReplicatedMergeTree.cpp:10280-10285) and InterpreterCheckQuery::TableCheckTask::checkNext (InterpreterCheckQuery.cpp:149-154). checkPartImpl re-throws retryable errors (ReplicatedMergeTreePartCheckThread.cpp:398-399), but both outer catches defeat that. The aggressive background merges in this test (max_parts_to_merge_at_once=3) add ZooKeeper and IO churn during the per-part check and raise the rate of that transient error, so the failure clusters on the first CHECK TABLE.

Scope of this PR (test-only mitigation). This PR removes the dominant trigger by disabling background merges for this test only, so the assertion window is stable. It does not fix the underlying silent-0-on-transient-error behavior of CHECK TABLE; that fundamental fix (re-throw retryable errors instead of reporting the part broken) is discussed in the PR thread and is best landed as a separate PR since it is a user-visible behavior change.

SYSTEM STOP MERGES cannot be used here: on ReplicatedMergeTree it cancels merger_mutator.merges_blocker, which the replication queue checks for both MERGE_PARTS and MUTATE_PART (ReplicatedMergeTreeQueue.cpp:1746), so it would also block the test's synchronous ALTER ... DELETEs. Instead set max_bytes_to_merge_at_max_space_in_pool=1, which stops background merge selection (getMaxSourcePartsBytesForMerge returns 0, CompactionStatistics.cpp:107) while mutation selection uses a separate gate (getMaxSourcePartBytesForMutation) and is unaffected. The setting is scoped via a new disable_background_merge flag, so sibling tests (e.g. test_broken_ignored, which needs a background merge) are unchanged.

With merges disabled, the later branch around the third ALTER ... DELETE can no longer "not be broken because of a merge", so the dual-branch tolerance there is tightened to require all_2_2_0_5 to stay broken and CHECK TABLE to return 0, keeping the hardlink invariant the test covers.

Verified locally: the test passes 20/20 runs through the integration runner with the fix.

test_broken_projections/test.py::test_mutation_with_broken_projection is a
chronic flaky integration test (tracked in ClickHouse#63002): the first CHECK TABLE on
the freshly created and inserted table returns 0 (broken) before anything is
deliberately broken, so the test fails with 'assert 1 == 0'.

The table is created with aggressive background merges enabled
(max_parts_to_merge_at_once=3), but the test asserts exact per-source-part
lineage names throughout (all_N_N_0 -> _4 -> _5 -> _6) and never needs a
background merge to combine parts. When a background merge fires near the
first CHECK TABLE, CHECK observes a freshly merged or in-flight part whose
projections are transiently inconsistent and reports it broken, returning 0.

Disable background merges for this test only. SYSTEM STOP MERGES cannot be
used here: on ReplicatedMergeTree it cancels merger_mutator.merges_blocker,
which the replication queue checks for both MERGE_PARTS and MUTATE_PART, so
it would also block the test's synchronous (mutations_sync=1) ALTER DELETEs.
Instead set max_bytes_to_merge_at_max_space_in_pool=1, which stops background
merge selection (getMaxSourcePartsBytesForMerge returns 0) while mutation
selection uses a separate gate (getMaxSourcePartBytesForMutation) and is
unaffected. The setting is scoped via a new disable_background_merge flag so
sibling tests (e.g. test_broken_ignored, which needs a background merge) are
unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Not fully. The failure is a sub-1% timing race (CIDB: ~6-8 test-body hits across 90 days). Local runs pass (50/50). I could not trigger it on demand, and I say so honestly. Instead I proved the mechanism by source analysis and validated the fix's safety end-to-end through the integration runner (item e).
b Root cause explained? Yes. The table is created with aggressive background merges (max_parts_to_merge_at_once=3). The test asserts exact per-source-part lineage names (all_N_N_0 -> _4 -> _5 -> _6) and never needs a merge to combine parts. When a background merge fires near the first CHECK TABLE, CHECK observes a freshly merged or in-flight part whose projections are transiently inconsistent, marks it broken, and returns 0 -> assert 1 == 0. The 90d line distribution confirms the body failures cluster at the first check(node, table_name, 1).
c Fix matches root cause? Yes. It disables background merge selection for this test (max_bytes_to_merge_at_max_space_in_pool=1 -> getMaxSourcePartsBytesForMerge returns 0 at CompactionStatistics.cpp:107), removing the merge that races CHECK. It is not a band-aid: no assertion is weakened, no data reduced, no blanket no-random-* tag.
d Test intent preserved / new tests added? Preserved. The test still breaks projections, mutates, and verifies CHECK TABLE results exactly as before. No assertion changed. The setting is scoped via a new disable_background_merge flag so sibling tests are untouched. (Flaky-setting fix, no new test needed.)
e Both directions demonstrated? Forward direction: with the fix the test passes 50/50 through the integration runner (301s). The reverse (fails without fix) cannot be shown on demand because the race is sub-1% (acknowledged in (a)). Critically I verified the fix does NOT introduce a deadlock: SYSTEM STOP MERGES would block the test's mutations_sync=1 ALTER DELETEs (the RMT queue gates MUTATE_PART on merges_blocker, ReplicatedMergeTreeQueue.cpp:1746), whereas max_bytes_to_merge_at_max_space_in_pool leaves mutation selection on its separate gate (getMaxSourcePartBytesForMutation) untouched. The 50/50 run, which performs three synchronous ALTER DELETEs each, confirms mutations still complete.
f Fix is general, not a narrow patch? N/A (flaky test setting fix, not a code bug). The change is scoped to the one test that needs it; sibling tests (e.g. test_broken_ignored, which requires a background merge) are deliberately unchanged because the non-FINAL OPTIMIZE path respects this setting.

Tracked flaky issue: #63002 (named explicitly in that issue as the most-frequent failure; confirmed still broken).

Session id: cron:clickhouse-worker-slot-1:20260611-202600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ — could you review this? It fixes the chronic flaky test_mutation_with_broken_projection (#63002) by disabling background merges for that test only via max_bytes_to_merge_at_max_space_in_pool=1, so a background merge can't race the first CHECK TABLE and transiently report a healthy part broken. SYSTEM STOP MERGES can't be used here because on ReplicatedMergeTree it also blocks the test's mutations_sync=1 ALTER DELETEs.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jun 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b159ed3]

Summary: ✅


AI Review

Summary

This PR now only disables background merges in test_mutation_with_broken_projection and tightens one assertion around the broken projection state. The flaky CHECK TABLE = 0 path that originally motivated that workaround was fixed in master by #109465, and the linked flaky issue #63002 is already closed, so the current diff no longer matches the PR's stated contract. I would not merge it as-is without either dropping the change or re-scoping it as pure test hardening with fresh motivation and evidence.

Findings

⚠️ Majors

  • [tests/integration/test_broken_projections/test.py:686] After #109465 merged, the transient CHECK TABLE false-negative that this workaround targeted is already fixed in the base branch. The current diff now just forces this test to run with max_bytes_to_merge_at_max_space_in_pool=1, which narrows coverage away from the normal background-merge configuration without showing a remaining failure on current master. Either drop the change, or re-scope the PR as a pure test-strengthening change and update the title/body to explain why the no-merge setup is still the right contract.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: either remove the merge-disabling change now that #109465 is in base, or keep it only after rewriting the PR as a test-hardening change with current rationale and evidence.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai,

I didn't expect that projections could be inconsistent inside the data parts. Maybe it is a fundamental problem. In ClickHouse, either the data part is invisible (being created with the tmp_ prefix) or fully consistent. All changes to data parts went through mutations, where the new data part is created with hardlinks to the old one, and materializes all the missing parts while it is still not committed. When it is committed, it is fully consistent.

If projections break this approach, we are in trouble. CC @amosbird

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov you are right, and my PR description was wrong. I traced the part lifecycle and your invariant holds: there is no projection-consistency bug here. I have retracted the "transiently inconsistent committed part" wording and corrected the description.

The invariant holds (a committed/Active part is fully consistent, projections included). In a merge the new part's projection parts are attached and the whole part is finalized (checksums written) before it becomes visible:

  • MergeProjectionsStage::finalizeProjectionsAndWholeMerge: addProjectionPart (MergeTask.cpp:2084), then finalizePart (2088/2090), then precommitTransaction (2100).
  • The visibility flip is atomic under data_parts_lock in a NOEXCEPT_SCOPE: covered source parts go to Outdated (MergeTreeData.cpp:8879) and the merged part goes to Active (8890) together, in Transaction::commit (8769/8836).

So a part becomes visible only after it is fully written, exactly as you said for mutations. There is no window where a visible part has inconsistent projections.

The flaky CHECK TABLE = 0 is a CHECK-side timing artifact, not on-disk inconsistency. CHECK TABLE snapshots the visible parts by name (StorageReplicatedMergeTree.cpp:10135), then re-resolves each by name in checkPartImpl -> findLocalPart (ReplicatedMergeTreePartCheckThread.cpp:293):

  • If a background merge superseded a checked part, re-resolution returns the covering part and CHECK is lenient: "We have part X covering part Y, will not check", success = true (checkPartImpl:329-337). A committed merge by itself does not make CHECK fail.
  • The only success = false outcomes on a healthy table are a genuinely missing part, or a thrown exception (e.g. a transient ZooKeeper error in the per-part zookeeper->exists/get) that checkDataNext turns into CheckResult(name, false, ...) (StorageReplicatedMergeTree.cpp:10154-10157). Neither implies an inconsistent committed part.

I cannot prove the exact server-side cause of each historical 0 (the test records only the result value, not the server log). A captured server log for this test, from a later cluster-teardown segment, does show one such path firing (a transient ZK "Connection loss" on /parts/all_N_N_0 making checkDataNext return failure); I offer that as existence proof of a projection-independent path to 0, not as proof it caused every failure. That uncertainty is why I removed the wrong explanation rather than swap in another guess.

Why the fix is test-only. The early phase asserts the exact unmerged layout (all_0_0_0..all_3_3_0) and that broken projections survive mutations via hardlinks; a background merge would collapse those parts and rebuild the projections, so the test already assumes no merges in that window (later stages explicitly tolerate them, "can be not broken because of a merge"). Disabling background merges for this test only makes that assumption explicit and removes merge/CHECK churn during the assertion window, leaving the mutations_sync = 1 deletes untouched (mutation selection is a separate gate).

If you would prefer a different direction (making CHECK retry transient ZK errors, or having the test poll rather than disable merges), I am happy to follow your call.

@alexey-milovidov

alexey-milovidov commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

CHECK TABLE snapshots the visible parts by name (StorageReplicatedMergeTree.cpp:10135), then re-resolves each by name in checkPartImpl -> findLocalPart (ReplicatedMergeTreePartCheckThread.cpp:293)

@groeneai, What is the reason CHECK query does it this way? Can it work similarly to SELECT queries in this regard - take a snapshot of data parts, hold it during the operation, and process every data part?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Good question. Short answer: the parts snapshot is already held, and the non-replicated check already works the way you describe. The replicated path re-resolves by name on purpose, for a reason specific to replication, and that re-resolution is not what produces the spurious 0.

The snapshot is already held. getCheckTaskList builds a DataPartsVector of shared DataPartPtrs and DataValidationTasks owns it for the whole operation (StorageReplicatedMergeTree.h:1019-1045), so parts cannot be freed mid-check, same as a SELECT. StorageMergeTree::checkDataNext then checks the held part directly via checkDataPart(part, ...) (StorageMergeTree.cpp:2945/2966). That is exactly the SELECT-style behavior you are asking about, and the non-replicated table already does it.

Why the replicated path re-resolves by name. StorageReplicatedMergeTree::checkDataNext deliberately drops the held part and calls part_check_thread.checkPartAndFix(part->name, ...) (StorageReplicatedMergeTree.cpp:10152). A replicated CHECK is not only a local-data check, it reconciles the local part against ZooKeeper: it reads /replicas/<r>/parts/<name>, compares the local columns-hash and checksums against the ZK header (TABLE_DIFFERS_TOO_MUCH), and picks a recovery action (fetch-missing from another replica, detach-unexpected, recheck-later for Outdated/young parts) - ReplicatedMergeTreePartCheckThread.cpp:290-450. That reconciliation is inherently keyed on the part name plus live ZK state, and it shares one entry point (checkPartAndFix(name)) with the asynchronous background part-check thread, which only ever has a name (it pulls names off the /parts check queue, never a DataPartPtr). The findLocalPart comment documents the ZK-first ordering (ReplicatedMergeTreePartCheckThread.cpp:272-278).

So a held-snapshot CHECK is fine for the local data validation, and feasible since the snapshot is right there, but it cannot replace the ZK reconciliation, which is the whole point of CHECK on a replicated table and is name/ZK-keyed by nature.

The spurious 0 is a different bug, and it is exactly the SELECT-parity you are pointing at. A merge superseding a checked part does not make CHECK fail; that path is lenient ("We have part X covering part Y, will not check", success=true, ReplicatedMergeTreePartCheckThread.cpp:333). On a healthy table the only way to get 0 is a thrown exception. The deeper code is careful to re-throw retryable errors (isRetryableException then throw, line 401) and findLocalPart's ZK read sits outside any try at all (zookeeper->exists, line 278). But all of that is defeated at the top: StorageReplicatedMergeTree::checkDataNext wraps the whole thing in a blanket catch (const Exception &) returning CheckResult(name, false, ...) (StorageReplicatedMergeTree.cpp:10154-10157), which catches retryable ZooKeeper hardware errors (connection loss, session expired) too and turns them into success=false then 0.

StorageMergeTree::checkDataNext does not do this: it re-throws retryable exceptions (StorageMergeTree.cpp:2955-2956 / 2971-2972), so a transient error surfaces as a retryable query error, never a wrong 0. That is the real parity gap with SELECT: SELECT fails loud or retries on transient errors instead of silently returning the wrong value.

Concrete fix. The minimal fundamental fix is to make replicated checkDataNext re-throw retryable exceptions the same way the non-replicated one does (test isRetryableException before converting the catch into CheckResult(false); it is already available via checkDataPart.h). That stops every replicated CHECK TABLE from turning a transient ZK error into a spurious broken result, not just this test. I am happy to put that up as a separate PR and, if it lands, drop the test-only workaround in this one. Want me to prototype it?

…jection

With background merges disabled from table creation, the dual-branch
tolerance around the third ALTER DELETE is dead: nothing can repair the
broken projection, so all_2_2_0_5 must stay broken and CHECK TABLE must
return 0. Require that deterministically instead of tolerating either
outcome, so the test keeps proving the hardlink invariant it covers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, both points are correct. Addressed:

Point 2 (tighten the hardlink invariant) - done in e7a6009. With background merges disabled from table creation, the all_2_2_0_5 branch had no way to "not be broken", so the dual-branch tolerance was dead code. It now requires all_2_2_0_5 to stay broken and CHECK TABLE to return 0 deterministically. Verified 20/20 passes locally (amd_tsan runner), so the tightened assertion holds without a merge repairing the projection.

Point 1 (the workaround only shifts probability) - agreed. I traced the two paths that turn a healthy CHECK TABLE into 0:

  1. Merge/read race (reduced by this PR): a concurrent merge adds ZK and IO churn during the per-part check. It does not corrupt the checked part (the part is held as a DataPartPtr and a merge produces a new part rather than overwriting the source), so it is not a distinct deterministic trigger - it raises the rate of path 2.
  2. Transient error swallowed into false (the real root cause, untouched by this PR): on a healthy part the only route to success=false is a thrown exception, and transient ZooKeeper/network errors get converted to CheckResult(false) -> 0. This happens at two levels:
    • StorageReplicatedMergeTree::checkDataNext blanket catch (const Exception &) -> CheckResult(name, false, ...) (src/Storages/StorageReplicatedMergeTree.cpp:10280-10285). checkPartImpl is careful to re-throw retryable errors (src/Storages/MergeTree/ReplicatedMergeTreePartCheckThread.cpp:398-399), but this outer catch defeats that.
    • InterpreterCheckQuery::TableCheckTask::checkNext blanket catch (const Exception &) -> CheckResult{"", false, ...} (src/Interpreters/InterpreterCheckQuery.cpp:149-154), which swallows for every storage.

So this PR is a genuine but partial mitigation. It removes the merge-driven churn that dominates the failure rate in this test (the empirical result: 0 local failures across the runs above), but it does not close path 2.

Correction to my earlier reply: I said the non-replicated StorageMergeTree "surfaces a retryable query error, never a wrong 0" because it re-throws retryable exceptions (src/Storages/StorageMergeTree.cpp:3385/3401). That is only half true - the interpreter-level catch (2) re-catches that re-throw and still returns 0. The silent 0-on-transient-error is a CHECK TABLE issue, not a replicated-only one.

The fundamental fix is to make CHECK TABLE re-throw transient errors (isRetryableException, already available via checkDataPart.h) instead of reporting the part broken, at both catch sites. One subtlety: the interpreter catch was added in "Fix RMT table shutdown with check table" to swallow the shutdown ABORTED exception, and isRetryableException treats ABORTED as retryable - so the fix must still swallow shutdown-ABORTED while re-throwing ZK-hardware/network errors. This is testable: there is no failpoint that injects a retryable ZK error in the check path today, but one can be added (template: replicated_merge_tree_commit_zk_fail_when_recovering_from_hw_fault -> zookeeper->forceFailureBeforeOperation()), and the regression test would assert CHECK TABLE throws a retryable error rather than returning 0.

It is a user-visible behavior change to CHECK TABLE (transient error: silent 0 -> thrown error), so I would rather land it as a separate PR and defer the go/no-go to a maintainer. I offered to prototype it above and can put it up; this PR then keeps only the test hardening. Happy to proceed either way.

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand) - updated for the tightened assertion
# Question Answer
a Deterministic repro? Not on-demand: the flake is a sub-1% transient CHECK-vs-ZooKeeper error under merge churn (root cause in the thread). Established from the CIDB 90d line-distribution + source analysis, not a single deterministic command.
b Root cause explained? Yes. On a healthy part the only route to CHECK TABLE = 0 is a thrown exception; transient ZK/network errors are converted to CheckResult(false) -> 0 at StorageReplicatedMergeTree.cpp:10280-10285 and InterpreterCheckQuery.cpp:149-154. Aggressive background merges add ZK/IO churn that raises the transient-error rate on the first CHECK.
c Fix matches root cause? Partial by design. This test-only PR removes the dominant trigger (merge churn) via max_bytes_to_merge_at_max_space_in_pool=1; it does not change CHECK TABLE's silent-0-on-transient-error behavior. The fundamental fix (re-throw retryable errors) is proposed as a separate PR in the thread. Not a band-aid on the assertion: nothing is widened or weakened.
d Test intent preserved / new tests added? Strengthened. The all_2_2_0_5 branch now requires the projection to stay broken and CHECK TABLE to return 0 (the dual-branch "can be not broken because of a merge" tolerance is dead once merges are off), so the test still proves the hardlink invariant. No test removed or weakened.
e Both directions demonstrated? The pre-fix flake is sub-1% and not reproducible on demand (acknowledged in a). With the fix: 20/20 local passes through the integration runner, including the tightened assertion.
f Fix is general across code paths? N/A (test-only setting scoping). The scoping flag is applied only to test_mutation_with_broken_projection; sibling test_broken_ignored (needs a merge) is unaffected.
g Fix generalizes across inputs? N/A (test-only setting fix, not a code bug).
h Backward compatible? N/A for this PR (test-only). Note: the fundamental fix discussed in the thread WOULD be a user-visible CHECK TABLE behavior change (transient error: silent 0 -> thrown error), which is exactly why it is deferred to a separate PR for maintainer sign-off.
i Invariants and contracts preserved? Yes. max_bytes_to_merge_at_max_space_in_pool=1 stops background merge selection while mutation selection uses a separate gate (getMaxSourcePartBytesForMutation), so mutations_sync=1 ALTER DELETEs still complete; the hardlink/lineage invariants the test asserts are preserved and now enforced more strictly.

Session id: cron:clickhouse-worker-slot-0:20260705-210500

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.89% +0.19%
Functions 91.48% 91.49% +0.01%
Branches 77.63% 78.23% +0.60%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 1410 line(s), 61 function(s) across 36 file(s) · Details

Top files
  • src/Interpreters/InterpreterCreateQuery.cpp: 299 line(s), 3 function(s)
  • programs/keeper/Keeper.cpp: 259 line(s), 25 function(s)
  • src/Storages/MergeTree/MergeTreeData.cpp: 166 line(s), 1 function(s)
  • src/Interpreters/InterpreterSystemQuery.cpp: 155 line(s)
  • src/Parsers/ParserSystemQuery.cpp: 102 line(s)

Full report

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e7a6009

CI fully finished on this head (Finish Workflow / Mergeable Check / PR all green). No test failure rows in CIDB; the only red check is the private upstream sync.

Check / test Reason Owner / fixing PR
CH Inc sync private upstream sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260706-000000

@alexey-milovidov alexey-milovidov self-assigned this Jul 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai,

It is a user-visible behavior change to CHECK TABLE (transient error: silent 0 -> thrown error), so I would rather land it as a separate PR and defer the go/no-go to a maintainer. I offered to prototype it above and can put it up; this PR then keeps only the test hardening. Happy to proceed either way.

Yes, let's fix CHECK TABLE so it will retry retriable Keeper errors. Then the changes in the test may be unnecessary anymore.

@groeneai

groeneai commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Will do. I'll put up a separate PR that makes CHECK TABLE retry retriable Keeper errors instead of reporting the part broken, at the two catch sites that currently collapse them to 0 (StorageReplicatedMergeTree::checkDataNext and InterpreterCheckQuery::checkNext).

One care point: the interpreter catch was added to swallow the shutdown ABORTED exception, and isRetryableException treats ABORTED as retryable, so the retry will target ZooKeeper hardware/session errors specifically and keep swallowing shutdown-ABORTED. I'll add a failpoint-based regression test (inject a retriable ZK error during CHECK and assert it does not return 0 on a healthy part).

Once it lands I'll re-check whether the test-only merge-disable change here is still needed and drop it if not.

@alexey-milovidov

Copy link
Copy Markdown
Member

Opened #109465 for the fundamental fix: it makes CHECK TABLE re-throw retryable ZooKeeper errors (via isRetryableException) at both catch sites (StorageReplicatedMergeTree::checkDataNext and InterpreterCheckQuery::checkNext) instead of reporting a healthy part as broken, and adds a failpoint-based regression test. Once it lands, the test-only merge-disable change here can be re-evaluated and dropped if no longer needed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 6, 2026
A replicated CHECK reconciles each local part against ZooKeeper. A transient
Keeper hardware error (connection loss, session expired) thrown during that
reconciliation was collapsed into CheckResult(false), so CHECK TABLE returned
a spurious 0 on a healthy table. checkPartImpl already re-throws retryable
errors, but two outer catch sites defeated that:
StorageReplicatedMergeTree::checkDataNext and
InterpreterCheckQuery::TableCheckTask::checkNext.

Wrap the per-part check in ZooKeeperRetriesControl (bounded by the existing
keeper_max_retries / keeper_retry_*_backoff_ms settings) so a transient blip is
retried. On retry exhaustion the Keeper hardware error is re-thrown instead of
reported as a broken part; the interpreter catch does the same. The guard is
narrowed to Coordination::Exception with isHardwareError, so the shutdown
ABORTED exception the interpreter catch was originally added for (a plain
DB::Exception, not Coordination::Exception) is still swallowed, and genuine
corruption or missing parts still report CheckResult(false) as before.

New failpoint check_data_part_zk_hardware_error injects a retriable Keeper
error on the query check path; the regression test asserts CHECK returns 1
after a retriable error is retried and throws (not 0) when retries are disabled.

Requested by Alexey Milovidov in
ClickHouse#107290 (comment)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 6, 2026
A replicated CHECK reconciles each local part against ZooKeeper. A transient
Keeper hardware error (connection loss, session expired) thrown during that
reconciliation was collapsed into CheckResult(false), so CHECK TABLE returned
a spurious 0 on a healthy table. checkPartImpl already re-throws retryable
errors, but two outer catch sites defeated that:
StorageReplicatedMergeTree::checkDataNext and
InterpreterCheckQuery::TableCheckTask::checkNext.

Wrap the per-part check in ZooKeeperRetriesControl (bounded by the existing
keeper_max_retries / keeper_retry_*_backoff_ms settings) so a transient blip is
retried. On retry exhaustion the Keeper hardware error is re-thrown instead of
reported as a broken part; the interpreter catch does the same. The guard is
narrowed to Coordination::Exception with isHardwareError, so the shutdown
ABORTED exception the interpreter catch was originally added for (a plain
DB::Exception, not Coordination::Exception) is still swallowed, and genuine
corruption or missing parts still report CheckResult(false) as before.

New failpoint check_data_part_zk_hardware_error injects a retriable Keeper
error on the query check path; the regression test asserts CHECK returns 1
after a retriable error is retried and throws (not 0) when retries are disabled.

Requested by Alexey Milovidov in
ClickHouse#107290 (comment)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
love-star pushed a commit to love-star/ClickHouse that referenced this pull request Jul 7, 2026
… part

On a healthy part, the only way `CHECK TABLE` returns 0 (part reported broken)
is a thrown exception. Transient/retryable errors - most notably ZooKeeper
hardware errors such as connection loss or session expiration on a
`ReplicatedMergeTree` table - were silently converted into a "broken" result at
two catch sites:

- `StorageReplicatedMergeTree::checkDataNext` had a blanket `catch (const Exception &)`
  that returned `CheckResult(name, false, ...)`, unlike `StorageMergeTree::checkDataNext`
  which already re-throws retryable exceptions.
- `InterpreterCheckQuery::TableCheckTask::checkNext` also blanket-caught and returned a
  false result for every storage.

This is the false-negative behind the chronic flaky
`test_broken_projections/test.py::test_mutation_with_broken_projection` (ClickHouse#63002):
aggressive background merges add ZooKeeper/IO churn that raises the transient-error
rate on the first `CHECK TABLE`.

Now both catch sites re-throw retryable exceptions (via `isRetryableException`), so
a transient error surfaces as a retryable query error instead of a spurious 0. The
interpreter catch still swallows the shutdown `ABORTED` exception it was originally
added for (`isRetryableException` treats `ABORTED` as retryable, so it is excluded
explicitly).

Adds a `check_table_inject_retryable_zk_error` failpoint and a stateless regression
test that injects a transient ZooKeeper error during `CHECK TABLE` and asserts it
throws rather than returning a broken row for a healthy part.

Related: ClickHouse#63002
Related: ClickHouse#107290

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

Copy link
Copy Markdown
Member

@groeneai, the fundamental fix #109465 has merged into master (merge commit 20e1dcae5f06d30435d11bfc051996307d1972e7): CHECK TABLE now re-throws retryable ZooKeeper errors via isRetryableException instead of collapsing them into a spurious 0 broken result, at both catch sites (StorageReplicatedMergeTree::checkDataNext and InterpreterCheckQuery::checkNext), with a failpoint-based regression test.

That closes the transient-error path we identified as the real root cause behind test_mutation_with_broken_projection (#63002), which the merge-disable here only mitigated probabilistically. As you offered earlier, please re-evaluate whether the test-only change is still needed now:

Either direction is fine — your call.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai I refreshed this branch by merging the latest master into it (it had fallen ~8 days / 3000+ commits behind). This also pulls in the merged #109465, which is the fundamental fix for the spurious CHECK TABLE = 0 that the review thread on test_broken_projections/test.py was about, so CI now runs against an up-to-date branch that already contains that fix. The PR content itself is unchanged (still the test-only disable_background_merge change). Pushed as b159ed31eb91af98a9921210d65a71735021267e.

table_name = "test1"
create_table(node, table_name, 1)
# Asserts exact per-source-part lineage names and never needs a merge.
create_table(node, table_name, 1, disable_background_merge=True)

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.

#109465 is now in master, and that change fixed the actual flaky path here: CHECK TABLE no longer collapses retryable Keeper errors into a spurious 0, and #63002 is already closed. After that merge, this line is no longer "fix the flake"; it just changes test_mutation_with_broken_projection to run with background merges disabled all the time.

If you still want this, I think it needs to be re-scoped as pure test hardening and justified on its own merits, because it narrows the test away from the normal background-merge configuration without showing a remaining failure on current master. Otherwise I would drop it now that the underlying CHECK TABLE bug is already fixed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov thanks for the refresh.

CIDB confirms #109465 de-flaked it on its own: since that merge (2026-07-07 02:35Z), test_broken_projections::test_mutation_with_broken_projection is 8617 OK / 0 FAIL across all PRs and master. The one failure in the last 25 days (2026-07-06) predates the merge.

So the test-only disable_background_merge change here is now redundant. I'd close #107290 as superseded by #109465. Happy to close it, or leave the call to you since you're tracking the branch.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b159ed3

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync — CH Inc sync (private, not actionable by us)

No PR-caused failure; CIDB shows zero FAIL/ERROR test rows on this head. This head is @alexey-milovidov's master-merge (b159ed3) which pulls in the merged #109465; the PR content itself is unchanged (test-only disable_background_merge).

Session id: cron:our-pr-ci-monitor:20260714-070000

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… part

On a healthy part, the only way `CHECK TABLE` returns 0 (part reported broken)
is a thrown exception. Transient/retryable errors - most notably ZooKeeper
hardware errors such as connection loss or session expiration on a
`ReplicatedMergeTree` table - were silently converted into a "broken" result at
two catch sites:

- `StorageReplicatedMergeTree::checkDataNext` had a blanket `catch (const Exception &)`
  that returned `CheckResult(name, false, ...)`, unlike `StorageMergeTree::checkDataNext`
  which already re-throws retryable exceptions.
- `InterpreterCheckQuery::TableCheckTask::checkNext` also blanket-caught and returned a
  false result for every storage.

This is the false-negative behind the chronic flaky
`test_broken_projections/test.py::test_mutation_with_broken_projection` (ClickHouse#63002):
aggressive background merges add ZooKeeper/IO churn that raises the transient-error
rate on the first `CHECK TABLE`.

Now both catch sites re-throw retryable exceptions (via `isRetryableException`), so
a transient error surfaces as a retryable query error instead of a spurious 0. The
interpreter catch still swallows the shutdown `ABORTED` exception it was originally
added for (`isRetryableException` treats `ABORTED` as retryable, so it is excluded
explicitly).

Adds a `check_table_inject_retryable_zk_error` failpoint and a stateless regression
test that injects a transient ZooKeeper error during `CHECK TABLE` and asserts it
throws rather than returning a broken row for a healthy part.

Related: ClickHouse#63002
Related: ClickHouse#107290

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants