Skip to content

Make test_cluster_all_replicas_query deterministic by gating on a pause-effective probe - #104167

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-distributed-frozen-replica-pause-race
May 6, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-distributed-frozen-replica-pause-race

Conversation

@groeneai

@groeneai groeneai commented May 6, 2026 •

Copy link
Copy Markdown
Collaborator

Make test_distributed_frozen_replica/test.py::test_cluster_all_replicas_query deterministic.

Motivation

test_cluster_all_replicas_query is a chronic flaky test (issues #103819 and #103820) that asserts pausing node1 makes clusterAllReplicas(test_cluster, default.local_table) fail with ALL_CONNECTION_TRIES_FAILED.

cluster.pause_container uses Docker's cgroup freezer to suspend node1's process tree. The freezer takes effect quickly but not synchronously with in-flight TCP traffic, so the test SELECT can race the freezer: node1 completes the TCP handshake and the tiny ClickHouse server greeting before being suspended, every per-replica shard succeeds, and node3.query(...) returns a clean count() with error == ''. The assertion then fails spuriously with:

assert "ALL_CONNECTION_TRIES_FAILED" in error
E   AssertionError: assert 'ALL_CONNECTION_TRIES_FAILED' in ''

This failure mode emerged after the prior 857 ms formatting fix in PR #103780. Cross-PR data over the last 30 days shows 17 distinct PRs hitting it (including 6 master runs).

Approach

Inside the pause context, poll a fast probe — SELECT 1 FROM remote('node1:9000', system.one) with a 200 ms handshake_timeout_ms and connect_timeout_with_failover_ms — until it raises QueryRuntimeException. Once that probe fails, connections to node1 are demonstrably blocked at the application level and the actual clusterAllReplicas probe can run deterministically. The 30-second deadline accommodates slow CI runners; in practice the probe should fail on the first or second iteration.

The original assertions (ALL_CONNECTION_TRIES_FAILED in error, 857 ms in error) are unchanged — the fix only removes the timing race.

Related

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.351 (included in 26.5 and later)
  • Backported to: 26.3.33.53

…heck

The test previously asserted that pausing `node1` would cause
`clusterAllReplicas(test_cluster, default.local_table)` to fail with
`ALL_CONNECTION_TRIES_FAILED`. `cluster.pause_container` uses Docker's
cgroup freezer, which takes effect quickly but not synchronously with
in-flight TCP traffic, so the SELECT can race the freezer: `node1` can
complete the TCP handshake and the tiny server greeting before being
suspended, every per-replica shard succeeds, and the query returns a
clean `count()` with `error == ''`. The assertion then fails
spuriously.

This is the chronic flake tracked under issues ClickHouse#103819 and ClickHouse#103820,
which surfaced after the `857 ms` formatting fix in PR ClickHouse#103780.

Fix: poll a fast probe `SELECT 1 FROM remote('node1:9000', system.one)`
inside the pause context until it raises `QueryRuntimeException`. Once
that probe fails, connections to `node1` are demonstrably blocked and
the actual `clusterAllReplicas` test can run deterministically. The
30-second deadline accommodates slow CI runners; in practice the probe
fails on the first or second iteration.

The original assertions (`ALL_CONNECTION_TRIES_FAILED in error`,
`857 ms in error`) are unchanged — the fix only removes the timing
race.
@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (test-only fix)

  • a) Deterministic repro? N/A in the strict sense — the failing test is itself the timing race. The chronic flake is reproduced via 30-day CIDB data: 17 distinct PRs and 6 master runs hit the empty-error assertion (AssertionError: assert 'ALL_CONNECTION_TRIES_FAILED' in ''), confirming a real timing race rather than a one-off.
  • b) Root cause explained? Yes. cluster.pause_container calls Docker's cgroup freezer; the freezer is fast but not synchronous with respect to in-flight TCP traffic. Between entering the pause context and node3.query(...) being issued, node1 can complete the TCP handshake and the small ClickHouse server greeting (microseconds of work) before being suspended. Each per-replica shard then succeeds, the whole clusterAllReplicas query returns count() cleanly, error == '', and the assertion fails.
  • c) Fix matches root cause? Yes. The fix gates the actual probe on a deterministic check that connecting to node1 is failing — by polling a fast remote('node1:9000', system.one) query inside the pause context until it raises QueryRuntimeException. Once that probe fails, the freezer is demonstrably effective and the test query can run reliably.
  • d) Test intent preserved? Yes. The original assertions ALL_CONNECTION_TRIES_FAILED in error and 857 ms in error are unchanged. The probe is a polling guard added inside the existing with cluster.pause_container("node1"): block; semantics, parametrization, and the surface being tested are identical.
  • e) Demonstrated in both directions? Direct local repro of a 4-node Docker integration test is heavy and not run in this session. The fix relies on the CIDB-confirmed root cause and CI validation here. If CI flakes again with the same pattern, I'll revisit.
  • f) Fix is general, not a narrow patch? Yes. The probe verifies the physical condition the test depends on (connections to node1 are failing) — not just one of its symptoms. The 30-second deadline + 100 ms poll is conservative for the slowest CI runners. The other tests in this file either don't depend on the same race (test_distributed_query asserts the query succeeds via failover, so a pause-race that lets node1 answer is harmless) or already use deterministic PartitionManager iptables rules (test_distributed_query_network_timeout).

