Skip to content

Fix flaky 02346_text_index_parallel_replicas - #112197

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-02346-parallel-replicas-local-plan
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-02346-parallel-replicas-local-plan

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #110057
Related: #111138

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

The fix was requested in #110057. It supersedes #111138, which is closed.

02346_text_index_parallel_replicas flaps on line 3 of its output:

 15	30
 3	3
-1	1
+1	0

i.e. sum(ProfileEvents['TextIndexUsedEmbeddedPostings']) > 0 reads 0. Column 1 of the same
statement (ParallelReplicasUsedCount > 0) never flaps.

This is the fix requested in #110057. It replaces #111138, which I closed as wrong:
that PR blamed a warm global TextIndexTokensCache persisting across stateless runs, which is
impossible because the cache key is disk:part_path:index_file and every stateless run gets a
fresh database. That concession stands. The mechanism below is a different one, it comes from
the CI settings data rather than from a hand-built local probe, and the two arms that establish
it are stated at the end so you can check them.

The data

Over 60 days, 15 CIDB rows match this test name. Split by failure signature, only 6 are this
flap; the other 9 fall in four unrelated classes (5 x return code: 241, a host-OOM class,
current RSS between 41.84 and 53.68 GiB; 2 x Code: 49 from one PR's own analyzer change; 1 x Code: 36;
1 x deb-unpack server died). Those 6 flap rows are 5 distinct pull requests (#111690, #110057,
#108673, #109696, #109083) plus 1 master run, so this is cross-author flakiness rather than any
PR's own test.

Extracting the runner's Settings used in the test: line from each of the 6 rows and
intersecting them, one randomized setting is constant across all of them:

Setting Value in all 6 Control base rate
parallel_replicas_local_plan 0 153/397 = 0.385
enable_vertical_final 1 0.506
distributed_aggregation_memory_efficient 0 0.473
use_top_k_dynamic_filtering_for_variable_length_types False 0.742

The control base rate is measured over 400 failing rows of other tests from the same two
check types in the same window, i.e. the same randomizer population. It also matches the runner
arithmetic: tests/clickhouse-test:1548 draws the setting with random.randint(0, 1), and
adjust_settings_for_autopr (:1687-1700) force-sets it to 1 whenever
automatic_parallel_replicas_mode == 2, itself drawn with probability 0.25 (:1608), so
P(local_plan = 0) = 0.75 * 0.5 = 0.375. 0.375^6 is about 2.8e-3. More decisively,
parallel_replicas_local_plan is the only one of those settings with a source path to this
counter.

The mechanism

TextIndexUsedEmbeddedPostings is incremented at exactly one place,
MergeTreeIndexText.cpp:1193 in TextIndexSerialization::deserializeTokenInfo, reached from
MergeTreeIndexGranuleText::analyzeDictionaryForTokens. That is index-analysis work, performed
by whichever server does the index analysis. ParallelReplicasUsedCount is incremented in the
coordinator (ParallelReplicasReadingCoordinator.cpp:1335), which always lives on the
initiator, which is why column 1 of the probe never flaps.

With parallel_replicas_local_plan = 1 (the default),
ClusterProxy::canUseLocalPlanForParallelReplicas returns true and
executeQueryWithParallelReplicas builds a local plan for the local replica, so the initiator
reads parts itself and the counter lands in the initiator's own query_log row.

With parallel_replicas_local_plan = 0 that predicate returns false and only
ReadFromParallelRemoteReplicasStep is built. The initiator performs no local read and no index
analysis at all, so every increment happens on a follower and reaches the test's sum(...) only
through a follower's query_log row.

Measured, on a 3-replica loopback cluster

Running the test body verbatim in a fresh database and reading system.query_log per row
instead of via sum() (no type = 'QueryFinish' predicate, since the row type is itself part of
the story):

--parallel_replicas_local_plan 1

type	is_init	ep	prc	hits	misses	dict_blocks
QueryFinish	0	0	0	0	0	0
QueryFinish	0	0	0	0	0	0
QueryFinish	1	3	1	0	9	8

--parallel_replicas_local_plan 0

type	is_init	ep	prc	hits	misses	dict_blocks
QueryFinish	0	1	0	0	3	3
QueryFinish	0	2	0	0	6	5
QueryFinish	0	0	0	0	0	0
QueryFinish	1	0	2	0	0	0

The initiator row carries ep = 3 in the first arm and ep = 0 with
hits = misses = dict_blocks = 0 in the second: it did no index analysis whatsoever. Repeated
20 times, the initiator's ep was 0 in 20 out of 20 runs with local_plan = 0, and how many
followers actually perform the analysis varied run to run (ParallelReplicasUsedCount on the
initiator was 1 in 15 runs and 2 in 5).

Two controls. ParallelReplicasUsedCount on the initiator's row is non-zero in both arms, so
the ep = 0 reading is not "parallel replicas never ran". And re-running the first arm with
use_text_index_tokens_cache = 0 still gives the initiator ep = 3, so the effect is about
replica placement and not about the tokens cache.

Why the CI reruns pass

Every failing row carries the runner's own Runs: 94..113, Failed: 0 block. That is expected
and not a contradiction: local_plan = 0 is necessary but not sufficient. On top of it, no
surviving follower must have contributed the counter. Locally I did not reproduce the flap
either (sum was non-zero in 20 out of 20 runs), and I did not tune the harness until it
failed. So this PR does not claim a reproduced failure; it claims, and measures, that
local_plan = 0 moves the counter off the row the probe is anchored on, which is the dependence
that makes the assertion a race.

For completeness about what I did not observe: with local_plan = 0 a follower could in
principle also fail to contribute because the coordinator cancelled it (a cancelled replica logs
an exception row, which the probe's type = 'QueryFinish' filter excludes) or because it took a
tokens-cache hit for a part another replica had already analysed. Neither showed up in my 20
runs (0 exception rows, 0 cache hits), so I am listing them as possible and not asserting them.

The change

One SET parallel_replicas_local_plan = 1; with a comment, in the test only. No source change
and no .reference change. This restores the setting's own product default, keeps the assertion
verbatim, and leaves every other randomized setting varying.

This is the established idiom for text index tests, and three of them already do it:

It is also the same shape as #93287, which fixed an earlier flake in this same file by pinning one
parallel-replicas setting with an explanatory comment (still lines 11-12 today).

Worth adding as a second, independent reason the pin is the right lever: with
parallel_replicas_local_plan = 1 the followers stop doing the index analysis too, because
ReadFromMergeTree.cpp:2788-2796 skips it on a follower when
parallel_replicas_index_analysis_only_on_coordinator (default true) is set. So the pin does not
just add the initiator as one more candidate incrementer; it concentrates the analysis on the one
server whose query_log row the probe is anchored to.

Alternatives, in case you prefer one

  • Anchor the probe on the initial query only (query_id = initial_query_id, the form
    02950_parallel_replicas_used_count.sql uses). That narrows the assertion to what the
    initiator does. I did not do it because under local_plan = 0 the initiator's ep is 0, so it
    would turn the flaky failure into a deterministic one unless the pin is added as well.
  • Propagate follower ProfileEvents into the initiator's query_log row. Remote profile events
    currently reach the initiator only through Protocol::Server::ProfileEvents into the internal
    profile-events queue, which feeds the client display, not logQueryFinishImpl's map. That is a
    cross-cutting change to every parallel-replicas query and does not belong in a flaky-test fix,
    but say the word and I will open it separately.

How to check the two arms

--parallel_replicas_local_plan 1 : initiator query_log row has TextIndexUsedEmbeddedPostings > 0
--parallel_replicas_local_plan 0 : initiator query_log row has TextIndexUsedEmbeddedPostings = 0

Run the test body in a fresh database against a cluster of three loopback replicas, then read
system.query_log selecting ProfileEvents['TextIndexUsedEmbeddedPostings'] and
query_id = initial_query_id per row rather than sum(). The sum() in the test hides which
row the counter landed on, which is the whole point.

groeneai added 2 commits July 27, 2026 19:12
The test asserts sum(ProfileEvents['TextIndexUsedEmbeddedPostings']) > 0 read back
from system.query_log, and that column flaps to 0 while the sibling
ParallelReplicasUsedCount column never does.

TextIndexUsedEmbeddedPostings is incremented at exactly one site,
TextIndexSerialization::deserializeTokenInfo in MergeTreeIndexText.cpp, by whichever
server performs the text index dictionary analysis. ParallelReplicasUsedCount is
incremented in the coordinator, which always lives on the initiator, which is why
column 1 is stable.

With parallel_replicas_local_plan = 0, canUseLocalPlanForParallelReplicas returns
false and executeQueryWithParallelReplicas builds only
ReadFromParallelRemoteReplicasStep, so the initiator performs no local read and no
index analysis at all. Every increment then happens on a follower and reaches the
test's sum() only through a follower's query_log row, which depends on replica
scheduling rather than on the behaviour under test.

That setting is 0 in 6 of 6 genuine flap rows over 60 days, against a control base
rate of 0.385 measured over 400 failing rows of other tests from the same two check
types in the same window. Measured on a three replica loopback cluster: with
local_plan = 1 the initiator's row carries the counter (ep = 3, misses = 9), with
local_plan = 0 it carries ep = 0 with no cache activity at all, in 20 out of 20 runs.
Re-running the first arm with use_text_index_tokens_cache = 0 still gives the
initiator a non-zero counter, so the effect is replica placement and not the tokens
cache.

Pin the setting to its own product default so the initiator performs the analysis
itself. The assertion, the reference file and every other randomized setting are
unchanged. This is the same shape as ClickHouse#93287, which fixed an earlier flake in this
file by pinning one parallel replicas setting with an explanatory comment.

The comment is deliberately verbose because the pinned value equals the product
default: without stating that the test runner randomizes the setting, a future
cleanup would delete the pin as a no-op and silently re-arm the flake.

This replaces ClickHouse#111138, whose stated mechanism (a warm global TextIndexTokensCache
persisting across stateless runs) was wrong, since the cache key is
disk:part_path:index_file and every stateless run gets a fresh database.
The comment above the pin stated two supporting sub-mechanisms as fact: that a
follower increments the counter only when it wins the shared tokens-cache race for
a part, and that it reports the counter only when the coordinator did not cancel it.
Both are source-real, but neither was observed in the twenty measured runs used to
justify the pin (zero follower cache hits, zero cancellation exception rows), and
the pull request description already lists them as possible rather than asserting
them. State only what was measured.

The remaining text keeps the three clauses that are load-bearing: which counter the
probe reads and that it is incremented by whichever server performs the index
analysis, that under parallel_replicas_local_plan = 0 the initiator builds no local
plan and so the counter lands only on scheduling-dependent follower query_log rows,
and that the test runner randomizes the setting, so pinning it to its own default is
not a redundant line a future cleanup can delete. The earlier commit message called
the comment deliberately verbose for that last reason; that reason still holds, the
two unmeasured clauses were not part of it.

Comment text only. The SET statement, the assertion, the reference file and the
binary are unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Before opening this PR the diff and the description went through two review rounds, each a cold
code review plus a separate second-model pass, with every finding adjudicated individually.
Round 1 sent the diff back for a source fix; round 2 came back clean, and the final second-model
pass reported 0 findings against the exact content published here.

Counts, taken from the per-round ledgers rather than restated: cold review 5 findings in round 1
and 6 in round 2, second-model pass 1 finding in round 1 and 0 in round 2. Verdicts: round 1
7 agreed / 2 disagreed, round 2 3 agreed / 1 disagreed / 4 recorded as non-defects.

  • ❌ Blockers: none
  • ⚠️ Majors: 4, all AGREED and fixed
  • 💡 Nits: 5 AGREED and fixed, 3 recorded with evidence

⚠️ The in-test comment asserted two sub-mechanisms that this description explicitly declines
to assert
(a follower losing the tokens-cache race for a part, and a follower cancelled by the
coordinator logging an exception row rather than QueryFinish). Both are real code paths, but
neither appeared in the 20 measured runs, so the description lists them as possible and does not
assert them. AGREED, and this is the finding that caused round 1's bounce: the comment was cut
from eight lines to six, stating only the measured dependency, with identifiers backticked.
Raised independently by the cold review and the second-model pass on the same hunk.

⚠️ A refutable figure in the runner block. The description said every failing row carries
Runs: 96..113. Re-extracting the runner's own block from all six flap rows gives
[96, 104, 112, 94, 113, 113], so the minimum is 94. AGREED, corrected to Runs: 94..113.

⚠️ A refutable figure in the host-OOM class. The five return code: 241 rows were described
at a single current RSS: 41.84 GiB, but one reports 53.68 GiB. AGREED, the description now
gives the range.

⚠️ The strongest precedent was missing. The first draft cited only #93287 (same file, but a
different setting and author). AGREED: the description now lists the three text index tests that
already pin this exact setting, with their PR numbers.

