Skip to content

Fix flaky 04257/04258 text-index ProfileEvents assertions under parallel replicas - #112263

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-04257-text-index-parallel-replicas
Jul 30, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-04257-text-index-parallel-replicas

Conversation

@groeneai

@groeneai groeneai commented Jul 28, 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

04257_text_index_lazy_profile_events and 04258_text_index_lazy_intersect_heap assert that the
TextIndexLazy* ProfileEvents fire, reading them from system.query_log. Under parallel replicas the
assertions intermittently see 0 for one or more events, e.g.

 all events fired across tagged queries:
-1	1	1	1	1	1	1	1	1
+1	1	1	1	1	1	1	0	0

The events do fire; they are counted on a row the assertion does not select.

PostingListCursor::~PostingListCursor increments six of the nine counters in the destructor
(src/Storages/MergeTree/MergeTreeIndexTextPostingListCursor.cpp:111-125), i.e. on whichever thread
destroys the cursor, which is the replica that read the granule; the other three are incremented at
:166 and :1116/:1134, equally on the reading replica. Remote ProfileEvents are not merged into the
initiator's query_log row: the packet the initiator receives goes into
CurrentThread::getInternalProfileEventsQueue() (RemoteQueryExecutor.cpp:808-812), which is drained only
for transmission to the client (ProfileEventsExt.cpp:194, reached only from
TCPHandler::sendSelectProfileEvents at TCPHandler.cpp:1838), while the query_log column comes from the
thread-group snapshot (ProcessList.cpp:892 -> executeQuery.cpp:719 -> QueryLog.cpp:265-273).

So the counters land on secondary query_log rows, whose current_database is not the test database (the
parallel-replica cluster entries declare no default_database, so the secondary session keeps the server
default), and the assertions' current_database = currentDatabase() predicate excludes them.

04257's table is a single granule (2000 rows, index_granularity = 8192), so each tagged query has one
mark, served by exactly one replica; four of its nine columns are fed by exactly one query each, so those
columns drop individually and the observed shapes differ between occurrences. 04258's table is larger
(50000 rows, so at least seven granules), which is also why its exposure is only latent: with marks spread
over the replicas, the initiator usually gets some of them and the counters show up on its own row anyway.

The engine behaviour is correct - ProfileEvents are process-local counters and the initiator does not own
counters incremented on a peer. The test predicate is what is wrong, so that is what this PR changes: both
assertions resolve the initiator query ids by current_database and then aggregate over every row of those
queries via initial_query_id, the same idiom already used by
04201_max_bytes_ratio_before_external_join_distributed.sh:112-133,
02875_parallel_replicas_remote.sql:13-16 and 02950_parallel_replicas_used_count.sql:22.

This only widens the row set: an initiator row has initial_query_id = query_id
(Context.cpp:3607-3608), so it is still selected, and the secondary rows of the same queries are selected
too. For sum(...) > 0 assertions that can turn a spurious 0 into the expected 1 and nothing else.

All twelve assertion expressions, their aliases and the expected output are unchanged, so the "every event
must fire" contract is preserved verbatim and parallel-replica coverage of the lazy text-index read path is
kept. No tag, no setting pin, no .reference change: 2 files, +32/-4.

Unlike the two SQL precedents above, the assertion queries here do not additionally pin
enable_parallel_replicas = 0 / parallel_replicas_for_non_replicated_merge_tree = 0 on themselves. That
is not needed for correctness: currentDatabase() is constant-folded on the initiator before the query is
distributed (currentDatabase.cpp:22,49-52), and a query's own secondary rows are written after it has
finished reading, so the CTE can neither resolve against the wrong database nor race its own rows.

04258 is fixed together with 04257 because it is the same carrier - the same lazy counters (:122-124
before this change), the same current_database predicate, no guard; its failure mode is the same one, just
less likely to be hit. Of the 20 text-index tests that read
ProfileEvents from system.query_log, 17 already carry no-parallel-replicas; the only other one that
does not is 02346_text_index_parallel_replicas.sql, which deliberately asserts parallel-replica behaviour
and already handles the secondary rows its own way, by matching them on the query text. None of those is
touched.

Verification

