Skip to content

Fix flaky test_concurrent_watches losing one watch - #114041

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-test-concurrent-watches
Aug 10, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-flaky-test-concurrent-watches

Conversation

@groeneai

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

test_keeper_back_to_back::test_concurrent_watches fails as assert 999 == 1000 (test.py:832) on
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6):
CI report.
It is a test bug; Keeper honours the ZooKeeper contract.

Root cause. trigger_watch mutated a path before owning its existing_path token, then removed
the token inside a bare except: pass. random.choice + set() + remove() is not atomic across the
10 pool threads, so two threads can pick the same token. A watch is one-shot per (path, session), so
the second mutation notifies nobody, and the deferred remove consumes a token belonging to a
different, still outstanding registration, which is then never mutated and never fires. Observed on
/487: register, two mutations 1 ms apart, one event, a second register, then a stale remove eats its
token.

Fix. Claim the token atomically before mutating, and skip when nothing was claimed, so every
registration is followed by a mutation. dumb_watch_triggered_counter == 1000 and two other
assertions are unchanged; trigger_called >= 1000 is tightened to == 1000, which removing unclaimed
mutations makes exact. That tightening is what makes the fix testable: restoring the old bodies under
it fails assert 1026 == 1000, while under >= they passed. The lock covers only the test's own list,
never a Keeper call.

Validation. A deterministic replay of that schedule against a real Keeper fails 3/3 before and
passes 3/3 after. Pre-fix runs issue 1024-1034 mutations for 1000 tokens, versus exactly 1000 in 11/11
runs after (including 1-thread and 50-thread); a watch is lost only when a stale remove lands on a live
token, hence the low rate. 25/25 repetitions pass under the failing job, the suite passes 9/9, five
mutation arms each redden the assertion, and collisions are unchanged (372 duplicate registrations, up
to 6 per path), so the lock did not serialize the test.

test_keeper_back_to_back::test_concurrent_watches fails as `assert 999 == 1000`.
It is a test bug, not a Keeper defect.

trigger_watch mutated a path before it owned the corresponding existing_path
token, and removed the token afterwards inside a bare `except: pass`. Since
random.choice + set() + remove() is not atomic across the 10 pool threads, two
threads can select the same token when only one is present. A watch is one-shot
per (path, session), so the second mutation notifies nobody, and the deferred
remove then consumes a token belonging to a different, still outstanding
registration. That registration is never mutated again, so its callback never
fires and the aggregate count lands one short.

In the failing run this happened on /487: register, two mutations 1 ms apart,
one event, a second register, then a stale remove ate its token, while the run's
last mutation was ~1.8 s later on another path. The expected count is 1000
rather than the number of distinct paths because kazoo fans a single event out
to every callback registered for that path, which is why the test creates a new
closure per registration.

Claim the token atomically before mutating and skip when nothing was claimed, so
that every registration is followed by a mutation. All four assertions are kept
verbatim, including the exact count: the test now satisfies its own
precondition instead of relying on the race not firing.
tests/integration/test_keeper_watches/test.py is the in-tree precedent for that
discipline. The lock covers only the test's list bookkeeping and never a Keeper
call, so the threads still issue overlapping requests and the multi-watcher
collisions remain (372 duplicate registrations, up to 6 on one path).

Validated with a deterministic replay of the observed schedule against a real
Keeper (pre-fix body fails 3/3, post-fix passes 3/3), by four mutation arms that
each redden the retained assertion, and by 50/50 repetitions under the job that
reported the failure.
The bound was assert trigger_called >= 1000, which is all that could hold while
mutating a path the thread held no token for was ordinary behaviour: pre-fix runs
issue 1024-1034 mutations for 1000 registrations and pass. Claiming a token before
mutating makes the count exact, so a revert of that change now reddens the test
(assert 1026 == 1000) instead of passing silently.

Also fix the comment: a mutation that consumes a registration does notify it. The
registration left unnotified is a later one, orphaned because a stale removal ate
its token.

Verified: restoring the pre-fix bodies under the tightened bound fails 1026 == 1000
with 26 stale removes; the tightened test passes 25/25 under
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6), the suite passes 9/9,
and trigger_called is exactly 1000 across 0 duplicates, 979 duplicates, 1 thread and
50 threads. Mutation arms that drop, steal or duplicate a notification still fail on
dumb_watch_triggered_counter (997, 999, 1001).
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 0 open findings)

Reviewed by an independent model that did not write the patch, over two rounds.

Round 1: 1 major, agreed and fixed.

❌ The fix was not verifiable by reverting it. assert trigger_called >= 1000 accepted the
excess mutations the old code issued, so the pre-fix body passed 3/3 (at 1024-1034 mutations for 1000
tokens) and a future refactor could reintroduce the bug with CI green. Fixed by tightening that bound
to == 1000, which the removal of unclaimed mutations makes exact. Verified by restoring the old
bodies underneath it: the test then fails assert 1026 == 1000 (26 mutations against paths the thread
held no token for). >= dates from the 2020 original, where mutating without a token was normal
behaviour; this change removes that behaviour, so the exact bound is part of the fix.

