Skip to content

Fix flaky test_replication_credentials replication race - #113473

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-test-replication-credentials
Aug 5, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-test-replication-credentials

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 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):

Made test_replication_credentials::test_same_credentials and ::test_no_credentials deterministic by waiting on SYSTEM SYNC REPLICA instead of a fixed time.sleep(1) before each cross-replica read.

Description

test_same_credentials and test_no_credentials insert into one replica and then
assert the table contents on the other, with a fixed time.sleep(1) as the only
barrier. When the INSERT returns its /log/log-N znode is durably in ZooKeeper,
but the other replica only learns of it asynchronously: it pulls the log, schedules
a background task, then fetches and commits the part over interserver HTTP. Nothing
in that chain is bounded by the test, so on a loaded runner it exceeds 1 s and the
assertion reads a stale replica:
AssertionError: assert '111\n' == '111\n222\n'. That has reached master
(sha cfc1fd2512eb276fe020907434207a08fbaa5e0b,
report),
plus 6 more across 3 unrelated PRs in 90 days, counting only an AssertionError at
one of the four reads querying the replica that did not receive the insert.

This replaces the barrier rather than the timing constant: the replica about to be
read runs SYSTEM SYNC REPLICA test_table with an explicit timeout=60. That is
the engine's own catch-up signal: it pulls the log synchronously, forces scheduling,
and snapshots the pending entry ids atomically with registering its callback, so it
cannot miss the entry it waits for and returns as soon as the fetch lands. The file
already uses this idiom four times.

All 8 assertions are byte-identical; only the barrier changed. Scope is
deliberately 2 tests, 4 lines: in test_different_credentials and
test_credentials_and_no_credentials the sleep guards a negative assertion across
intentionally mismatched credentials, where a sync can never complete: measured, it
fails with QueryTimeoutExceedException.

Validation: with the fetch stalled deliberately, the assertion fails before the
change with the exact CI signature and passes after it on the same binary;
reverting the barrier reddens it. 200/200 over 50 repeats.

Other failures in this file are pre-existing and separate: a ZooKeeper-container
start failure, a MemorySanitizer report, a SIGSEGV, and a Sanitizer assert from
cluster.shutdown().

Version info

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

test_same_credentials and test_no_credentials insert into one replica
and then assert the table contents on the other, with a fixed
time.sleep(1) as the only barrier.

ReplicatedMergeTreeSink commits the part's /log/log-N znode in the same
multi-op transaction that commits the part, so when the INSERT returns
the log entry is durably in ZooKeeper. The other replica, however,
learns of it only asynchronously: its queue_updating_task pulls the
log, a background pool task executes the resulting GET_PART, and the
part is fetched over the interserver HTTP endpoint and committed. None
of that chain is bounded by anything the test controls, so on a loaded
sanitizer runner it routinely exceeds one second and the assertion
reads a stale replica:

    AssertionError: assert '111\n' == '111\n222\n'

That reached master at cfc1fd2. Over
the last 90 days CIDB has 7 occurrences of the lag signature - an
AssertionError at one of the four reads that query the replica which
did not receive the insert - across 4 distinct refs, spanning both
tests. Over the same 90 days CIDB records 220751 OK and 13 FAIL
results for these two tests, so the lag accounts for 7 of the 13
failures: a genuine low-rate race rather than a broken check.

Replace the barrier instead of the timing constant: before each
cross-replica assertion, the replica about to be read runs SYSTEM SYNC
REPLICA test_table with an explicit timeout. waitForProcessingQueue
first calls pullLogsToQueue(..., SYNC), so a pending GET_PART is
guaranteed visible before the wait set is computed, then triggers the
background assignee, then addSubscriber snapshots the queue's entry
ids under state_mutex while registering the callback, so the wait
cannot miss the entry it must wait for and returns as soon as the
fetch lands. That turns an unbounded asynchronous wait into a
deterministic barrier at no fixed cost. The file already uses this
idiom at four other places. Raising the sleep was rejected: it treats
the symptom and re-races on a slower runner.

Scope is deliberately two tests and four lines. In
test_different_credentials and test_credentials_and_no_credentials the
sleep guards a negative assertion across intentionally mismatched
interserver credentials, where replication must not happen; a sync
there can never complete and fails with QueryTimeoutExceedException,
which was measured rather than assumed. All eight assertions are left
byte-identical, so the change only strengthens the barrier.

Validated with the fetch stalled deliberately on the reading replica:
the assertion fails before this change with the exact CI signature and
passes after it on the same binary, and reverting only the new barrier
reddens it again. 200/200 green over 50 repeats of the whole file.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 2 cold rounds, 1 gate finding, 6 self-found; 6 corrections applied, 1 refuted with evidence

This change was reviewed cold twice by independent models with no access to the
author's evidence notes, and every countable claim in the PR text, the commit message
and this comment was re-derived from CIDB or from the source tree. Verdicts below;
findings are the reviewers' unless marked as the gate's. Worth stating plainly: all
six self-found defects were in maintainer-facing TEXT. The 4-line diff itself was
found clean in both rounds, and no source change was made after the first review.