parallel_replicas_local_plan is randomized 0/1 by the test runner (tests/clickhouse-test:1548). Forcing
it to 0 serves every mark remotely and makes the flake deterministic; the fix was measured in both
directions on a 3-replica loopback cluster:

parallel_replicas_local_plan predicate 04257 04258
0 before 0 0 0 0 0 0 0 0 0 0 1 0
0 after 1 1 1 1 1 1 1 1 1 1 1 1
1 after 1 1 1 1 1 1 1 1 1 1 1 1
parallel replicas off after 1 1 1 1 1 1 1 1 1 1 1 1

With the current_database filter removed, the event-bearing rows are visibly the secondary ones
(is_initial_query = 0, current_database = 'default'), and all 24 of them resolve to an initiator
query_id through initial_query_id - the premise the new predicate relies on. Reverting only the outer
WHERE on the fixed files reproduces the failure exactly, which pins the predicate as the load-bearing
change. Both files then ran 50 times with randomized settings and 50 times without, 200/200 green.

Note the tests deliberately do not pin parallel_replicas_local_plan or
automatic_parallel_replicas_mode. Pinning them would make the assertion always take the remote path, but
it would also fix the topology the test runs under, and the point of leaving them randomized is that the
assertion must hold under every topology the lane can produce - which is what the four rows above show. The
consequence is that any single run may or may not exercise the remote path, so the fix is not observable
from one green run; the deterministic evidence is the forced-remote arm.

04258's negative assertion (BruteForceIntersections = 0) is the one place a wider row set could in
principle turn a pass into a failure. It cannot here: all three of its tagged queries set
text_index_lazy_intersection_density_threshold = 1.0, which forces leapfrog on whichever replica runs
them, so no replica increments the brute-force counter for those query ids. It stayed green in every arm
above.

Correction to my earlier comment on #111918

In #111918 (comment) I proposed pinning the
tests with SET enable_parallel_replicas = 0. That would remove parallel-replica coverage of this read
path for no reason, so this PR takes the different route above and selects the rows that own the events
instead.

That comment also mis-attributed the breadth, and my first attempt at correcting it was itself too narrow
because it only looked back 30 days. Over 60 days, 04257 shows this exact signature on three unrelated
PRs, all on lanes whose name contains ParallelReplicas (only those lanes get
config.d/enable_parallel_replicas.xml, via --parallel-rep at tests/config/install.sh:484-485):
#112008 (columns 8 and 9), #111918 (column 6) and #97261 (column 6, 2026-06-11, outside the window I
originally queried). A fourth row, the all-nine-zeros one, is on an amd_asan_ubsan, distributed plan
lane, which does not enable parallel replicas; it is collateral from a host-memory-pressure job (131
failures in that job, 120 of them memory limit exceeded) and its own recorded settings show
parallel_replicas_local_plan 1. The other 04257 rows in that window are unrelated classes: Code: 241
host memory pressure, and one Code: 36 settings error. For 04258 the recorded failures are host memory
pressure plus a cluster of self-caused ones on the branch that introduced the test, so its exposure to this
mechanism is latent rather than observed. This fix therefore addresses the parallel-replica shapes; it is
not expected to remove reds caused by host memory pressure.

A tracking issue was also requested. I do not open issues on my own initiative, so that offer still stands
on the #111918 thread.

Version info

  • Merged into: 26.8.1.431 (included in 26.8 and later)

04257_text_index_lazy_profile_events and 04258_text_index_lazy_intersect_heap
assert that the TextIndexLazy* ProfileEvents fire, reading them from
system.query_log. Under parallel replicas they intermittently see 0 for one or
more events.

The events do fire, but they are counted on a row the assertion did not select.
PostingListCursor::~PostingListCursor increments six of the nine counters in the
destructor, and the remaining three are incremented in buildPostingSegment and
lazyIntersectPostingLists, so all of them are counted on whichever replica reads
the granule. Remote ProfileEvents are not merged into the initiator's
system.query_log row: the packet the initiator receives is pushed into the
internal profile events queue, which is drained only for transmission to the
client, while the query_log column comes from the thread group snapshot. The
counters therefore land on secondary query_log rows, whose current_database is
default rather than the test database, so the assertions'
current_database = currentDatabase() predicate excluded them. Each test table is
a single granule, so a tagged query's one mark is served by exactly one replica
and columns fed by a single query drop individually.