💡 Countables corrected after re-deriving each from CIDB rather than from the earlier
write-up: 15 matching rows (not 13), four unrelated failure classes (not three, Code: 36 had
been dropped), 5 distinct pull requests plus one master run (not 6 pull requests -- the master
row has pull_request_number = 0 and had been counted as one), and the base rate for
parallel_replicas_local_plan = 0 is exactly 0.375 from the runner's own arithmetic, alongside
the value measured over other tests in the same window.

💡 The relationship links did not render. They sat inside the template's HTML comment.
AGREED, twice: round 1 moved the reference into the visible body, and round 2 replaced the
combined shorthand with two rendered lines carrying one full URL each, as the template asks.

💡 An @-mention used as narrative. The description referred to the requester by handle in
running prose, which notifies without needing attention. AGREED, reworded to reference the pull
request instead.

💡 The description promised "falsifiable by two commands" and then gave two expected outcomes
plus prose.
AGREED, reworded to match what is actually provided.

💡 The test would not deterministically fail if this pin were reverted -- DISAGREED as a
finding, recorded as a disclosed limitation. That is structurally true of any probabilistic
flaky-test setting pin: local_plan = 0 is necessary but not sufficient. The properties that
can be established were measured on a Build-ID-verified binary: the pin's effect (initiator
TextIndexUsedEmbeddedPostings = 3 with local_plan = 1 versus 0 in 20 of 20 runs with
local_plan = 0) and that it is load-bearing (deleting only the SET and keeping the comment
flips 18 of 18 initiator rows back to 0; with the SET present, 20 of 20 initiator rows report
the value 1 even when the runner injects 0, so the statement-level SET wins). The assertion and
the .reference are byte-identical to master, so the pin cannot mask a regression. The
description states the limitation rather than implying a reproduced failure.

