Skip to content

Fix flaky tests 03100_lwu_15_future_reads and 03100_lwu_16_future_reads - #109429

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03100-lwu-future-reads-flaky
Jul 30, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03100-lwu-future-reads-flaky

Conversation

@groeneai

@groeneai groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

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

Fixes two independent races that made the lightweight-update "future reads" tests 03100_lwu_15_future_reads and 03100_lwu_16_future_reads flaky. Both were observed on master and across several unrelated PRs as result differs with reference (also as Failed to wait for block ... extra output line, and occasionally return-code timeouts under load). No related open issue found.

1) Patch-part count race (03100_lwu_15). After the scenario, OPTIMIZE ... FINAL folds both patch parts into the base part, so the two patch parts become redundant. The background cleanup thread (MergeTreeData::clearUnusedPatchParts, gated by the remove_unused_patch_parts setting, default true) then legitimately drops them. The assertion

SELECT sum(rows) FROM system.parts WHERE ... AND startsWith(name, 'patch');  -- expects 200

races that cleanup and observes 100 (one patch dropped) or 0 (both dropped). The data is always correct: sum(v) = 799500 both with and without patch parts, because the updates are already reflected in the base part. Pinning remove_unused_patch_parts = 0 on the table keeps the redundant patch parts around until the count is read, making the assertion deterministic without weakening it. This matches 03100_lwu_01_basics.sql, which already pins the same setting for the same reason.

2) wait_for_block_allocated timeout (both tests, shared helper in parts.lib). On a busy machine the helper's polling budget (100 x 0.3s, each iteration doing a synchronous SYSTEM FLUSH LOGS zookeeper_log) could expire before the block-create event appeared in system.zookeeper_log. The failpoint only sleeps 3s, so any timeout is purely load-induced. On timeout the helper printed Failed to wait for block ... to stdout, polluting the test output and producing the result differs diff. The budget is increased to ~90s, and, matching the sibling helpers wait_for_delete_empty_parts / wait_for_delete_inactive_parts, the failure message now goes to stderr with a non-zero return so a genuine timeout fails loudly instead of silently corrupting stdout.

Both fixes were reproduced and validated locally in both directions (fails without the fix, passes with it); the three other consumers of wait_for_block_allocated (03100_lwu_13, _14, _28) continue to pass.

Two independent races made these lightweight-update "future reads" tests
flaky (seen on master and across unrelated PRs, "result differs with
reference"):

1) Patch-part count race (03100_lwu_15). After the scenario, OPTIMIZE FINAL
   folds both patches into the base part, so the two patch parts become
   redundant and the background cleanup thread (clearUnusedPatchParts, gated
   by the remove_unused_patch_parts setting, default true) legitimately drops
   them. The assertion "SELECT sum(rows) ... startsWith(name,'patch') = 200"
   then races that cleanup and observes 100 or 0. Data is always correct
   (sum(v) = 799500 with or without patch parts). Pin remove_unused_patch_parts
   = 0 on the table so the redundant patch parts are not removed before the
   count is read. This matches 03100_lwu_01_basics.sql, which already pins the
   setting for the same reason.

2) wait_for_block_allocated timeout (both tests, shared helper in parts.lib).
   On a busy machine the helper's ~30s polling budget (100 x 0.3s, each
   iteration doing a synchronous SYSTEM FLUSH LOGS zookeeper_log) could expire
   before the block-create event appeared in system.zookeeper_log, and it then
   printed "Failed to wait for block ..." to stdout, polluting the test output
   (the failpoint only sleeps 3s, so the timeout was purely load-induced).
   Increase the budget to ~90s and, matching the sibling helpers
   wait_for_delete_empty_parts / wait_for_delete_inactive_parts, send the
   failure message to stderr and return non-zero so a genuine timeout fails
   loudly instead of silently corrupting stdout.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Mechanism A: with cleanup_delay_period = 1, clearUnusedPatchParts drops the redundant patch parts within ~1s of the scenario finishing (server log shows Will drop unused patch part ... twice), so the patch rows = 200 assertion deterministically observes 100/0. Mechanism B: calling wait_for_block_allocated on a never-allocated block deterministically prints Failed to wait ... to stdout (old) vs stderr (new).