ProfileEvents are process-local counters and the initiator legitimately does not
own counters incremented on a peer, so the engine behaviour is correct and the
test predicate was wrong. Both assertions now resolve the initiator query ids by
current_database and aggregate over every row of those queries via
initial_query_id, the idiom already used by
04201_max_bytes_ratio_before_external_join_distributed,
02875_parallel_replicas_remote and 02950_parallel_replicas_used_count. All
assertion expressions and the expected output are unchanged, so parallel-replica
coverage of the lazy text-index read path is kept and no assertion is relaxed.

04258 is fixed alongside 04257 because it is the same carrier: the same lazy
counters, the same predicate, no guard. The other text-index ProfileEvents tests
already carry no-parallel-replicas, and 02346_text_index_parallel_replicas
deliberately asserts parallel-replica behaviour, so neither is touched.

Verified by forcing parallel_replicas_local_plan = 0 on a three-replica loopback
cluster, which serves every mark remotely and makes the failure deterministic:
both files fail before the change and pass after it, in that regime, with a
local plan, and with parallel replicas disabled. Reverting only the outer WHERE
on the fixed files reproduces the failure exactly. Both files then ran 50 times
with randomized settings and 50 times without, all green.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand) - 7 findings across 2 rounds: 6 agreed and fixed, 1 disagreed with evidence

Before opening this PR I reviewed it myself against the resulting code, then had a second model
review it independently, then adjudicated every finding. The diff is test-only, so all agreed
findings landed in the description rather than in code.

❌ Disagreed, with evidence

remote-path-not-pinned (major) - "The tests can pass with the new predicate reverted, because
the tests pin neither parallel_replicas_local_plan nor automatic_parallel_replicas_mode; pin
both, or add an oracle proving secondary rows contributed."

Every premise is correct and I re-verified each one: neither file pins those settings;
tests/clickhouse-test:1548 randomizes parallel_replicas_local_plan (default true,
Settings.cpp:7768); tests/clickhouse-test:1608 picks automatic_parallel_replicas_mode = 2 with
probability 0.25; and Context::canUseTaskBasedParallelReplicas requires that mode to be 0
(Context.cpp:8428-8432). So an individual CI run can indeed execute every tagged query locally and
pass even with the old predicate.

I still disagree, because the necessary step - that pinning makes the remote path deterministic and
so turns this into a valid regression test - does not hold, and because both suggested remedies are
worse than the status quo:

  • Parallel replicas are only enabled on lanes that pass --parallel-rep
    (ci/jobs/functional_tests.py:163 -> tests/config/install.sh:484-485, which link the cluster and
    the forcing profile). On every other stateless lane there is no cluster at all, so
    parallel_replicas_local_plan = 0 is inert and the queries still run locally. Pinning buys
    determinism on one lane family and nothing anywhere else, so it cannot deliver the property the
    finding asks for.
  • The alternative remedy is affirmatively wrong: an oracle such as
    countIf(is_initial_query = 0) > 0 evaluates to 0 on every lane without parallel replicas, which
    would turn two currently-green tests into permanent failures on almost every stateless lane.
  • Liveness is established by the right instrument instead: the forced-remote arm
    (parallel_replicas_local_plan = 0 on a 3-replica loopback cluster) fails 100% of the time with
    the old predicate and passes with the new one, and reverting only the outer WHERE on the fixed
    files reproduces the failure byte-for-byte. For a flakiness fix that is the proof that the change
    is load-bearing; probabilistic per-run exercise in CI is inherent to the class.
  • Pinning would also delete real coverage. Left unpinned, the assertion must hold under every
    topology the randomizer produces, which is what the four measured arms in the description show.
    Narrowing the tests' topology is the same objection that ruled out the SET enable_parallel_replicas = 0 approach I originally proposed on Web UI: make the image-preview gesture discoverable in the link tooltip #111918.

Accepted in part: the observation that one green run is not evidence of the fix is worth stating, so
the description now records that the settings are deliberately left randomized and that the
deterministic evidence is the forced-remote arm.