Round 2: 0 findings on the code; 3 majors on the PR description, corrected before publication.

⚠️ The draft said all four assertions were unchanged, which the tightening had made false and which
reads like a weakened test when diffing the patch. It also undercounted the mutation arms, and cited a
50/50 repetition batch that had run on the earlier, looser tree; the published text cites the 25/25
batch actually run on this content.

💡 Not changed: the empty changelog entry is correct for the CI Fix or Improvement category.

Also observed while triaging, not addressed here: three failures attributed to this test name are
server-side teardown defects surfaced by the module fixture (a nodes_seen logical error, a
LeakSanitizer leak in Coordination::Storage::BlockData::create, and a SIGSEGV), each belonging to
the pull request that surfaced it.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Verdict Evidence
a Deterministic repro PASS Replay of the observed /487 op order against a real Keeper: the pre-fix body fails 3/3 with assert 1 == 2. No threads, no sanitizer, no timing dependence. The race is also visible on every pre-fix run of the real test as trigger_called 1024-1034 for 1000 tokens.
b Root cause explained PASS Mutating before owning a token lets a deferred remove consume another thread's outstanding registration; a watch being one-shot per (path, session), that registration is never notified again.
c Fix matches root cause PASS The ordering inversion itself is removed. No widened bound, added wait, skip/no-parallel tag, weakened assertion, or post-hoc flush.
d Test intent preserved PASS Nothing is weakened. Three assertions are byte-identical, including dumb_watch_triggered_counter == 1000; the fourth is strengthened from trigger_called >= 1000 to == 1000. That bound was loose only because mutating an unclaimed path used to be ordinary behavior, so removing that behavior is what makes equality available. Consequence: reverting this change now reddens the test (assert 1026 == 1000), where before it passed silently at 1024-1034. Mutation arms prove each protected property still bites; the collision histogram proves the duplicate-registration coverage survived.
e Both directions PASS 3/3 fail before, 3/3 pass after, deterministically. Additionally, restoring the pre-fix bodies under the tightened bound fails with assert 1026 == 1000 (26 mutations issued against unclaimed paths), so the fix is verifiable by reverting it.
f General across code paths PASS Of every tests/integration/*/test.py that mentions watch and uses a Pool, only this one increments a counter inside a watch callback. Zero repo-wide occurrences of .remove() in a bare except on a pool-shared list. test_random_requests shares the variable name but builds its requests single-threaded and asserts fake-vs-genuine equality. test_keeper_watches is already correct by construction. No src/ carrier.
g Generalizes across inputs PASS Passes with 0 duplicate registrations (all paths distinct), 979 duplicates (50 threads over 21 paths), and a single thread, all re-run under the tightened bound. trigger_called is exactly 1000 in every configuration, 11/11 runs.
h Backward compatible N/A Test-only. No settings, serialization, format, or user-visible behavior; no SettingsChangesHistory.cpp entry needed.
i Invariants preserved PASS A mutation is issued only against a token the caller popped, and the token is appended only after the synchronous get registered the watch, so a token exists iff a live registration awaits a mutation. The emptiness test and the pop are under one lock (no TOCTOU), no Keeper call runs under it (no lock held across I/O, single lock so no ABBA), and the drain loop terminates on None instead of a racy while existing_path. Dropping the bare except around remove also means a genuine set() failure now surfaces instead of being swallowed.

Randomized runs: 50/50 and then 25/25 pass under Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6), the job that reported the failure; full test_keeper_back_to_back suite 9/9.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin, could you review this? It is a test-only fix: the test mutated a path before claiming its token from a list shared by 10 pool threads, so a stale removal could drop the token of a later registration, which then never got a mutation and its one-shot watch never fired.

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

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e02e7a8]

Summary: ✅


AI Review

Summary

This PR fixes test_keeper_back_to_back::test_concurrent_watches by claiming a path token under a lock before mutating it and by tightening the mutation-count assertion from >= to ==, so the original stale-token race is both removed and made detectable again if reintroduced. I reviewed the current diff, the surrounding test code, the prior PR discussion, and the current CI surface, and I did not find a remaining correctness issue that warrants an inline review comment.

Final Verdict

✅ No blocking issues found.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 9, 2026
@PedroTadim PedroTadim self-assigned this Aug 9, 2026
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e02e7a8

CI is fully finished on this commit: Finish Workflow, Config Workflow, Mergeable Check and
PR all SUCCESS, no check queued or in progress, and CIDB reports zero FAIL/ERROR test rows
for this SHA.

Check / test Reason Owner / fixing PR
(none) no failures on this commit not applicable

Session id: cron:our-pr-ci-monitor:20260809-210000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit 1d9cae3 Aug 10, 2026
180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 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 groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

4 participants