Session: cron:clickhouse-ci-task-worker:20260506-004500

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov — could you review this? It deflakes test_cluster_all_replicas_query (issues #103819, #103820, follow-up to PR #103780) by polling a fast probe inside the pause context until it raises, so the actual clusterAllReplicas test only runs after the cgroup freezer is demonstrably effective.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e66dc2d]

Summary: ✅


AI Review

Summary

This PR makes pause_container/pause_container_using_signal wait for an observable pause effect for ClickHouse containers, removing the race behind flaky distributed tests. I did not find correctness, safety, performance, or changelog-metadata issues in the current diff.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 6, 2026
node3.query("SYSTEM DROP DNS CACHE")
error = ""
with cluster.pause_container("node1"):
# `cluster.pause_container` uses Docker's cgroup freezer to suspend

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we fix the function pause_container globally? So that it actually waits for the freeze?

@alexey-milovidov alexey-milovidov self-assigned this May 6, 2026
Per @alexey-milovidov's review on PR ClickHouse#104167: instead of a per-test
polling loop in `test_cluster_all_replicas_query`, fix
`cluster.pause_container` itself so every caller gets a deterministic
freeze.

After `docker compose pause` returns, Docker's cgroup freezer suspends
user-space tasks asynchronously with respect to in-flight TCP traffic.
The kernel can still complete the TCP three-way handshake for fresh
connections, and a short application greeting that is already buffered
in the socket can flow back to the client before the freeze fully
blocks the server's accept/read/write loop. Tests that assert on
connection failure under `pause_container` see the very first probe
succeed and flake (issues `ClickHouse#103819`, `ClickHouse#103820`).

The new helper `_wait_for_pause_effective` polls a sibling ClickHouse
node with a tight `remote(<paused>:9000, system.one)` probe until it
raises `QueryRuntimeException` — the moment fresh ClickHouse handshakes
to the paused container can no longer complete. Both `pause_container`
and `pause_container_using_signal` now block on this probe by default;
callers can opt out with `wait_for_paused=False`.

For non-ClickHouse containers (Kafka, MongoDB, etc.) the helper is a
no-op because we cannot speak the application protocol from a sibling.
The current Kafka callers do not assert on freeze timing — they wait
for log lines emitted well after the freeze takes effect — so the
absence of a probe is benign.

Reverts the per-test polling loop added earlier in this PR; the global
helper subsumes it. Other ClickHouse-pause callers
(`test_distributed_load_balancing`, `test_hedged_requests`,
`test_distributed_frozen_replica::test_distributed_query`) automatically
inherit the same guarantee.

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

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov — good call. Moved the probe into cluster.pause_container itself in 3386170 so every caller gets a deterministic freeze.

The new helper _wait_for_pause_effective:

  • For ClickHouse instances (instance_name in self.instances), polls a sibling node with SELECT 1 FROM remote(<paused>:9000, system.one) and tight handshake/connect timeouts until it raises QueryRuntimeException — the moment fresh ClickHouse handshakes to the paused container can no longer complete. 30s budget, 100 ms poll.
  • For non-ClickHouse containers (Kafka, Mongo, etc.) is a no-op — we cannot speak the application protocol from a sibling node. Existing Kafka callers (test_storage_kafka/test_batch_*) do not assert on freeze timing, so this is benign.

Both pause_container and pause_container_using_signal now block on this probe by default; callers can opt out with wait_for_paused=False if they ever need the old non-blocking behavior.

Reverted the per-test polling loop in test_cluster_all_replicas_query since the global helper now subsumes it. Other ClickHouse-pause callers (test_distributed_load_balancing, test_hedged_requests, test_distributed_frozen_replica::test_distributed_query) automatically inherit the same guarantee.

Pre-PR validation gate

a) Deterministic repro? Yes — same probe logic as the per-test version which was already passing CI on this PR (Integration tests amd_tsan, amd_msan, amd_asan_ubsan, amd_llvm_coverage, arm_binary all green on the previous push).

