Skip to content

Wait for replication before asserting a row count in test_rename_distributed - #114274

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/test-rename-distributed-replication-barrier
Aug 13, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/test-rename-distributed-replication-barrier

Conversation

@groeneai

@groeneai groeneai commented Aug 11, 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_rename_column/test.py::test_rename_distributed asserts an exact row count right after
inserting into a Distributed table, with no barrier - only a 30 second poll in select().
Two things must finish first, and neither is awaited:

  1. The INSERT is background-spooled: insert_sync at StorageDistributed.cpp:1143 is false here
    (distributed_foreground_insert defaults false, table is persistent), so DistributedSink takes
    writeAsync and the INSERT returns while a block is still on the initiator's disk.
  2. internal_replication is true, so a shard's peer replica must FETCH every part (~100 tiny parts
    per INSERT per shard given PARTITION BY num % 100), and load_balancing defaults to RANDOM,
    so a shard leg can be served by a replica still fetching.

Found by inspection plus a local repro; public CI has not lost this race yet. Forcing the assert
onto its first read (poll=0) fails reproducibly with assert '1473\n' == '1998\n'. There,
system.distribution_queue held 2 un-flushed files while all four system.replication_queues
were empty, so a bare SYSTEM SYNC REPLICA returns vacuously. The spool drains first.

The fix adds a helper running SYSTEM FLUSH DISTRIBUTED then SYSTEM SYNC REPLICA on all four
nodes, after each insert. The first insert needs it too: the spool replays stored query text naming
the columns, so a block outliving the num2 -> foo2 rename replays INSERT ... (num, num2) and
fails permanently with NO_SUCH_COLUMN_IN_TABLE, reproduced separately. poll=30 is unchanged;
raising it only lengthens the bet.

Validated with the same poll=0 probe in both arms on one binary, so the barrier does the work and
not the poll: 2/2 fail without it, 3/3 pass with it. Then 50/50 green with poll=30 restored, whole
file green.

The sibling test_rename_distributed_parallel_insert_and_select also reads a Distributed table,
but its select() calls pass no expected_result, so they assert nothing about counts and are left
alone. The other eight tests read plain ReplicatedMergeTree.

Version info

  • Backported to: 26.7.11.8, 26.6.9.6, 26.3.33.97

…ributed

test_rename_distributed asserted an exact row count immediately after inserting
into a Distributed table, with no barrier of any kind. The only thing between the
INSERT and the assertion was a 30 second wall-clock poll inside the select()
helper, so the test bet on convergence instead of waiting for it.

Two data-movement gaps sit in that window and neither was awaited:

1. The Distributed INSERT is background-spooled. insert_sync at
   StorageDistributed.cpp:1143 is false here (distributed_foreground_insert
   defaults false, insert_shard_id is unset, the table is persistent), so
   DistributedSink::consume takes writeAsync -> writeToShard, which spools the
   block to disk, and onFinish waits on the job pool only when insert_sync is
   set. The client's INSERT therefore returns while a block is still on the
   initiator's disk.

2. internal_replication is true, so an INSERT lands on one replica per shard and
   the peer replica must FETCH every part through the ReplicatedMergeTree queue.
   PARTITION BY num % 100 over 1000 rows makes that ~100 tiny parts per INSERT
   per shard, and because load_balancing defaults to RANDOM the SELECT can be
   served by the replica that is still fetching.

Measured at the moment of the failing read: system.distribution_queue on the
initiator held 2 un-flushed files while all four system.replication_queue tables
were empty. A bare SYSTEM SYNC REPLICA would have returned immediately and
vacuously, so the spool has to drain first.

The barrier is also required after the FIRST insert, not only the last. The spool
replays stored query text that names the columns (createInsertToRemoteTableQuery
at DistributedSink.cpp:167, written into the file header at :949), and the test
renames num2 -> foo2 between its two inserts. Holding the spool across the rename
reproduces a permanent failure of that file:

  Code: 16. No such column num2 in table default.test_rename_distributed_replicated
  ... While sending .../shard2_all_replicas/1.bin (NO_SUCH_COLUMN_IN_TABLE)