b Root cause explained? Yes. (A) OPTIMIZE FINAL folds both patches into the base part -> the two patch parts become redundant -> the background cleanup thread (clearUnusedPatchParts, gated by remove_unused_patch_parts, default true) legitimately drops them; the count assertion races that drop. Data is always correct (sum(v)=799500 with and without patch parts). (B) On a busy machine the helper's ~30s polling budget expires before the block-create event lands in system.zookeeper_log (each poll does a synchronous SYSTEM FLUSH LOGS), and the timeout message went to stdout, polluting the diff.
c Fix matches root cause? Yes. (A) remove_unused_patch_parts = 0 disables exactly the racing cleanup for that table (same idiom as 03100_lwu_01_basics.sql). (B) larger budget removes the load-induced timeout; stderr + non-zero return stop the message from polluting stdout. Neither weakens an assertion.
d Test intent preserved / new tests added? Yes. The sum(v)=799500 correctness assertion and the patch rows = 200 assertion are unchanged; pinning the cleanup setting only removes the race, it does not relax what is checked. No source code changed, so no new regression test is required.
e Both directions demonstrated? Yes. (A) remove_unused_patch_parts=1 -> patch rows drop to 0 (FAIL); =0 -> stays 200 (PASS). (B) old helper -> Failed to wait on stdout (pollutes diff); new helper -> stdout empty, message on stderr. Both tests then pass 30/30 (+ earlier 20/20) with exit code 0; sibling consumers 03100_lwu_13/14/28 still pass.
f Fix is general across code paths? N/A (test-infrastructure fix: a per-table setting pin and a shared-helper robustness change, not a C++ code bug). The parts.lib change covers all 5 consumers of the helper.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (test-infrastructure fix, not a code bug).
h Backward compatible? (maintainer-approved exception only) N/A (test-only change; no settings defaults, formats, or user-visible behavior changed).
i Invariants and contracts preserved? Yes. wait_for_block_allocated now returns 0 on success / non-zero on timeout, matching the sibling helpers wait_for_delete_empty_parts / wait_for_delete_inactive_parts; under set -e a genuine timeout fails loudly instead of silently corrupting stdout. No data-structure or concurrency invariant is touched.

Session id: cron:clickhouse-worker-slot-2:20260705-051400

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ — could you review this test-only fix? It de-flakes 03100_lwu_15/16_future_reads: (1) pins remove_unused_patch_parts = 0 on the table so the background clearUnusedPatchParts cleanup does not race the patch rows = 200 assertion after OPTIMIZE FINAL folds the patches into the base (data is always correct), and (2) makes the shared wait_for_block_allocated helper in parts.lib robust under load (larger budget, and it now writes its timeout message to stderr + returns non-zero like the sibling helpers instead of polluting stdout).

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

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6520e1b]

Summary: ✅


AI Review

Summary

This PR de-flakes the lightweight-update future-read tests by hardening wait_for_block_allocated, cleaning up the shared failpoint/table state on every exit path, serializing the five shared-failpoint callers with no-parallel, and pinning the settings that made block numbers and patch-part counts nondeterministic. I did not find any remaining blocker or major issue in the current code, and the latest CI for commit 6520e1be25897b28d8662bd6e8a230587d2d28f1 is green.

Final Verdict

✅ Approve. No new inline review comments.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 5, 2026
Comment thread tests/queries/0_stateless/parts.lib Resolved
Addresses review feedback on parts.lib. The wait_for_block_allocated
helper now returns non-zero on timeout, and its callers run it under
set -e right after enabling the server-global ONCE failpoint
rmt/smt_lightweight_update_sleep_after_block_allocation. If block
allocation never happens, the script aborts at wait_for_block_allocated
before it can wait for the background client or disable the failpoint.