⚠️ Agreed and fixed

  • 04258-not-single-granule - the description said "each test table is a single granule". True
    for 04257 (2000 rows) but not for 04258, which inserts 50000 rows at index_granularity = 8192
    (:29, :60), i.e. at least seven granules. The claim was scenery - the initial_query_id
    correlation does not depend on granule count - but it was wrong. The single-granule explanation is
    now scoped to 04257, and 04258's multi-granule layout is given as the reason its exposure is
    latent rather than observed.
  • Breadth understated (my own finding, major). My first correction of the breadth on Web UI: make the image-preview gesture discoverable in the link tooltip #111918 was
    itself too narrow because it only looked back 30 days. Over 60 days this signature appears on three
    unrelated PRs, not two: Keep the stack when an async signal arrives during an MSan report #112008 (columns 8 and 9), Web UI: make the image-preview gesture discoverable in the link tooltip #111918 (column 6) and PR: use serialized query plan - part 2 #97261 (column 6,
    2026-06-11), all on lanes whose name contains ParallelReplicas. Corrected in the description,
    with the lane-config mechanism cited so the claim is checkable.
  • Residual classes mis-enumerated. "The two remaining rows are the plain Code: 241 form" missed
    a Code: 36 settings error on 04257 and, for 04258, a cluster of self-caused failures on the
    branch that introduced the test. Now enumerated per file.
  • Sibling count wrong. "The other 13 text-index ProfileEvents tests" - the real figures are 20
    such tests, 17 already tagged no-parallel-replicas. Corrected in both the description and the
    validation-gate comment.
  • Divergence from the cited precedents undocumented. Both SQL precedents referenced in the
    description put enable_parallel_replicas = 0 /
    parallel_replicas_for_non_replicated_merge_tree = 0 on the assertion query itself; these
    assertions do not. I verified that is not a correctness gap - currentDatabase() is constant-folded
    on the initiator before distribution (currentDatabase.cpp:22,49-52) and a query's own secondary
    rows are logged after it finishes reading - and said so explicitly, since a reviewer comparing
    against those precedents would otherwise have to work it out.

💡 Noted, not blocking

The comment added to both test files says the secondary rows' current_database "is default". That
is config-dependent: it holds because the parallel-replica cluster entries declare no
default_database (Cluster.cpp:122), so the secondary session keeps the server default. It is
accurate for every lane that runs these tests today. The description uses the unconditional wording
("is not the test database"); the in-file comment is left as committed.