poll=30 is left unchanged. Raising it would only lengthen the same bet, and
removing it would be a gratuitous change to a line the barrier already makes
deterministic.

Validated with the same binary in both arms and poll patched to 0, so the barrier
rather than the poll is what is being tested: the unmodified test fails 2/2 with
assert '1473\n' == '1998\n', and passes 3/3 with the barrier. Then 50/50 green
with poll=30 restored, and all 10 tests in the file green.

The sibling test_rename_distributed_parallel_insert_and_select also reads a
Distributed table, but its select() calls pass no expected_result and select()
asserts only when one is given, so it is not a carrier of this invariant and is
left untouched. The other eight tests in the file read plain ReplicatedMergeTree
per node, with no Distributed spool involved.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two findings from an independent cold review plus a second-model pass.

❌ 1 - wrong mechanism in a comment (fixed). The helper comment and the commit message
attributed read-replica selection to the rand() sharding key. rand() is consumed on the write
side only, to choose a shard; replica choice on reads comes from load_balancing (default
RANDOM), with prefer_localhost_replica pinning only the local leg. The sharding key affects
reads solely via shard pruning under optimize_skip_unused_shards (default off). Syncing all four
nodes is unchanged and better supported by the real mechanism. Both texts now name
load_balancing.

⚠️ 2 - keeping poll=30 (deliberate, DISAGREE). The suggestion was to drop the poll so that
reverting the barrier fails deterministically. That proof exists; it was produced with the poll
removed as a probe rather than shipped that way. With poll patched to 0 in both arms on one
binary, the unmodified test fails 2/2 (assert '1473\n' == '1998\n') and passes 3/3 with the
barrier. Non-vacuity is measured, not argued: at the failing read system.distribution_queue held
2 un-flushed files while all four system.replication_queue tables were empty, which is why the
flush comes first.

I kept it for two reasons. Pairing a barrier with a retry is ordinary here: 52 of the 108
tests/integration files using SYSTEM SYNC REPLICA also use a retry or wait helper. And the
50/50 green run was taken at poll=30, the shipped configuration, while poll=0 has 3 runs on an
idle local debug box; under sanitizers on a loaded runner, removing it would trade a rare flake for
a different one. Happy to drop it if you prefer.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. Patching poll=30 to poll=0 at test.py:772 makes select() assert on its first read; the unmodified test then fails 2/2 with AssertionError: assert '1473\n' == '1998\n'. The probe is reverted before commit (committed file keeps poll=30).
b Root cause explained? YES. Two unawaited gaps: (1) insert_sync is false at StorageDistributed.cpp:1143, so DistributedSink takes writeAsync and the INSERT returns while a block is still spooled on the initiator's disk; (2) with internal_replication true each shard's peer replica must FETCH ~100 tiny parts per INSERT (PARTITION BY num % 100), and load_balancing (default RANDOM) can route the read to a replica still fetching. Measured at the failing read: system.distribution_queue = 2 files, all four system.replication_queues = 0.
c Fix matches root cause? YES. It waits for exactly the two things that must happen, in the order the data travels: SYSTEM FLUSH DISTRIBUTED, then SYSTEM SYNC REPLICA on every node. No assertion weakened, no timeout raised, no fixture shrunk; poll=30 deliberately unchanged.
d Test intent preserved / new tests added? YES. Same 1998 assertion, same 2x2 cluster, same PARTITION BY num % 100 fixture, same async Distributed sink path under test; nothing skipped or widened. Test-only fix, so the changed test IS the coverage - no separate regression test warranted.
e Both directions demonstrated? YES, with the binary held constant (Build ID d898b027ae5db81d7cfea17a8b76962f73f3acf5) and poll=0 in both arms: pristine master FAILS 2/2; with the barrier, --count 3 PASSES 3/3. Passing at poll=0 shows the barrier, not the poll, makes it deterministic. Then 50/50 green with poll=30 restored, and the whole file 10/10 green.
f Fix is general across code paths? YES. All 14 asserting select() calls and both create_distributed_table users were enumerated from the file: line 782 is the only carrier. The eight test_rename_with_* tests read plain ReplicatedMergeTree per node (no spool). The helper flushes on the initiator and syncs every node passed in, so it covers any future caller.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for type wrappers - no expression, type or settings surface is touched. The relevant dimension here is topology, and it is covered: all four replicas of both shards are synced, so the fix holds for any load_balancing outcome rather than only the one observed.
h Backward compatible? (maintainer-approved exception only) YES, vacuously. Test-only change: no setting, no default, no serialization format, so no SettingsChangesHistory.cpp entry applies.
i Invariants and contracts preserved? YES. Both barriers sit inside the existing try block, so finally: drop_distributed_table(...) still runs and the table still exists when FLUSH DISTRIBUTED names it. Neither is wrapped in try/except: a genuine timeout must fail loudly (SYNC REPLICA ...: command timed out, InterpreterSystemQuery.cpp:2191) instead of degrading back into a silent short count. DEFAULT sync mode also covers the ALTER METADATA entries from the two renames.