# Severity Finding Verdict
❌ 1 major The commit message said CIDB shows 8 occurrences of the lag signature across 4 distinct refs in 90 days. Re-measured, the lag signature is 7 rows across 4 refs in 90 days. The 8th row a looser predicate picks up is 2026-05-25 PR 105056 test.py:104, whose error is Code: 210 ... Connection reset by peer (NETWORK_ERROR) - not an assertion failure, and one of the rows this PR explicitly lists as out of scope. The two figures were also mutually inconsistent: that 8-row set spans five refs. (8 is the correct assertion-only count at a 120-day window, so the digit was stated against a window the text did not name.) Agreed - corrected, with the predicate now named.
❌ 2 major The commit message described the lag signature as an AssertionError at one of the eight cross-replica reads. Of the 8 assertions in the two changed tests, only four read the replica that did not receive the insert (:64, :69, :105, :110); the other four are same-node and cannot observe replication lag. Corroborated by the data: every observed lag row is at exactly those four sites, and none at the same-node four. Agreed - corrected to four; the same wrong phrase has also been removed from this comment, where the first round had introduced it.
❌ 3 major The pre-PR validation gate comment said All 11 cross-replica read sites in the file were enumerated; 4 are fixed and 7 dispositioned. Enumerated with ast, there are ten: 4 fixed, 4 negative assertions across intentionally mismatched credentials, and 2 already guarded by a pre-existing sync on the reading node. Agreed - corrected, with the disposition of all ten now given by line.
❌ 4 major The PR body grouped the pre-existing failures as the ZooKeeper-container and Client failed! infrastructure classes. One of those is not infrastructure: all four 2026-06-14 PR 107442 rows are a MemorySanitizer report (use-of-uninitialized-value, Return code: -6), i.e. a sanitizer abort. The other three classes checked out (ZooKeeper container start on 06-18, signal 11 SIGSEGV on 05-25, Sanitizer assert ... zoo1 from cluster.shutdown() on 07-31). Agreed - the paragraph now names each class for what it is.
⚠️ 5 nit The exercise rate is 46778 OK / 2 FAIL named neither its window nor its test set, so it was not reproducible. The substance holds either way (~3e-5). Agreed - now stated with both, at a named clock.
⚠️ 6 nit Two OK counts had drifted with the rolling window between rounds. Agreed - re-measured at publication: over 30 days the two changed tests are 94635 OK / 3 FAIL; over 90 days, 220821 OK / 13 FAIL. The load-bearing digits reproduce exactly: 7 lag rows, 4 refs, and 7 + 6 non-lag = the 13 total.
💡 7 major (gate) The gate asked for proof that the new barrier is required and actually waits, suggesting "a controlled fetch delay/failpoint exceeding one second, or equivalent before/after evidence". Disagreed - that evidence exists and is exactly the suggested shape.

On #7: three arms were run on one binary, differing only in the test file, with the
fetch stalled by SYSTEM STOP FETCHES on the replica about to be read and released
from a background thread after the barrier, so the stale window strictly spans it.
Pre-fix fails with AssertionError: assert '111\n' == '111\n222\n', byte-identical to
the master occurrence; post-fix passes under the identical injection; and reverting
only the one added SYSTEM SYNC REPLICA back to time.sleep(1) reddens it again,
which is what rules out the injection itself doing the work. The arms were confirmed
to be genuinely different files by reading each run's own echoed source rather than
trusting the labels.

The gate's other half - that the sync might be a silent no-op - is settled at source
rather than by a test, and was re-derived independently in the second round. The
barrier's return is causally chained to the part being queryable: the sink creates
/log/log-N in the same multi-op transaction that commits the part, returning success
only on ZOK; waitForProcessingQueue calls pullLogsToQueue(..., SYNC) first, and
that inserts the pulled entries into the in-memory queue under state_mutex before
the wait set is computed; addSubscriber then snapshots the pending entry ids under
both state_mutex and subscribers_mutex, carrying the in-source note that this must
be atomic with adding the callback, so the wait cannot miss its entry; and that entry
is erased - notifying the subscriber - only from removeProcessedEntry, whose only
caller on this path runs after executeFetch returned true, which itself returns true
only once fetchPart has committed the part via renameTempPartAndReplace and
checkPartChecksumsAndCommit. A no-op sync is not constructible without breaking that
chain. A bare SYSTEM SYNC REPLICA is SyncReplicaMode::DEFAULT, which is the
wait-set branch; only PULL returns early.

Also checked and found correct, so recorded rather than re-litigated: all eight
assertions in the two changed tests are byte-identical (zero assert lines in the
diff); ruff is clean, and the file is formatting-neutral against pristine master
(normalizing both copies leaves exactly the four intended lines differing);
timeout=60 is a client-side kill, inside both the server-side receive_timeout
default of 300 s and the harness default of 600 s, so 60 s is the binding bound and a
permanent fetch failure surfaces as a clear timeout rather than a stuck job;
import time is still required by the four untouched sleeps; the two-test scope is
right, and a sync at a negative window of the other two tests was measured to time
out, which is why they are untouched; the file's own four pre-existing uses of this
idiom are unchanged; the master occurrence was the only failing test of its check; and
the changed file is byte-identical between this PR's base and current master, so none
of these figures is stale against a moved base.