ONCE failpoints stay enabled until they are consumed or explicitly
disabled, and system.fail_points is process-global (documented in
03916_system_fault_injection_points.sql), so a single genuine timeout
would arm the failpoint for a later unrelated stateless test and turn
this de-flake into a new cross-test flake. This was already a latent
leak for any query failing under set -e between ENABLE FAILPOINT and
the end of the script; the non-zero return just makes it reachable.

Add a trap cleanup EXIT to all five callers (03100_lwu_13/14/15/16/28)
that disables the failpoint and reaps the background client on every
exit path, including the timeout abort. The cleanup swallows its own
errors so it never changes the script exit code, and disabling an
already-consumed ONCE failpoint is a harmless no-op.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch, addressed in 0705d22.

You're right that turning the timeout into a non-zero return leaks the process-global ONCE failpoint under set -e: the caller aborts at wait_for_block_allocated before it can wait for the background client or disable rmt/smt_lightweight_update_sleep_after_block_allocation (which stays armed for a later test, per the note in 03916_system_fault_injection_points.sql). This was in fact a pre-existing latent leak for any query failing under set -e between ENABLE FAILPOINT and the end of the script; the non-zero return just makes it reachable.

Fix: added a trap cleanup EXIT to all five callers (03100_lwu_13/14/15/16/28) that disables the failpoint and reaps the background client on every exit path, including the timeout abort. cleanup swallows its own errors so it never changes the script exit code, and disabling an already-consumed ONCE failpoint is a no-op.

Verified on a debug build (external Keeper), both directions:

Case failpoint before script rc failpoint after
forced wait_for_block_allocated timeout, no trap 0 2 1 (leaked)
forced timeout, with trap 0 2 0 (disabled)

Also: 50x each of 03100_lwu_15/_16 with randomization = 100/100 pass, and the normal path leaves the failpoint disabled with the "Failed to wait..." message on stderr (not polluting the .reference).

The EXIT trap added in the previous commit disables the failpoint and reaps
the background client, but on the wait_for_block_allocated hard-timeout path
the script exits before its normal DROP TABLE, leaving the replicated table
(and its zookeeper path) behind. Under clickhouse-test --order=random that can
poison a later test that reuses the same zookeeper path (e.g. 03100_lwu_24
registers t_lwu_renames on the same /zookeeper/{database}/t_lwu_on_fly/ path).

Add a best-effort DROP TABLE IF EXISTS ... SYNC to the cleanup function of all
five callers (13/14/15/16/28) after the wait, guarded with || true so it never
changes the script exit code.

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

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch, addressed in cf89d9c.

You're right that the EXIT trap fixed the failpoint leak but not the table: on the wait_for_block_allocated hard-timeout path cleanup runs before the caller's normal DROP TABLE, so the replicated table and its zookeeper path survive. Under --order=random, 03100_lwu_24_renames.sh registers t_lwu_renames on the same /zookeeper/{database}/t_lwu_on_fly/ path, so a rare timeout here poisons it.

Fix: added a best-effort DROP TABLE IF EXISTS ... SYNC to cleanup (after wait, || true so it never changes the exit code) in all five callers (03100_lwu_13/14/15/16/28), so each test tears down its own table on every exit path including the timeout abort.

Verified on a debug build with a forced wait_for_block_allocated timeout (t_lwu_on_fly scenario), both directions:

Case script rc table after zk path after failpoint after
forced timeout, old cleanup (no drop) 2 present (leaked) present -> a later table on the same path fails with a metadata mismatch 0
forced timeout, new cleanup 2 gone gone 0

The timeout still returns non-zero (hard failure preserved), and 30x each of 03100_lwu_15/_16 with randomization still pass.

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.88% 85.90% +0.01%
Functions 91.48% 91.48% +0.00%
Branches 78.47% 78.51% +0.04%

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

Newly covered by added/modified tests: 100 line(s), 4 function(s) across 46 file(s) · Details

