Skip to content

Fix two distributed_index_analysis tests on an unavailable replica - #112879

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03622-dia-unavailable-replica
Aug 1, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03622-dia-unavailable-replica

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 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

03622_distributed_index_analysis_applies_skip_indexes and
03622_distributed_index_analysis_additional_table_filters both fail whenever 127.0.0.2:9000,
the second replica of test_cluster_one_shard_two_replicas, is unreachable.

The server warns that the replica dropped out at LogsLevel::warning, the stateless runner ships
--send_logs_level=warning for every .sql test, and any non-empty stderr fails the test.
Separately, DistributedIndexAnalyzer::run fills the result address only for replicas that
connected, so the dead replica's entry keeps an empty address with zero counters while the local
replica absorbs its parts. Both tests pin the healthy two-replica split, so they also fail on
stdout.

The empty-address entry is correct behaviour and is already a pinned expectation elsewhere in this
family, so this change is test-only.

Each test now sets send_logs_level='error' (as most tests in the family already do) and
asserts the plan through
select * from (explain indexes=1 ...) where explain not like '%Address:%' and ..., which drops
only the per-replica rows, leaving the aggregate Parts:/Granules: on the PrimaryKey entry.
Because the plan no longer names the replica that answered, each test also asserts from
system.query_log that
DistributedIndexAnalysisReplicaFallback and DistributedIndexAnalysisMissingParts are zero. Both
are incremented only after a replica connects, so they are unaffected by its availability and still
fail if the remote analysis silently falls back to the initiator.

Validated by binding a server to 127.0.0.1 only so the second replica genuinely refuses: both
tests fail before the change and pass after it, in that arm and with both replicas up. Mutations
redden them, including forcing distributed index analysis off and forcing the remote analysis to
throw while the replica is up, so no assertion became a tautology. 50 randomized runs per test per
arm pass, and a 22-test sweep over the family shows no regressions.

Four more tests carry half of the same latent exposure; they are tracked separately.

Related: #111492

03622_distributed_index_analysis_applies_skip_indexes and
03622_distributed_index_analysis_additional_table_filters both fail whenever
127.0.0.2:9000, the second replica of test_cluster_one_shard_two_replicas, is
unreachable. One cause produces two divergences.

First, DistributedIndexAnalyzer::establishConnectionsSync logs the connect
failure at LogsLevel::warning (distributedIndexAnalysis.cpp:456). The stateless
runner passes --send_logs_level=warning for every .sql test
(tests/clickhouse-test:3603, default at :6646), so the record reaches the
client's stderr, and any non-empty stderr fails the test (:1300). The observed
runner verdict is "having stderror:", not a timeout.

Second, DistributedIndexAnalyzer::run pre-sizes its result vector to the full
remote-replica count and fills the address only for replicas that connected
(distributedIndexAnalysis.cpp:307-309), so the dead replica's entry keeps a
default-constructed address with zero counters. selectRangesToRead emits it
unconditionally (ReadFromMergeTree.cpp:2958-2977) and describeIndexes prints it
(:4845-4855), while the local replica absorbs the remaining parts. Both tests
pin the healthy two-replica split in their .reference, so they also diverge on
stdout. This means suppressing the warning alone is not sufficient: it only
moves the failure to a result diff.

The empty-address entry is correct behaviour and is already the pinned
expectation of 03622_explain_indexes_distributed_index_analysis.reference for
the unreachable replica of the parallel_replicas cluster, so this change is
test-only and touches no source file.

Each test now sets send_logs_level='error', matching 17 of the 22 stateless
tests that enable distributed_index_analysis, and asserts the plan through
select * from (explain indexes=1 ...) where explain not like '%Address:%' and
..., which drops only the per-replica rows. The aggregate Parts:/Granules: on
the PrimaryKey entry survive; those are populated from received_parts and
received_granules (ReadFromMergeTree.cpp:2979-2993), so the tests still prove
the skip index was applied on the replicas. Forcing distributed index analysis
off makes them read 100/100 and the tests fail, so the assertion did not become
a tautology.