Session id: cron:clickhouse-impl-slot-6:20260811-024900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter, could you review this? It is test-only: test_rename_distributed asserted an exact row count with no barrier, so it raced the Distributed spool drain plus the writer to replica part fetch against a 30 second poll, and the fix adds SYSTEM FLUSH DISTRIBUTED then SYSTEM SYNC REPLICA after each insert.

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

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af431ec]

Summary: ✅


AI Review

Summary

This PR makes test_rename_distributed deterministic by flushing the Distributed queue and waiting for replica catch-up before the exact-count assertion. The second barrier addresses the flake, but the first new barrier also narrows the scenario under test enough to hide a real failure mode for accepted async inserts that survive a later column rename.

Findings

⚠️ Majors

  • [tests/integration/test_rename_column/test.py:774] Flushing before the first rename removes the only coverage in this file for a background-spooled INSERT that is accepted under (num, num2) and replayed after the schema becomes (num, foo2). Because queued Distributed inserts persist the original column list, this change can turn a product-level NO_SUCH_COLUMN_IN_TABLE regression into a green test instead of surfacing it. Suggested fix: keep the replica barrier for the final exact-count assertion, but preserve the pre-rename queued-insert path here or split it into a dedicated regression test instead of serializing it away.
Final Verdict

⚠️ Needs changes before merge: the assertion flake fix looks reasonable, but the first barrier drops meaningful coverage for queued async inserts across RENAME COLUMN.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing af431ec59 with master 068ec6d2a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 692.30 MiB 689.29 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3b1be38

CI is fully finished on this head and there are no failures to own.

Check / test Reason Owner / fixing PR
(none) - no failed checks on this head
Sync - CH Inc sync (private, not actionable)

175 leaf jobs: 11 OK, 164 skipped, 0 failed, 0 dropped. The high skip count is expected for a
test-only diff and is not a dropped matrix: the praktika report for this head is top-level OK
with 0 DROPPED jobs, and every skip carries an explicit reason (Not affected by the changed files and not required x93, no build-affecting changes x25, none of the changed test modules apply x20, reused from cache x7, not labeled with 'pr-performance' x6, not a bug-fix PR
x5). CIDB reports no FAIL/ERROR rows for this commit.

Session id: cron:our-pr-ci-monitor:20260811-113000

try:
create_distributed_table(node1, table_name)
insert(node1, table_name, 1000)
sync_distributed_table(node1, nodes, table_name)

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.

Flushing here changes the test contract from “a successful async INSERT survives a later RENAME COLUMN” to “rename only after the Distributed queue is empty”. That narrows the only coverage in this file for a pre-rename block still sitting in the queue: DistributedSink persists the original column list into the queued insert header, so the old path is exactly what would catch a block accepted as (num, num2) later replaying into foo2 and failing with NO_SUCH_COLUMN_IN_TABLE. If the flaky part is only the final exact-count assertion, I think the barrier belongs before the final select, and the pre-rename queued-insert case should stay covered here (or move into a dedicated regression test/product fix) instead of being serialized away.

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 mechanism is right, and I measured it before shipping: DistributedSink stores the query
text with the original column list, so a block from the first INSERT that outlives the rename
replays (num, num2) and fails with NO_SUCH_COLUMN_IN_TABLE. Holding the spool across the
rename with SYSTEM STOP DISTRIBUTED SENDS reproduces it exactly (Code: 16 ... While sending .../shard2_all_replicas/1.bin, thrown at InterpreterInsertQuery.cpp:292).