Session id: cron:clickhouse-review-slot-48:20260805-113700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand. The natural rate is ~3e-5 (over the 30 days to 2026-08-05 12:20Z CIDB records 94635 OK and 3 FAIL results for the two changed tests, and all 3 are the lag signature), so the lag is manufactured: SYSTEM STOP FETCHES test_table on the replica about to be read, with the release deferred past the barrier, then the assertion. Scored on the assertion TEXT, never the exit code.
b Root cause explained? Yes. The INSERT commits its /log/log-N znode synchronously, but the other replica learns of it asynchronously: pull the log, schedule a background task, fetch the part over interserver HTTP, commit it. Nothing bounds that chain, so time.sleep(1) is a guess at its latency and the assertion reads a stale replica.
c Fix matches root cause? Yes. It replaces the barrier, not the timing constant: SYSTEM SYNC REPLICA pulls the log synchronously (waitForProcessingQueue, StorageReplicatedMergeTree.cpp:9956), forces scheduling, and snapshots the pending entry ids atomically with registering its callback (ReplicatedMergeTreeQueue.cpp:2808). Explicitly not a band-aid: the sleep was not raised, no assertion weakened, no tag added, no data reduced.
d Test intent preserved / new tests added? Preserved exactly. All 8 assertions are byte-identical, mechanically checked (git diff | grep -cE '^[+-].*assert' = 0). No new test is owed: this makes two existing tests deterministic, and the coverage is the file itself. A control run with only the new barrier reverted reddens again, so the tests still detect the defect.
e Both directions demonstrated? Yes, same binary (Build ID 90e990c38257405d868fb9b7cb253aff2da8369f), same injection: before the change the assertion FAILS with the exact CI signature AssertionError: assert '111\n' == '111\n222\n'; after it, PASSES. Plus an anti-vacuity control (barrier reverted, reddens) and 200/200 over 50 repeats of the whole file.
f Fix is general across code paths? Yes. All 10 cross-replica read sites in the file were enumerated with ast (pairing each assertion with the preceding insert, then comparing the reading node against the inserted-into node): 4 are fixed (:64, :69, :105, :110), 4 are negative assertions across intentionally mismatched credentials (:151, :156, :223, :228), and 2 are already guarded by a pre-existing sync on the reading node (:183 after :181; :250 after :249). The remaining 8 assertion reads are same-node and cannot observe replication lag. The sibling test_no_credentials is fixed too, though the master hit was only in test_same_credentials, because a cold CIDB re-measurement found a carrier there as well. The 4 negative-assertion sites being untouched is measured, not assumed: adding a sync at one of them fails with QueryTimeoutExceedException, since the credentials are mismatched by design and the fetch can never succeed.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (integration-test barrier fix, not a code bug). No C++ types, no type wrappers, no settings matrix, no boundary values.
h Backward compatible? (maintainer-approved exception only) N/A (test-only). No setting defaults, no SettingsChangesHistory.cpp entry, no serialization format, no versioning.
i Invariants and contracts preserved? Yes. The invariant is: before asserting a replica's contents, that replica has caught up to the log. The barrier is bounded on both sides, by the client-side timeout=60 (helpers/client.py:226, Timer(timeout, kill_process)) and by the server-side receive_timeout inside waitForProcessingQueue, so a genuine permanent fetch failure surfaces as a clear timeout rather than a stuck job. Only sites with working credentials are synced, so a permanent failure there would itself be a real bug worth surfacing.

Session id: cron:clickhouse-review-slot-48:20260805-113700

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix, could you review this? Two tests in test_replication_credentials insert into one replica and assert on the other with only a fixed time.sleep(1) in between, so a slow interserver fetch reads a stale replica; this waits on SYSTEM SYNC REPLICA on the reading replica instead, leaving all eight assertions byte-identical.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e2550f]

Summary: ✅


AI Review

Summary

This PR replaces four fixed time.sleep(1) barriers in tests/integration/test_replication_credentials/test.py with SYSTEM SYNC REPLICA ... timeout=60 on the replica that is about to be read, so the two positive replication tests wait for replication progress instead of guessing on wall-clock delay. I reviewed the current diff, the surrounding test file, the SYSTEM SYNC REPLICA wait path in InterpreterSystemQuery and StorageReplicatedMergeTree, the prior PR discussion, and the current all-green CI report; I did not find a correctness, coverage, or PR-metadata issue that warrants an inline finding.

Final Verdict

✅ Approve. No blocking findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 5, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 5, 2026
Merged via the queue into ClickHouse:master with commit a8a51cc Aug 5, 2026
179 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 0e2550f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks infra: build-profile telemetry INSERT fails against the CI logs cluster (non-gating hook; the enclosing check reports success, so it is invisible to the check-runs API) #113409 (external, open)

Session id: cron:our-pr-ci-monitor:20260805-170000

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-master PR origin: master/nightly CI monitoring finding 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