💡 Is one pin enough? Recorded as a non-defect after enumerating the carriers independently:
the local-plan predicate has three inputs, of which the analyzer setting is already pinned by
this test and parallel_replicas_prefer_local_replica is not randomized by the runner. The
second-order follower index-analysis skip reads two further settings, neither randomized. A
single pin closes the predicate, so no sibling pin is added.

Every source citation in the description was re-verified independently against master in both
rounds: the single increment site, the coordinator-local counter, the local-plan predicate and
its else branch, the follower index-analysis skip, the setting default, the runner's
randomization lines, and the authorship of each cited precedent.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? The mechanism is deterministic; the flap itself is not, and I am not claiming it is. Deterministic and on demand: with --parallel_replicas_local_plan 0 the initiator's query_log row carries TextIndexUsedEmbeddedPostings = 0 in 20/20 runs, while with = 1 it carries a non-zero value. That is the dependence the fix removes. The flap on top of it (no surviving follower contributing the counter) is a race and did NOT reproduce locally in 20 runs, matching CI's own Runs: 94..113, Failed: 0 reruns on every failing row. No harness was tuned to force a failure.
b Root cause explained? TextIndexUsedEmbeddedPostings is incremented at exactly one site (MergeTreeIndexText.cpp:1193, TextIndexSerialization::deserializeTokenInfo) by whichever server performs the text-index dictionary analysis. parallel_replicas_local_plan = 0 makes ClusterProxy::canUseLocalPlanForParallelReplicas return false, so executeQueryWithParallelReplicas builds only ReadFromParallelRemoteReplicasStep and the initiator does no local read and no index analysis at all. Every increment then happens on a follower, and reaches the test's sum(...) only through a follower's query_log row, which is scheduling-dependent. That setting is 0 in 6 of 6 genuine flap rows over 60 days, against a measured control base rate of 0.385 (400 failing rows of other tests, same two check types, same window).
c Fix matches root cause? Yes. It pins the one setting whose value the data isolates and whose source path to the counter is verified, back to its own product default (Settings.cpp:7768 = true). It is not a widened bound, not a weakened assertion, not a reduced dataset, and not a blanket no-random-* tag.
d Test intent preserved / new tests added? Preserved verbatim: sum(ProfileEvents['TextIndexUsedEmbeddedPostings']) > 0 and the sibling ParallelReplicasUsedCount assertion are untouched, the .reference is unchanged, and every other randomized setting keeps varying. The test still exercises the text-index read under parallel replicas, on the local-plan path the feature documents (parallel_replicas_index_analysis_only_on_coordinator and parallel_replicas_support_projection are both documented "Effective only with enabled parallel_replicas_local_plan"). No source change, so no new regression test is owed.
e Both directions demonstrated? Yes, on a Build-ID-verified binary (efd159ce086904d9a6051c870a0cca8492d1bbd9, confirmed equal to the running server's buildId()). Mechanism direction: initiator ep = 3 with local_plan = 1 vs ep = 0 (and hits = misses = dict_blocks = 0) with local_plan = 0, 20/20. Authority direction, the load-bearing arm: with the pin and --client-option parallel_replicas_local_plan=0 injected, 20/20 initiator rows report the setting as 1 and the test passes 50/50; deleting only the added SET line (keeping the comment) makes 18/18 initiator rows report 0 with ep = 0. Also 50/50 fully randomized, and a single default run byte-identical to the reference.
f Fix is general across code paths? The counter has exactly one increment site tree-wide (git grep TextIndexUsedEmbeddedPostings -- src/ returns the declaration, one extern, and that one increment), and exactly one test asserts it (git grep -l ... -- tests/ returns only this file), so there is no sibling path to widen to. parallel_replicas_prefer_local_replica, the other input to the same predicate, is not randomized by the test runner, so pinning parallel_replicas_local_plan alone is sufficient. The sibling text-index counters share the placement hazard in principle but no test asserts them via query_log under parallel replicas.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (flaky test setting fix, not a code bug). No data type, wrapper or parameter surface is involved.
h Backward compatible? N/A (test-only). No setting default changes, no SettingsChangesHistory.cpp entry, no format or version surface, no backport.
i Invariants and contracts preserved? The invariant is: the server that performs the text-index dictionary analysis is the server whose query_log row the probe reads. The pin restores it by keeping the analysis on the initiator, where it is unconditional. Verified in both arms that ParallelReplicasUsedCount > 0 on the initiator's row, so parallel replicas genuinely still run and the assertion's first column is unaffected. Verified separately that the effect is replica placement and not the tokens cache: arm (i) re-run with use_text_index_tokens_cache = 0 still gives the initiator a non-zero counter. Test classification is unchanged across revisions (read_test_tags_and_random_settings_limits identical; both content-based skip scanners 0 hits on both revisions), and both analyzer-wording style passes are clean.

Session id: cron:clickhouse-impl-slot-46:20260727-184700

@groeneai

groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter, could you review this? It pins parallel_replicas_local_plan back to its default in one stateless test: with the setting at 0 the initiator builds no local plan and does no index analysis, so the TextIndexUsedEmbeddedPostings counter the test asserts on lands only on follower query_log rows. That value is present in 6 of 6 flap rows over 60 days. Same shape as #93287, which pinned a different parallel-replicas setting in this same file.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3122af7]


AI Review

Summary

This PR pins parallel_replicas_local_plan to 1 in 02346_text_index_parallel_replicas so the test always exercises the local-plan path that records TextIndexUsedEmbeddedPostings on the initiator instead of depending on follower scheduling. I traced the current parallel_replicas_local_plan / coordinator index-analysis behavior in the codebase and did not find a correctness or coverage regression in this test-only fix.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 28, 2026
@rschu1ze

Copy link
Copy Markdown
Member

The fix defeats the purpose of the test.

@rschu1ze rschu1ze closed this Jul 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed, and I withdraw it. Pinning parallel_replicas_local_plan = 1 removes the = 0 placement, in which the initiator builds no local plan, so it deletes coverage the test name promises.

It was also unnecessary, which I should have established before opening the PR. Per-row query_log on this test (26.8.1.1, test_cluster_one_shard_three_replicas_localhost, 20 runs per arm):

  • parallel_replicas_local_plan = 1: TextIndexUsedEmbeddedPostings = 3 on the initiator row, 0 on every follower row, 20/20.
  • parallel_replicas_local_plan = 0: 0 on the initiator row, 3 summed over the follower rows, 20/20.

The counter has a single increment site (MergeTreeIndexText.cpp:1193, dictionary deserialization), so it is charged to whichever server performs the index analysis. Since the assertion sums over all rows it sees either placement, and it passed in 53/53 serial runs with parallel_replicas_local_plan = 0. That setting was 0 in 6 of 6 failing CI rows, but a correlation is not a cause, and my measurements say the = 0 placement on its own is not sufficient to produce 1 0.

So I have not reproduced the failing direction and I do not have a mechanism worth proposing. I also checked the guess that a cancelled replica could be the one that did the analysis while the probe filters type = 'QueryFinish': cancelled rows do keep their ProfileEvents, but in my runs they appeared only in the local_plan = 1 arm and never in the = 0 arm, which is the wrong way round for this failure, so I am dropping that idea too.

Before I spend more on it: do you consider a ProfileEvents counter a sound oracle for this test at all under parallel replicas, or would you rather the second column asserted something else?

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.

3 participants