Top files
  • src/Functions/if.cpp: 7 line(s)
  • src/Storages/StorageReplicatedMergeTree.cpp: 7 line(s)
  • src/Interpreters/FileCache/FileSegment.cpp: 6 line(s), 1 function(s)
  • src/Functions/FunctionCustomWeekToSomething.h: 5 line(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionLast2Samples.cpp: 4 line(s)

Full report

@groeneai

groeneai commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — cf89d9c

Every failure below has an owner: a fixing PR (ours or external). This is a test-infrastructure-only PR (tests/queries/0_stateless/parts.lib + the five 03100_lwu_* callers); neither failure is in a code path it touches.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 04061_spilling_hash_join_overflow_limits flaky (arm relaxed-atomics parallel_hash global-JOIN-limit race; trunk, 23 unrelated PRs / 5 master in 30d) #109404 (ours, open)
Stress test (amd_tsan) / Hung check failed, possible deadlock found deadlock (chronic hung-check family) #108212 (ours, merged) / #105905 (ours, merged)

Reports:

Session id: cron:our-pr-ci-monitor:20260705-173000

groeneai and others added 2 commits July 29, 2026 12:32
The five tests 03100_lwu_13/14/15/16/28 all enable the same server-global
ONCE failpoint rmt_lightweight_update_sleep_after_block_allocation (or the
smt_ variant under s3_with_keeper). The failpoint API is name-only
(FailPointInjection::enableFailPoint / disableFailPoint take just the name,
and the SYSTEM ENABLE/DISABLE FAILPOINT grammar parses a bare identifier),
so there is no table, database or query-id key that could scope an enable
to one test. Unique table names therefore cannot make these tests safe to
run concurrently with each other.

Until this change the tests were parallel-eligible, so two of them could
interleave between one test's SYSTEM ENABLE FAILPOINT and the fiu_do_on
site in StorageReplicatedMergeTree::updateLightweight: the sibling could
consume the ONCE failpoint, or its EXIT cleanup could disable it, and the
intended 3s pause window would be lost, making the future-read scenario
scheduler-dependent again.

no-parallel makes clickhouse-test run them in the sequential group, which
executes after the parallel workers. Coverage is not lost: the runner maps
the sequential job flavor to --no-parallel, 14 stateless jobs use that
flavor, and the flaky check still reruns sequential tests via
--sequential-test-runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
The stateless test profile installs insert_keeper_fault_injection_probability
= 0.01 (tests/config/users.d/insert_keeper_retries.xml, linked in by
tests/config/install.sh). 03100_lwu_13, _14 and _28 already set it to 0
before their replicated insert; _15 and _16 did not.

Both tests then poll for the exact znode block-0000000001. The initial
INSERT allocates its block through ZooKeeperWithFaultInjection, and an
injected failure after a successful create consumes that block number, so
the retry takes the next one and the background UPDATE's block is no longer
block-0000000001. wait_for_block_allocated then polls its whole budget and
the intended pause window is lost.

Pinning the setting to 0 makes the block numbering deterministic and brings
these two tests in line with their three siblings.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6520e1be25897b1f2ba3dcbf3ee5b04b2fbfa7a1

No failures on this head, so there is nothing to assign an owner to.

Check / test Reason Owner / fixing PR
(none) 174 check-runs completed, 0 failure/timed_out/cancelled -

174 of 174 check-runs completed (56 success, 118 skipped). Config Workflow, Style check,
Fast test, Fast test (arm_darwin) and Finish Workflow all succeeded, and result_pr.json
reports the root as OK with no non-OK child. CIDB agrees: 121917 passing rows across 58 checks
for this commit and 0 rows in FAIL or ERROR.

For the record, the one failure on the previous head 5450ce072bce is resolved here:
Stateless tests (arm_binary, parallel) / 04357_distributed_alias_same_expression failed with
a reference diff and the runner classified it flaky (11 of 77 same-settings reruns failed). That
test is not part of this PR and passes on the current head.

Session id: cron:our-pr-ci-monitor:20260729-213000

@alexey-milovidov alexey-milovidov self-assigned this Jul 30, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 9331daf Jul 30, 2026
179 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 30, 2026
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 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.

3 participants