Session id: cron:clickhouse-review-slot-10:20260728-095900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a 3-replica loopback cluster with parallel_replicas_local_plan = 0 (randomized 0/1 by tests/clickhouse-test:1548), every mark is served remotely and 04257's assertion row is 0 0 0 0 0 0 0 0 0 on every run, 04258's is 0 1 0. Not a rate-based repro.
b Root cause explained? Yes. Six of the nine counters are incremented in PostingListCursor::~PostingListCursor (MergeTreeIndexTextPostingListCursor.cpp:111-125), the rest at :166/:1116/:1134, i.e. on the replica that reads the granule. Remote ProfileEvents are never merged into the initiator's query_log row (RemoteQueryExecutor.cpp:808-812 feeds a queue drained only for the client, ProfileEventsExt.cpp:192-194, while the column comes from the thread-group snapshot, ProcessList.cpp:891-892). The counters therefore appear on secondary rows whose current_database is default, which the assertions' current_database = currentDatabase() predicate excludes.
c Fix matches root cause? Yes. The wrong thing is the row selection, and only the row selection changed: the assertions resolve the initiator query ids and aggregate over every row of those queries via initial_query_id. No bound widened, no setting pinned, no tag added, no defensive guard, no engine change.
d Test intent preserved / new tests added? Yes. All twelve assertion expressions, their aliases and the expected output are byte-identical to master (verified by hashing the extracted expression lines), so the "every event must fire" contract is unchanged and is now evaluated over the real execution topology. The change makes two existing tests deterministic, so no new test applies.
e Both directions demonstrated? Yes. Before: 0 0 0 0 0 0 0 0 0 / 0 1 0. After: 1 1 1 1 1 1 1 1 1 / 1 1 1. Also with local_plan = 1 and with parallel replicas off, so the common case is proven unaffected. Reverting only the outer WHERE on the fixed files reproduces the failure exactly, pinning the predicate as the load-bearing change.
f Fix is general across code paths? Yes. All 270 stateless tests containing both ProfileEvents[ and system.query_log were swept. Of the 20 text-index ones, 17 already carry no-parallel-replicas; the two exposed carriers, 04257 (observed) and 04258 (latent, same counters at :122-124, same predicate, no guard), are both fixed here. The one other untagged test, 02346_text_index_parallel_replicas.sql, deliberately asserts parallel-replica behaviour and already handles the secondary rows its own way, matching them on the query text at :37, so it is untouched.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type wrappers: a system.query_log predicate performs no type dispatch. The applicable axis is the execution topology, and all three regimes are covered (forced-remote, local plan, parallel replicas off).
h Backward compatible? (maintainer-approved exception only) Yes, trivially. Test-only change: no setting default, no SettingsChangesHistory.cpp entry, no serialization or format change, no experimental gate.
i Invariants and contracts preserved? Yes. No source contract is touched. The assertion's own invariant ("each event fires at least once across these queries") is widened in coverage, never relaxed. The initial_query_id predicate is exactly scoped to this test's queries, so a concurrently running copy cannot cross-contaminate the aggregation, which dropping current_database on its own would have allowed.

Session id: cron:clickhouse-impl-slot-46:20260728-092200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Ergus — could you review this? It fixes the flaky TextIndexLazy* ProfileEvents assertions in 04257/04258: the counters are incremented on whichever replica reads the granule, and remote ProfileEvents are never merged into the initiator's system.query_log row, so under parallel replicas they land on secondary rows that the tests' current_database = currentDatabase() predicate excluded. The assertions now resolve the initiator query ids and aggregate over every row of those queries via initial_query_id; no assertion or expected output changes.

@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 [741173a]

Summary: ✅


AI Review

Summary

This PR rewrites the system.query_log assertions in 04257_text_index_lazy_profile_events.sql and 04258_text_index_lazy_intersect_heap.sql to aggregate by initial_query_id, so the TextIndexLazy* counters are still observed when the relevant work runs in secondary parallel-replica sessions. I did not find a correctness or coverage regression in the new predicate: the pattern matches existing parallel-replica tests in this tree, initial_query_id is populated for initial queries and propagated to secondaries, and the PR includes focused verification plus all-green CI, including the ParallelReplicas stateless lanes.

Final Verdict
  • Status: ✅ Approve

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 741173a

CI has fully finished on this head: 174 check-runs, 0 queued, 0 in progress, Config Workflow
success at 12:29:43Z and Finish Workflow success at 17:12:57Z. 47 success, 127 skipped, 0
failures
, so there is nothing to own.

Check / test Reason Owner / fixing PR
(none) CI is green on this head not applicable

The two changed tests were exercised rather than skipped, which is the part worth stating for a
test-only diff. 04257_text_index_lazy_profile_events and 04258_text_index_lazy_intersect_heap
each ran 50 out of 50 times with 0 failures in every one of the four flaky checks
(amd_asan_ubsan, amd_debug, amd_msan, amd_tsan), plus single runs on amd_debug parallel,
amd_tsan parallel, amd_tsan s3 storage 3/3, amd_asan_ubsan distributed plan,
amd_debug distributed plan s3 storage, arm_binary parallel, arm_asan_ubsan azure parallel,
amd_msan WasmEdge 2/2 and both Fast test flavors. All ten Stress test flavors are also green.

The 127 skips are structural for a diff that touches only two .sql files, and the reasons the
report gives are explicit: every Build (*) and every job depending on a build reports "Skipped:
no build-affecting changes; coverage would be identical to master", the untouched stateless
flavors report "Only test files changed in this PR and none of the changed tests apply to this
job's parallel/sequential flavor", and the Bugfix validation jobs report "Skipped, not a bug-fix
PR". No job was dropped, and no check was cancelled.

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

@PedroTadim PedroTadim self-assigned this Jul 30, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Jul 30, 2026
Merged via the queue into ClickHouse:master with commit 5a3efd7 Jul 30, 2026
178 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 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