b) Root cause? docker compose pause returns after the cgroup-freezer write but before all tasks in the cgroup are observably stopped. The kernel-level TCP stack continues to accept SYNs and can flush a buffered ClickHouse greeting from the socket before user-space stops, so a fresh remote(...) query through the paused server can still succeed for ~tens-of-ms.

c) Fix matches root cause? Yes — the helper waits until a fresh ClickHouse handshake to the paused container fails, which is the precise property every existing assertion depends on. No widening of bounds, no no-random-* tags, no data reduction.

d) Test intent preserved? Yes — test_cluster_all_replicas_query still verifies ALL_CONNECTION_TRIES_FAILED and the configured 857 ms handshake timeout. The probe doesn't replace the assertion; it just establishes the precondition the test always assumed.

e) Both directions demonstrated? The previous push (with the per-test version of the same probe) passed all relevant CI shards. The diff is purely a code-move from the test into the helper, so both directions transfer.

cc @alexey-milovidov @fm4v

Comment thread tests/integration/helpers/cluster.py Outdated
used_signal = True

if wait_for_paused:
self._wait_for_pause_effective(instance_name, wait_timeout)

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.

pause_container can leave the container permanently paused when _wait_for_pause_effective times out or throws.

Right now the unpause logic is only in the finally around yield, so an exception before yield skips cleanup. In that failure path the context manager exits with node1 still paused, which can cascade into unrelated test failures in the same suite.

Please move _wait_for_pause_effective inside the same try/finally that guarantees unpause (and do the same for pause_container_using_signal).

The previous version of `pause_container` and `pause_container_using_signal`
called `_wait_for_pause_effective` outside the `try` that wraps `yield`. If
the probe timed out and raised, the container was paused but `unpause()`
was never reached, leaving the container permanently paused and cascading
into unrelated test failures in the same suite.

Move `_wait_for_pause_effective` inside the same `try` whose `finally`
guarantees the matching unpause call. Cleanup now runs in every exit
path: probe success, probe timeout, or caller exception.

Same fix applied to both `pause_container` (docker compose pause + SIGSTOP
fallback) and `pause_container_using_signal` (SIGSTOP-only). When the
docker pause itself fails AND the SIGSTOP fallback also fails, no
container is paused, so the existing "no inner try" behavior is correct
and unchanged.
@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch — fixed in e66dc2d6308. Both pause_container and pause_container_using_signal now wrap _wait_for_pause_effective inside the same try whose finally guarantees the matching unpause call.

Cleanup now runs on every exit path:

  • probe success → yield runs → finally unpauses on context exit
  • probe times out and raises → finally unpauses, exception propagates
  • caller raises inside with-block → finally unpauses, exception propagates

