Skip to content

Preallocate multipart_tags deque to reduce dynamic memory allocation … - #101799

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
gagandhakrey:perf/s3-multipart-upload-allocation
May 7, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
gagandhakrey:perf/s3-multipart-upload-allocation

Conversation

@gagandhakrey

@gagandhakrey gagandhakrey commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem Overview:
Preallocate multipart_tags deque to reduce dynamic memory allocation overhead in S3 upload loop.

Summary:
During S3 multipart file uploads, the previous implementation dynamically allocated storage for part tags element-by-element inside the main scheduling loop using push_back. Since the exact number of file chunks is calculated prior to the loop, this dynamic allocation created completely unnecessary memory overhead and locking contention interleaved with thread queuing. This PR optimizes the flow by pre-allocating the entire container upfront and replacing dynamic sizing with direct index assignment, eliminating repeated heap allocations during chunk queuing.

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Reduce memory allocation overhead during S3 multipart uploads by preallocating internal tracking containers.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.419

@CLAassistant

CLAassistant commented Apr 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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

clickhouse-gh Bot commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [069f2ff]

Summary: ✅


AI Review

Summary

This PR preallocates multipart_tags with resize(num_parts) and switches from push_back to indexed assignment while scheduling multipart-upload tasks. On the current PR head, I did not find any new correctness, safety, concurrency, or performance issues introduced by this change.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Apr 5, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@gagandhakrey

Copy link
Copy Markdown
Contributor Author

Thanks @alexey-milovidov for merging the stress test fix commit, now most of the stress test passed but I see arm_msan stress test still failing , not only this pr but other PRs , Also on checking ci-cd logs for this step I don't find any reason of failure linked to changes in this pr, Do let me know if you feel this is failure due to my changes only , I will dig deeper and try to find out the root cause

@alexey-milovidov

Copy link
Copy Markdown
Member

The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158

@gagandhakrey

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov can you please help in closing it ,all stress test also passed, do let me know if anything required from my end

@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Gagan Dhakrey seems not to be a GitHub user.

We will need to rewrite the commits with your email from GitHub. Could you please do it?

@gagandhakrey
gagandhakrey force-pushed the perf/s3-multipart-upload-allocation branch from c5dcf9b to ff4a6a9 Compare May 5, 2026 15:47
@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix the failure of test_distributed_frozen_replica and send a separate PR. If the fix already exists, link it here.

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — investigated. The test_distributed_frozen_replica/test.py::test_cluster_all_replicas_query[3-test_cluster_secure] failure on this PR is unrelated to the S3 multipart change and is a chronic flaky test with a known second failure mode that emerged after my prior fix.

What's happening

There are two distinct failure modes for this test:

# Assertion failing Root cause Status
1 assert "857 ms" in error (formatted-error parity) HedgedConnections vs ReadBufferFromPocoSocket format the timeout-error string differently Fixed — PR #103780 (merged 2026-04-30) made the 857 ms assertion format-agnostic
2 assert "ALL_CONNECTION_TRIES_FAILED" in '' (empty error) The query unexpectedly succeeds because cluster.pause_container("node1") has a brief race window during which a freshly-resolved connection from node3 to node1 can complete the handshake before the cgroup freezer is fully effective Open — what your run hit

Auto-generated flaky-test issues already filed for mode 2: #103819, #103820 (filed 2026-05-01, after my mode-1 fix landed).

Cross-PR evidence (last 30d, mode 2 only)

17 distinct PRs hit the empty-error assertion:

PR    | hits  | days affected
0 (master) | 6
102499 | 2
100186 | 2
100141 | 2
103222 | 2
100399 | 2
100849 | 2
102165 | 2
103170 | 2
+ 8 more PRs at 1 hit each (incl. this PR #101799)

The 51-failure spike on 2026-05-05 was almost entirely a single PR (#100185, 48/51) and not a real surge.

Why mode 2 happens

clusterAllReplicas(test_cluster, …) calls Cluster::getClusterWithReplicasAsShards, which turns each replica into its own shard with no failover. So if node1's shard fails to connect, the whole query must fail with ALL_CONNECTION_TRIES_FAILED — there's no fallback.

The query should fail because node1 is paused. But Docker's pause is implemented via the cgroup freezer, and the test's flow is:

  1. node3.query("SYSTEM DROP DNS CACHE") — flushes cached resolutions
  2. Enter cluster.pause_container("node1") (freezer applied)
  3. Immediately issue the SELECT against clusterAllReplicas(...) with handshake_timeout_ms=857, connect_timeout_with_failover_ms=100

If steps 2 → 3 happen faster than the freezer fully suspends node1's ClickHouse process, node1 can complete the TCP handshake + ClickHouse server greeting (greeting is tiny, microseconds of work) before being frozen. After that the per-replica shard succeeds, all four shards return data, query returns count()=16, error='', and the assertion fails.

Fix direction

I'm filing a follow-up PR to make the test gate the actual probe on a deterministic check that pause is effective:

with cluster.pause_container("node1"):
    # Verify pause is effective before the actual test — connecting to node1 must fail.
    # Without this, the freezer can race the SELECT and let the query succeed.
    deadline = time.time() + 30
    while time.time() < deadline:
        try:
            node3.query(
                "SELECT 1 FROM remote('node1:9000', system.one) "
                "SETTINGS connect_timeout_with_failover_ms=200, "
                "handshake_timeout_ms=200, connections_with_failover_max_tries=1",
                timeout=2,
            )
        except QueryRuntimeException:
            break
    else:
        pytest.fail("cluster.pause_container did not take effect within 30s")

    # Now run the actual probe — pause is verified
    ...

This makes the test deterministic and preserves the original intent (validate that handshake_timeout_ms, connect_timeout_with_failover_ms, connections_with_failover_max_tries are honored when a replica is frozen). The 857 ms check from PR #103780 stays.

I'll post the fix PR shortly and link here.

— @groeneai (CI bot)

@groeneai

groeneai commented May 6, 2026

Copy link
Copy Markdown
Collaborator

Follow-up fix posted: PR #104167 — gates the probe on a deterministic pause-effective check, so the actual clusterAllReplicas test only runs once the cgroup freezer is demonstrably blocking connections to node1. Once that lands the chronic flake should stop hitting unrelated PRs like this one.

Comment thread src/IO/S3/copyS3File.cpp Resolved
… block

If `multipart_tags.resize(num_parts)` threw (e.g. `std::bad_alloc`) while
placed before the `try` block, the multipart upload already created by
`createMultipartUpload` would be silently abandoned as an orphan in S3,
because the `catch` block calling `abortMultipartUpload` would never be
reached.

Moving the resize to the first statement inside the `try` block ensures
that any allocation failure is caught and `abortMultipartUpload` is always
called to clean up the in-progress upload.
@clickhouse-gh

clickhouse-gh Bot commented May 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 100.00% (7/7) · Uncovered code

Full report · Diff report

@gagandhakrey

Copy link
Copy Markdown
Contributor Author

All of CI pipeline steps are successful, also have pushed all the commits with correct email address, also addressed one comment , should be good to merge now, if still anything else required from my end please do let me know

cc: @alexey-milovidov

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 7, 2026
Merged via the queue into ClickHouse:master with commit 679eed4 May 7, 2026
165 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 7, 2026
@PedroTadim

Copy link
Copy Markdown
Member

Hello! Can a performance test be added?

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 manual approve Manual approve required to run CI pr-performance Pull request with some performance improvements 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.

6 participants