Three further tests in the family lack the same guard but pin no per-replica
rows, so they are latent rather than failing and are left to a separate change.
The previous commit made these two tests tolerate an unavailable
127.0.0.2 by filtering the per-replica rows out of the `EXPLAIN`
output. That filter also removed the only observable that
distinguished "the remote replica analyzed its own parts" from "the
remote replica silently fell back to the initiator": on that fallback
path `DistributedIndexAnalyzer` catches the failure, increments
`DistributedIndexAnalysisReplicaFallback` and logs only at
`LogsLevel::warning`, which the tests now suppress; `resolveMissingParts`
then re-analyzes those parts locally, so the aggregate `Parts:` and
`Granules:` counters are unchanged and the test would have passed.

Add a `system.query_log` assertion on three profile events that are
independent of replica availability, so it reads identically whether
or not 127.0.0.2 is up:

  DistributedIndexAnalysisMicroseconds > 0
  DistributedIndexAnalysisReplicaFallback = 0
  DistributedIndexAnalysisMissingParts    = 0

`DistributedIndexAnalysisReplicaFallback` and
`DistributedIndexAnalysisMissingParts` are incremented only once a
replica has connected and its analysis then failed, which is exactly
the case that must not pass silently.
`DistributedIndexAnalysisScheduledReplicas` and
`DistributedIndexAnalysisReplicaUnavailable` are deliberately not
asserted: both vary with replica availability and would reintroduce the
flakiness these tests exist to avoid.

Verified by forcing the remote analysis to fail while both replicas are
up: both tests go red on the new assertion alone, on the synchronous
and the asynchronous reader path, while the filtered plan output stays
identical.

Also wrap the literal log message excerpt and the literal setting name
in the new comments in inline code blocks.
@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 6 findings, 4 agreed and fixed, 0 disagreed)

Before opening this PR I ran two independent review rounds against the diff: a cold code review
plus a separate reviewing model, adjudicated each finding against the source, and had the author
side implement the agreed ones. Round 2 came back with zero findings.

# Severity Finding Verdict Resolution
1 ❌ blocker Filtering every per-replica row out of the plan removed the only observable that distinguishes "the remote replica analyzed its parts" from "the remote replica silently fell back to the initiator". The fallback path only logs at LogsLevel::warning, which this PR's own send_logs_level='error' suppresses, and the aggregate Parts: 20/100 is unchanged because the initiator re-analyzes the missing parts locally. AGREE Both tests now assert from system.query_log that DistributedIndexAnalysisReplicaFallback and DistributedIndexAnalysisMissingParts are zero. A mutation that forces the remote analysis to throw while both replicas are up reddens that assertion alone, with the filtered plan output byte-identical, so the case that used to pass silently now fails.
2 ⚠️ major 03622_explain_indexes_distributed_index_analysis_in.sh has the same stdout exposure on the same cluster: it pins four "Address": "127.0.0.2:9000" rows and no empty-address row. The original class-coverage claim ("the only two reference files pinning per-replica rows for a two-replica cluster") was therefore wrong. AGREE Tracked separately rather than folded in. Its remedy differs (a jq-side projection with a per-statement non-vacuity argument over four statements), and its stderr half is already guarded, so it is latent rather than failing.
3 ⚠️ major The residue paragraph surveyed only the send_logs_level axis, implying the remainder was guard-only while a fourth test stayed exposed on the stdout axis. AGREE Rewritten to cover both axes.
4 💡 nit Two new comments quoted a log excerpt with plain double quotes and one carried a bare setting name, against the repository convention of putting literal log excerpts and SQL names in inline code blocks. AGREE Backticked in both test files and in their echoed reference copies.
5 💡 nit Availability-independence of the two asserted profile events; soundness of the system self-exclusion and query_kind predicates; behaviour under the stress profile's server-side AST fuzzer; the four query_log suppression settings; behaviour under a fixed --database; echo/reference byte-consistency. verified, no action Each confirmed from source. The two availability-dependent events (DistributedIndexAnalysisScheduledReplicas, DistributedIndexAnalysisReplicaUnavailable) are deliberately not asserted, since pinning either would reintroduce the flakiness this PR removes.