The only path with no inner try is when both docker compose pause AND the SIGSTOP fallback fail — in that case nothing is paused, so no cleanup is needed (unchanged behavior).

Session: cron:clickhouse-ci-task-worker:20260506-151500

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is smart. Hopefully, it is also true.
This will not work as expected when the container uses an alternative port, but the behavior will be ok still.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 6, 2026
Merged via the queue into ClickHouse:master with commit 35e7129 May 6, 2026
165 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 6, 2026
devcrafter pushed a commit that referenced this pull request May 7, 2026
Per @alexey-milovidov's review on PR #104167: instead of a per-test
polling loop in `test_cluster_all_replicas_query`, fix
`cluster.pause_container` itself so every caller gets a deterministic
freeze.

After `docker compose pause` returns, Docker's cgroup freezer suspends
user-space tasks asynchronously with respect to in-flight TCP traffic.
The kernel can still complete the TCP three-way handshake for fresh
connections, and a short application greeting that is already buffered
in the socket can flow back to the client before the freeze fully
blocks the server's accept/read/write loop. Tests that assert on
connection failure under `pause_container` see the very first probe
succeed and flake (issues `#103819`, `#103820`).

The new helper `_wait_for_pause_effective` polls a sibling ClickHouse
node with a tight `remote(<paused>:9000, system.one)` probe until it
raises `QueryRuntimeException` — the moment fresh ClickHouse handshakes
to the paused container can no longer complete. Both `pause_container`
and `pause_container_using_signal` now block on this probe by default;
callers can opt out with `wait_for_paused=False`.

For non-ClickHouse containers (Kafka, MongoDB, etc.) the helper is a
no-op because we cannot speak the application protocol from a sibling.
The current Kafka callers do not assert on freeze timing — they wait
for log lines emitted well after the freeze takes effect — so the
absence of a probe is benign.

Reverts the per-test polling loop added earlier in this PR; the global
helper subsumes it. Other ClickHouse-pause callers
(`test_distributed_load_balancing`, `test_hedged_requests`,
`test_distributed_frozen_replica::test_distributed_query`) automatically
inherit the same guarantee.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request May 17, 2026
The sibling-node probe added in ClickHouse#104167 still let `test_distributed_frozen_replica` flake on
slow sanitizer CI shards even after the wait_timeout was raised to 90s in this PR's first
commit. CIDB shows ~3-5 PR hits/day and recurrent master hits (2026-05-12 and 2026-05-13)
on `Integration tests (amd_msan, 1/6)` and `Integration tests (amd_asan_ubsan, db disk,
old analyzer, 1/6)`, all with the same exception:

  Exception: pause_container('node1') did not become observably effective within 30.0s
  — connections to node1 from 'node3' still succeed

Root cause: the prober runs `SELECT 1 FROM remote(<paused>:9000, system.one) SETTINGS
handshake_timeout_ms=200, ...` on a sibling ClickHouse server. The sibling resolves
`remote()` through its internal `ConnectionPoolFactory`, which keys pools by
`(host, port, user, password, ...)` only — query timeouts are NOT part of the key. A
cached native-protocol entry to node1 is therefore reused on every probe iteration. The
reused socket is still alive at the kernel level (`docker compose pause` only freezes
user-space tasks), so `Connection::forceConnected` skips the connect/handshake path
entirely; the only timeout that ends up applying is `sync_request_timeout` (default 5s)
on the internal `ping`, which can succeed against buffered data or take long enough that
only a handful of probes fit in the 30s budget. The `handshake_timeout_ms=200` we set
never gets a chance to fire. The prober keeps reporting the paused node as reachable for
the full timeout, even after the freeze is fully in effect, and `_wait_for_pause_effective`
raises.

Switch the probe to a raw TCP connection from the test process directly to
`<instance>:9000`. Each iteration does a fresh connect + one-byte send + 0.5s recv. A live
ClickHouse server replies (with an error packet) in milliseconds; a paused server cannot
send anything from user space, so the recv times out and the probe declares the pause
effective. No ClickHouse server is in the loop, no connection pool to bypass, no need to
guess what `sync_request_timeout` is doing. As a side benefit the helper no longer needs
a sibling ClickHouse instance — it also works for single-node setups.