What I disagree with is that the old path covered it. That replay runs on the directory queue's
background pool: the exception is caught at DistributedAsyncInsertDirectoryQueue.cpp:253 and
only recorded in status.last_exception (:439), and NO_SUCH_COLUMN_IN_TABLE is not in
isDistributedSendBroken (DistributedAsyncInsertHelpers.cpp:39), so the file is retried with
backoff rather than quarantined. The test reads neither system.distribution_queue nor
last_exception (zero occurrences before this change), its only assertion is the row count at
test.py:227, and the finally runs DROP TABLE ... SYNC, which deletes the pending blocks
(StorageDistributed.cpp:1596). So that case could only ever surface as a short count,
indistinguishable from the replication lag this PR is about.

Moving to a single barrier just before the final select makes it worse rather than better.
SYSTEM FLUSH DISTRIBUTED is synchronous and rethrows the first error
(StorageDistributed.cpp:2023), so with the first INSERT still spooled at that point the test
would hard-fail with Code: 16 precisely when the race lands. On a natural run with only the
first barrier removed I measured the spool surviving both renames (data_files=1), so that
window is live rather than theoretical. That trades a silent flake for a loud one.

On a dedicated test for the queued-insert-across-rename case: I am not raising one. The
user-visible report, #74723, was closed without a code change, and I have no evidence a
maintainer wants the case pinned. If a reviewer does want it, SYSTEM STOP DISTRIBUTED SENDS is
the deterministic lever (01790_dist_INSERT_block_structure_mismatch_types_and_names.sql uses
the same pattern for a structure mismatch), and it belongs in its own test rather than inside a
row-count assertion.

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 13, 2026
Merged via the queue into ClickHouse:master with commit e1f8c9d Aug 13, 2026
182 checks passed
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - af431ec

Every failure below has an owner: a fixing PR (ours 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.

CI is fully finished on this head and there are no failures.

Check / test Reason Owner / fixing PR
(none) no failed checks on this head n/a

Gates: 0 incomplete checks; Config Workflow and Finish Workflow both SUCCESS; last check
completed 2026-08-13T12:34:10Z. Coverage verified from the praktika report rather than the skip
ratio: result_pr.json top-level OK, 0 DROPPED, 0 ERROR-without-start_time, and every
one of the 162 skips carries a genuine reason (94 not affected by the changed files, 25 no
build-affecting changes, 20 no changed tests apply, plus per-label and cache reasons). 15 jobs
ran, including Integration tests on amd_asan_ubsan (db disk, old analyzer), amd_tsan, amd_msan,
arm_binary (distributed plan) and the flaky check. CIDB: 0 FAIL/ERROR rows for this commit
(4306 rows total, so the zero is signal).

This head is @ PedroTadim's merge of master into the branch (2026-08-13T08:14:14Z); my own commit
3b1be38da0d14ab is unchanged and the diff is still +10/-0 in
tests/integration/test_rename_column/test.py. The previous ledger covered 3b1be38da0d14ab,
so this one supersedes it for the current head.

Session id: cron:our-pr-ci-monitor:20260813-130000

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 13, 2026
@groeneai groeneai added the groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet label Aug 19, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Backporting to fix CI

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 17, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 17, 2026
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Backport #114274 to 26.3: Wait for replication before asserting a row count in test_rename_distributed
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Backport #114274 to 26.6: Wait for replication before asserting a row count in test_rename_distributed
PedroTadim added a commit that referenced this pull request Sep 17, 2026
Backport #114274 to 26.7: Wait for replication before asserting a row count in test_rename_distributed
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ting a row count in test_rename_distributed
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ting a row count in test_rename_distributed
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…ting a row count in test_rename_distributed
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-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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.

5 participants