Validation is summarised in the description. Beyond that: five mutations, each reddening the
tests for the expected reason and each source restore verified byte-identical; 200 randomized runs
across two arms with zero failures; and a 22-test sweep over the family in which both arms ran the
same 22 tests, with the only differences being the two tests this PR fixes.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Server bound to 127.0.0.1 only, clusters.xml port-rewritten to the test port, so 127.0.0.2 genuinely refuses. clickhouse-test --client-option use_hedged_requests=0 --no-random-settings --no-random-merge-tree-settings <test> gives [ FAIL ] Reason: having stderror: on every run for both tests, with frame 6 at distributedIndexAnalysis.cpp:449. Not a rate-based flake.
b Root cause explained? Yes. One cause, two divergences. The connect failure is logged at LogsLevel::warning (distributedIndexAnalysis.cpp:456) and the runner ships --send_logs_level=warning for every .sql test (clickhouse-test:3603, default at :6646), so non-empty stderr fails the test (:1300). Separately DistributedIndexAnalyzer::run pre-sizes its result to the full remote-replica count and fills the address only for replicas that connected (:307-309), so the dead replica's entry is emitted with an empty address and zero counters (ReadFromMergeTree.cpp:2958-2977, printed at :4845-4855) while both .reference files pin the healthy two-replica split.
c Fix matches root cause? Yes, and it is not a band-aid. No timeout bump, no no-parallel, no blanket no-random-*, no widened bound, no src/ change guarding correct output. The assertion is narrowed to exactly the rows a dead replica reshapes and nothing else. send_logs_level='error' matches 17 of the 22 stateless tests that enable distributed_index_analysis.
d Test intent preserved / new tests added? Preserved, and proven so on two independent axes. The surviving Parts:/Granules: on the PrimaryKey entry come from the ranges the replicas returned (ReadFromMergeTree.cpp:2979-2993), so forcing distributed index analysis off makes them read 100/100 and the test fails. Because that aggregate is invariant to which replica answered, each test additionally asserts three system.query_log profile events that are independent of replica availability, so a remote replica that connects and then fails its analysis can no longer pass silently. No new test file is owed: the deliverable is the fix to two existing tests, and no src/ line changes.
e Both directions demonstrated? Yes. Dead-replica arm with use_hedged_requests=0: both tests FAIL before, pass after. Dead-replica arm at the default use_hedged_requests=1: fail before on the stdout half, pass after. Healthy two-replica arm: pass before and after. The new profile-event assertion reads byte-identically in the dead-replica and healthy arms, which is what shows the chosen events are availability-independent.
f Fix is general across code paths? Yes. Carriers enumerated by SETTING, not by test name, across all 22 stateless tests that enable distributed_index_analysis. Both tests that pin per-replica rows in plain-text EXPLAIN output for a two-replica cluster are fixed here. All four fallback sites in distributedIndexAnalysis.cpp (:702, :707 synchronous; :780, :785 asynchronous) increment the same event, so one assertion covers both reader paths, and this was verified by forcing a failure on each path in turn. Three remaining tests lack the log-level guard but pin no per-replica rows, and 03622_explain_indexes_distributed_index_analysis_in.sh pins them in JSON form for the same cluster while already suppressing the warning; all four are latent, not failing, and are left to separate changes and noted in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes within scope. Verified at both values of the randomizing setting use_hedged_requests (0 and 1) and at both values of async_socket_for_remote (which selects the synchronous or asynchronous reader path), in both the dead-replica and healthy arms, and under 50 randomized runs per test per arm. Not a type or wrapper change, so no datatype matrix applies.
h Backward compatible? (maintainer-approved exception only) N/A. Test-only: zero src/ lines, no setting defaults changed, no SettingsChangesHistory.cpp entry, no serialization or format change.
i Invariants and contracts preserved? Yes. No production invariant is touched. The tests' own invariant, that distributed index analysis applies the skip index on the replicas, is preserved and shown load-bearing by the mutation that forces it off; the presence of the Distributed: block is still asserted, shown by the mutation that deletes that expectation from the references; and the stronger invariant that the remote replica analyzed its own parts rather than deferring to the initiator is now asserted directly and shown load-bearing by a mutation that fails the remote analysis while the replica is up.