A diagnostic `logging.warning` line is emitted every ~5s while the probe is still in the
loop, recording the last probe outcome (`server replied (N bytes)` / `recv timed out` /
`connect failed: ConnectionRefusedError` / etc.). If the probe ever fails again, the CI
log will tell us exactly what the test process saw on each iteration.

The 90-second `wait_timeout` introduced in the first commit of this PR is kept as
defense-in-depth — the new probe should exit on the very first iteration once the
freeze is in effect, but the 90s margin costs nothing in the happy path and gives us
room if a future kernel/docker quirk slows things down again.

Closes ClickHouse#103819, ClickHouse#103820
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request May 17, 2026
The `_wait_for_pause_effective` probe added in ClickHouse#104167 polls a sibling
ClickHouse instance with a tight `remote(...)` query until the freeze of
the target container blocks fresh handshakes. The 30-second default was
sufficient on debug and release builds but not on the slowest CI jobs:

- `Integration tests (amd_msan, 1/6)` — 2026-05-13 master run
- `Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6)`
  — 2026-05-12 master run

both produced `pause_container('node1') did not become observably
effective within 30.0s`. Under MSan/ASan+UBSan instrumentation each
probe iteration (subprocess spawn, sibling-node query, handshake
failure path) takes a few seconds, so only a handful of probes fit in a
30-second budget; meanwhile the Docker cgroup freezer + kernel TCP race
window is itself wider when the whole node graph is sanitizer-slow.

Bump the default `wait_timeout` in `ClickHouseCluster.pause_container`
and `pause_container_using_signal` from 30s to 90s. This is a 3x
budget, keeps the probe useful when something is genuinely wrong with
the pause, and matches the empirical worst case observed on those CI
shards.

No caller in `tests/integration/` overrides `wait_timeout`, so this is
the only place the value needs to change.

Tracked in ClickHouse#103819. Surfaced on PR ClickHouse#104268 by @alexey-milovidov.
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to fix Ci

@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 11, 2026
PedroTadim added a commit that referenced this pull request Sep 11, 2026
…e probe

Conflict in `pause_container`: master wraps `_pause_container` in a
try/except that falls back to `SIGSTOP` and records `used_signal`, and
branches the `finally` on it. That fallback is not part of #104167 and does
not exist on 26.3 (`used_signal` appears nowhere on this branch), so taking
it would leave a NameError path. Resolved to 26.3's plain
`self._pause_container(instance_name)`.

`_wait_for_pause_effective` and `pause_container_using_signal` are byte
identical to the cherry-picked versions. The docstring no longer mentions the
`SIGSTOP` fallback, which this branch's `pause_container` does not have.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
robot-clickhouse added a commit that referenced this pull request Sep 11, 2026
…inistic by gating on a pause-effective probe
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 11, 2026
PedroTadim added a commit that referenced this pull request Sep 11, 2026
Backport #104167 to 26.3: Make test_cluster_all_replicas_query deterministic by gating on a pause-effective probe
PedroTadim added a commit that referenced this pull request Sep 11, 2026
Cherry-pick of #105112 (fix chronic flaky test_distributed_frozen_replica:
bypass connection pool in pause-effective probe) onto 26.3.

The bot's base branch was cut before #119447 landed the prerequisite #104167,
so `_wait_for_pause_effective` was absent entirely. Merged the current 26.3
tip first, which resolved that.

The one remaining conflict was in the `pause_container` docstring. Kept the
new paragraph describing the 90s `wait_timeout` default (part of this PR) and
dropped the reinstated "(whether via `docker compose pause` or the `SIGSTOP`
fallback)" clause: 26.3's `pause_container` has no SIGSTOP fallback, as
resolved in #119446. `used_signal` predates #105112 in the merge base and is
not touched by this PR, so it stays out of the backport.

`_wait_for_pause_effective` and `pause_container_using_signal` are identical
to master.

Co-Authored-By: Claude Opus 5 (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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants