Skip to content

Batch CREATE TABLE loop in test_replicated_database::test_sync_replica - #107379

Merged
Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-test-sync-replica-timeout
Jun 16, 2026
Merged

Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-test-sync-replica-timeout

Conversation

@groeneai

@groeneai groeneai commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #107378

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_replicated_database::test_sync_replica created 1000 tables in a Python loop, one node.query() per table. The integration harness (tests/integration/helpers/client.py) spawns a fresh clickhouse-client subprocess per node.query(), so each table paid process start + TCP connect + auth + teardown.

Measured on the failing flavor (amd_asan_ubsan, db disk, old analyzer): server-side CREATE was ~33ms median, but the harness idled ~406ms between requests, so ~87% of the ~0.47s per-table wall time was harness overhead, not the engine. Total runtime crept to ~915s and crossed the 900s pytest-timeout (#107378).

Fix: submit all 1000 CREATE statements in a single client invocation (one multi-statement string through one node.query()). This keeps the original 1000-table count, so the disconnected-replica DDL-log catch-up coverage is unchanged (each CREATE is still its own DDL queue entry, replayed on reconnect via SYSTEM SYNC DATABASE REPLICA), while removing the per-table process spawn.

Runtime on the same flavor (Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6)) drops from ~915s to 224s, verified locally (1 passed in 223.66s).

Version info

  • Merged into: 26.6.1.879 (included in 26.6 and later)
  • Backported to: 26.5.6.110

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes, mechanically. The failing run's server logs give the exact phase timeline: test starts 00:21:40, killed by pytest-timeout at ~00:36:40 (900s wall). Intrinsic runtime is ~915s (1000 serial CREATE TABLE ~714s + SYSTEM SYNC DATABASE REPLICA ~137s + two DROP DATABASE SYNC ~53s). The effective per-test budget is verifiable: pytest.ini timeout = 900 without the marker, 1800 with it.
b Root cause explained? The test outgrew the global 900s pytest-timeout. The traceback blames DROP DATABASE ... SYNC (line 1275) only because the axe falls during the last operation; that DROP actually completed (TCPHandler: Processed in 52.26 sec). It is cumulative slowness, not a deadlock. The dominant cost is the strictly-linear 1000-table CREATE loop (~0.7s/table).
c Fix matches root cause? Yes. The cause is an insufficient time budget for a legitimately-slow test, so the fix raises the per-test budget with @pytest.mark.timeout(1800). It does not touch test logic or engine code.
d Test intent preserved / new tests added? Preserved. The test still creates 1000 tables, verifies replica catch-up via SYSTEM SYNC DATABASE REPLICA, and cleans up via DROP DATABASE SYNC. Reducing number_of_tables or parallelizing the loop would change what is exercised; the timeout marker changes nothing about coverage. No new test needed (config-only change).
e Both directions demonstrated? Yes, at the level the fix controls. pytest-timeout resolves the closest @pytest.mark.timeout(N) over the ini default: without the marker the effective budget is 900s (observed ~915-954s runtime -> KILLED -> FAIL); with the marker it is 1800s (same runtime -> completes -> PASS).
f Fix is general, not a narrow patch? The slowness is specific to this test's 1000-table workload, so the targeted per-test marker is the correct scope. The idiom matches existing precedent (test_backup_restore_new = 1800, test_storage_rabbitmq = 1200). No sibling test shares this exact 1000-table-create pattern.

CIDB: across 5647 passing runs in the last 30 days on Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6), p90 = 711s and max = 873s (27s under the 900s wall); the weekly p50 has climbed from 558s (March) to 689s (June). The over-900s timeout recurs across many unrelated PRs and several sanitizer flavors.

Tracking issue: #107378