Additional validation: five mutations each redden the tests. Four are test-side (reverting the log-level guard; reverting the subquery filter; forcing distributed index analysis off; deleting the Distributed: header expectation), after which all four files were restored and checksum-verified. The fifth forces the remote analysis to throw while both replicas are up, on the synchronous and the asynchronous reader path in turn; both tests then fail on the new profile-event assertion alone while the filtered plan output stays identical, which is exactly the silent-fallback case the assertion exists to catch. That mutation was applied to distributedIndexAnalysis.cpp only temporarily and reverted, and the file's checksum was verified identical afterwards so the shipped change remains test-only. 50 randomized runs per test in each arm pass with the tags left as long only. A 22-test sweep over the family, with a baseline built from this branch with only these four files reverted, ran the identical selection in both arms and shows no regressions, two improvements (these tests), and nine pre-existing failures identical in both arms that need the eleven-node parallel_replicas cluster the sandbox does not provide.

Session id: cron:clickhouse-review-slot-11:20260801-061400

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat, could you review this? Two stateless tests pinned the per-replica Distributed: rows of test_cluster_one_shard_two_replicas, so an unreachable 127.0.0.2 failed them on both stderr and stdout; they now filter those rows out and instead assert DistributedIndexAnalysisReplicaFallback and DistributedIndexAnalysisMissingParts from system.query_log, which your "only alive replicas participate" change makes independent of replica availability.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@PedroTadim PedroTadim self-assigned this Aug 1, 2026
@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 10:59
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9db69d]

Summary: ✅


AI Review

Summary

This PR makes two distributed_index_analysis stateless tests tolerate an unavailable replica by filtering the per-replica Distributed: rows from EXPLAIN output and adding a system.query_log check that the analyzed query still recorded distributed index analysis work with no post-connect fallback or local missing-part recovery. After reviewing the current diff, the surrounding distributed-index-analysis tests, the clickhouse-test log-comment wiring, and the relevant distributedIndexAnalysis.cpp event semantics, I did not find a correctness or coverage regression in the updated tests.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 1, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit c294650 Aug 1, 2026
179 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 Aug 1, 2026
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Sep 23, 2026
…s tests

On the MSan lane these four tests intermittently die while connecting to a
127.0.0.x:9000 loopback peer:

  Code: 209. DB::NetException: Timeout exceeded while reading from socket
    (peer: 127.0.0.2:9000, local: 127.0.0.1:NNNNN, 10000 ms) ... (SOCKET_TIMEOUT)

10000 ms is the default handshake_timeout_ms. Connection::connect installs it as
the socket receive and send timeout for the Hello exchange only, restoring the
regular timeouts once the handshake completes, so under sanitizer instrumentation
plus 2-way-sharded host load the peer answers Hello late and the query dies before
any data moves (the CI rows show "Wrote 0 blocks and 0 rows" on the slow shard).
The timeouts are an argument of each pool get() call and are not part of the pool
or cluster identity, which is why a query-time value is effective even for the
materialized-view carrier, whose pools were created by an earlier CREATE TABLE.

Pin 60000 per test, following d4fed63, which fixed the sibling
00563_shard_insert_into_remote the same way. The shell test takes it as a client
option on its single client invocation. Unlike a no-msan/no-tsan tag this deletes
no sanitizer coverage, and it still applies in the stress jobs, where no-<build>
tags are ignored by design.

This raises the initiator's patience from 10 s; the receiver's own 30 s
handshake_timeout_milliseconds server setting still bounds the exchange, and is
left alone. It has fired once in 365 days of public CI, on an unrelated test.

Validated by putting a 12 s delay in front of the loopback peer, which makes all
four fail on demand with the signature above and pass with the pin, on the same
peer and binary. A 2000 ms and 3000 ms calibration shows the printed budget
tracking the in-file value, so the value is measured to reach the failing socket
rather than assumed to. 80 deterministic and 200 randomized runs green.

464 stateless files reference remote('127.0.0. or cluster('test_, and exactly one
pinned this setting before this change. The pin goes only where a failure was
observed, so the signal that would catch a real handshake regression stays.

Two neighbours are deliberately excluded:
03622_distributed_index_analysis_applies_skip_indexes, whose single sighting was a
swallowed warning rather than a query failure and whose oracle ClickHouse#112879 has since
made availability-independent, and 01600_benchmark_query, already fixed by
7ec04d1.

Co-Authored-By: Claude Opus 5 <[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 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