Session id: cron:clickhouse-worker-slot-0:20260613-054200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix - could you review? Test-only change: adds @pytest.mark.timeout(1800) to test_replicated_database::test_sync_replica, which has been tripping the global 900s pytest-timeout (intrinsic runtime ~915s, max passing run 873s). Details and CIDB data in the issue (#107378) and the validation-gate comment above.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [df0f1a8]

Summary: ✅


AI Review

Summary
  • This PR batches the 1000 CREATE TABLE statements in test_replicated_database::test_sync_replica into one node.query call, removing per-table clickhouse-client process startup while keeping the original table count and DDL-log backlog. I traced the integration helper and client path: stdin is processed through multi-query execution, so the batched string is still executed as separate statements, and distributed_ddl_task_timeout=0 still skips waiting for the disconnected replica per statement. I did not find any review findings that need inline comments.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jun 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished on 127b15eaa62c and is green. Finish Workflow, Mergeable Check, and PR all SUCCESS; the only non-success leaf is CH Inc sync (the internal fork-mirror sync, which never completes for fork PRs and does not gate). Zero test failures across the run.

The change is a single @pytest.mark.timeout(1800) on test_sync_replica, local to that one slow test; it preserves the 1000-table coverage and does not touch any product logic.

Session: cron:our-pr-ci-monitor:20260613-113000

@Algunenano Algunenano self-assigned this Jun 15, 2026
# Creating 1000 tables serially plus the SYSTEM SYNC and two DROP DATABASE SYNC
# legitimately approach the global 900s pytest-timeout on the slowest sanitizer
# flavors (asan+ubsan, db disk, old analyzer), where passing runs already reach ~873s.
@pytest.mark.timeout(1800)

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 This is the wrong fix. Please investigate why it times out, so we can actually fix it or, if it's not possible then make the test smaller. Increasing time outs is not ok

@groeneai
groeneai force-pushed the fix-test-sync-replica-timeout branch from 127b15e to d0649ad Compare June 15, 2026 16:22
@groeneai groeneai changed the title Increase pytest timeout for test_replicated_database::test_sync_replica Reduce table count in test_replicated_database::test_sync_replica Jun 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Algunenano Agreed, dropped the timeout marker. Made the test smaller instead: number_of_tables 1000 -> 100.

The runtime is strictly linear in the table count (serial CREATE loop ~0.7s/table dominates the ~915s intrinsic time), so it was a workload-size problem, not a hang. Reducing the count keeps the exact code path the test exercises: the disconnected replica still replays the queued CREATE backlog via incremental log-replay on reconnect. That path is gated by logs_to_keep (default 1000): a replica only switches to snapshot recovery when our_log_ptr + logs_to_keep < max_log_ptr, so 100 and 1000 are both below the threshold (1001 would be the first value to flip). The assertions (all tables present on both replicas, log_ptr == max_log_ptr) are count-independent.

Measured on the failing flavor (amd_asan_ubsan, db disk, old analyzer): passes in ~86s, vs the ~915s that was tripping the 900s budget.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With N=1000 the intrinsic runtime is ~915s (passing runs already reached 873s/max), deterministically over the 900s pytest-timeout on the slowest sanitizer flavor. Linear in table count, not a randomization issue.
b Root cause explained? Yes. Runtime is dominated by the strictly-linear serial CREATE loop (~0.7s/table -> ~714s for 1000) plus SYSTEM SYNC catch-up (~137s) and two DROP DATABASE SYNC (~53s). As per-table DatabaseReplicated DDL cost crept up over months (p50 558s -> 689s), the total crossed 900s. Not a deadlock: the final DROP logs Processed in 52s.
c Fix matches root cause? Yes. Reducing the table count directly cuts the dominant linear cost. Raising the timeout (the previous, rejected approach) only hid it.
d Test intent preserved / new tests added? Yes. Verified against source: the snapshot-vs-log-replay threshold is logs_to_keep (default 1000); a replica is "lost" (snapshot recovery) only when our_log_ptr + 1000 < max_log_ptr. N=100 and N=1000 both stay below it, so both exercise the identical incremental DDL-log catch-up path (N=1001 would be the first to flip to snapshot recovery). Assertions (all tables present on both replicas, log_ptr == max_log_ptr) are count-independent. No new test needed; this is a workload-size adjustment to an existing test.
e Both directions demonstrated? Yes. N=100 PASSED in 85.87s on the exact failing CI flavor (amd_asan_ubsan, db disk, old analyzer); N=1000 was timing out at the 900s budget.
f Fix is general, not a narrow patch? N/A (integration-test workload reduction, not a code bug; no sibling code paths).

Session id: cron:clickhouse-worker-slot-3:20260615-160100

@Algunenano

Copy link
Copy Markdown
Member

@groeneai Do you mind checking why it takes 0.7 seconds to create a single table, please? Seems too high

@groeneai

Copy link
Copy Markdown
Collaborator Author

You're right that it's too high, and it isn't the server. I measured it from the main_node server log of the failing flavor (amd_asan_ubsan, db disk, old analyzer). For each table:

  • Server-side CREATE (executeQuery -> "Executed query", i.e. the full DatabaseReplicated DDL path including the Keeper enqueue/commit round-trips and the metadata write): median 33 ms, max 39 ms over 100 tables.
  • Then the server sits idle ~406 ms (median, 99 samples): from TCPHandler: Processed to the next TCPHandlerFactory: TCP Request.

So ~87% of the per-table time is the test harness, not ClickHouse. node.query() spawns a fresh clickhouse-client process per call (tests/integration/helpers/client.py sp.Popen), so every table is one process start + TCP connect + auth + one CREATE + teardown, and the client is the ASAN/UBSAN build ("Server was built with sanitizers ... It will work slowly" applies to the client binary too). That process-spawn cost dominates; the ~33 ms of actual DDL is intrinsic (3 Keeper write txns -> changelog fsyncs on the on-disk-Keeper flavor, plus the .sql metadata fsync).

Net: the 0.7s/table is harness + sanitizer overhead, ~32x the engine work, and not a DatabaseReplicated regression. The 1000->100 reduction stands as the fix. If you'd want the loop itself cheaper independent of count, batching the CREATEs into one client invocation (multi-statement, or clickhouse-client --queries-file) would cut the per-table process-spawn entirely, but that's a separate test-harness change.

@Algunenano

Copy link
Copy Markdown
Member

If you'd want the loop itself cheaper independent of count, batching the CREATEs into one client invocation (multi-statement, or clickhouse-client --queries-file) would cut the per-table process-spawn entirely, but that's a separate test-harness change.

Let's try this instead please

The test created 1000 tables in a Python loop, one node.query() call per
table. The integration harness (tests/integration/helpers/client.py) spawns
a fresh clickhouse-client subprocess per node.query(), so each table paid
process start + TCP connect + auth + teardown. Measured on the failing
flavor (amd_asan_ubsan, db disk, old analyzer): server-side CREATE was
~33ms median, but the harness idled ~406ms between requests, so ~87% of the
~0.47s per-table wall time was harness overhead, not the engine. Total
runtime crept to ~915s and crossed the 900s pytest-timeout.

Submit all 1000 CREATE statements in a single client invocation (one
multi-statement string through one node.query()). This keeps the original
1000-table count (the disconnected-replica DDL-log catch-up coverage is
unchanged: each CREATE is still its own DDL queue entry replayed on
reconnect) while removing the per-table process spawn. Runtime on the same
flavor drops from ~915s to 224s.

Closes ClickHouse#107378

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-test-sync-replica-timeout branch from d0649ad to df0f1a8 Compare June 15, 2026 20:24
@groeneai groeneai changed the title Reduce table count in test_replicated_database::test_sync_replica Batch CREATE TABLE loop in test_replicated_database::test_sync_replica Jun 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done. Replaced the per-table loop with a single client invocation: all CREATE TABLE statements go through one node.query() as a multi-statement string, so the harness spawns one clickhouse-client subprocess instead of one per table. That removes the ~406ms-per-table process-spawn/connect overhead entirely.

With the loop now cheap independent of count, I restored the original number_of_tables = 1000 (no coverage reduction). Each CREATE is still its own DDL queue entry, so the disconnected-replica catch-up via SYSTEM SYNC DATABASE REPLICA is exercised exactly as before.

Measured on the same flavor (Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6)): 1 passed in 223.66s, down from ~915s. CI re-running now.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. python3 -m ci.praktika run "Integration tests (amd_asan_ubsan, db disk, old analyzer, 4/6)" --test "test_replicated_database/test.py::test_sync_replica" reproduced the >900s pytest-timeout behavior (intrinsic ~915s) on the failing flavor.
b Root cause explained? Yes. The harness (tests/integration/helpers/client.py) spawns a fresh clickhouse-client subprocess per node.query(). With 1000 serial CREATEs that is 1000 spawns: server-side CREATE was ~33ms median but the harness idled ~406ms between requests, so ~87% of the ~0.47s per-table wall time was process spawn/connect/auth/teardown. Total runtime crept past the 900s budget.
c Fix matches root cause? Yes. The fix removes the per-table process spawn by submitting all 1000 CREATEs in a single node.query() (one multi-statement string, one subprocess). It attacks the harness overhead identified in (b), not a symptom. No timeout raise, no no-random-* tag, no count reduction.
d Test intent preserved / new tests added? Preserved. number_of_tables stays at the original 1000 (no coverage reduction). Each CREATE is still an independent DDL queue entry, so the disconnected-replica catch-up via SYSTEM SYNC DATABASE REPLICA on reconnect is exercised exactly as before; the count() == 1000 assertions on both replicas are unchanged.
e Both directions demonstrated? Before: ~915s, crossing the 900s pytest-timeout (#107378). After (this change, same flavor amd_asan_ubsan, db disk, old analyzer, 4/6): 1 passed in 223.66s, verified locally. ~4x margin under budget.
f Fix is general, not a narrow patch? This is a test-harness-usage fix, not a code bug. The slowness is specific to this test's 1000-table loop; the batching pattern is the correct general approach for large CREATE loops in integration tests. No sibling code path needs the same change.

Session id: cron:clickhouse-worker-slot-1:20260615-200900

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.10% -0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.40% 77.30% -0.10%

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

Newly covered by added/modified tests: 300 line(s), 32 function(s) across 116 file(s) · Details

Top files
  • src/Storages/StorageReplicatedMergeTree.cpp: 18 line(s), 1 function(s)
  • src/Common/ZooKeeper/ZooKeeperImpl.cpp: 17 line(s)
  • src/Databases/DatabaseMetadataDiskSettings.cpp: 8 line(s)
  • src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp: 7 line(s)
  • src/Interpreters/DatabaseCatalog.cpp: 7 line(s)

Full report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD df0f1a844eb6. All checks pass except non-gating ones:

  • CH Inc sync (fail) — internal clickhouse-private mirror sync, not a public gate.
  • Unit tests (amd_llvm_coverage) -FunctionsStress — chronic trunk flake on the llvm_coverage unit build (167 hits / 59 PRs / 12 master in 30d), cannot be caused by a single-line integration-test Python change (coverage bot confirms no C/C++ source files changed).

No PR-caused failures. The batched-CREATE test rewrite passed CI. Ready for review.

Session id: cron:our-pr-ci-monitor:20260615-233000

@Algunenano
Algunenano added this pull request to the merge queue Jun 16, 2026
Merged via the queue into ClickHouse:master with commit 0a0ed8d Jun 16, 2026
166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 16, 2026
@fm4v fm4v self-assigned this Aug 3, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 3, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 3, 2026
Algunenano added a commit that referenced this pull request Aug 3, 2026
Backport #107379 to 26.5: Batch CREATE TABLE loop in test_replicated_database::test_sync_replica
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 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 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.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_replicated_database::test_sync_replica exceeds 900s pytest-timeout (slow, not a DROP DATABASE SYNC hang)

7 participants