Skip to content

Add native support for GCS - #105505

Closed
tanner-bruce wants to merge 14 commits into
ClickHouse:masterfrom
Shopify:gcs-grpc-high-level-clean
Closed

tanner-bruce wants to merge 14 commits into
ClickHouse:masterfrom
Shopify:gcs-grpc-high-level-clean

Conversation

@tanner-bruce

@tanner-bruce tanner-bruce commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

  • adds support for using gRPC DirectPath connectivity to GCS. Enables using workload identity for GCS access through the existing XML multipart workflow

This is obviously a very large PR, I've been testing quite thoroughly with benchmarks and in typical case it is quite a bit faster, but there is some nuance to it. I put this together to help out with testing. https://github.com/tanner-bruce/gcp-gcs-upload-benchmarks

Main questions:

  • I originally added support for specifying profile events as GCS specific, which required touching a bunch of the S3 code, but opted to remove it to limit where this PR touched. See bdfae65 for what the removal diff looked like. Is something like this desirable? I saw Azure has its own, but it goes through a separate code path. The native/gRPC code path does use the GCS profile events. This could easily be misleading to users.
  • Is the re-use of the S3 poco/xml multipart workflow acceptable?

Notes:

  • The write performance of gRPC is much lower than XML workflow, which is what brought on supporting the xml workflow still
  • I'm just finishing final benchmark suite and will post results here shortly.
  • if desired I can split this up into multiple PR, like gRPC first and then XML, or other way

Check close:

  • I'm not experienced with CMake. The modifications made in the CMake were fully driven by AI. It compiles and I haven't seen issue.

Fixes #91012

Register native GCS object storage and add the high-level GCS client, read/write/rewrite support, observability events, throttling, and regression coverage.

This commit intentionally excludes local planning, tmp, and autoresearch artifacts.
Use the high-level GCS client for native reads, writes, and related tests, including cancellation and offset-read fixes.
Add the XML multipart credential seam and guarded native GCS write transport, fail closed for create-if-absent, and use larger XML multipart defaults.

This commit intentionally excludes autoresearch artifacts.
Use a 64 MiB minimum XML multipart part size instead of a strict part size so the adaptive upload policy can still grow parts.

This commit intentionally excludes autoresearch artifacts.
Avoid draining an extra byte when a native GCS read already consumed the requested range.

This commit intentionally excludes autoresearch artifacts.
Increase native GCS parallel compose upload concurrency to improve large multipart-style writes.

This commit intentionally excludes autoresearch artifacts.
Reduce sequential read window growth and avoid reopening native GCS streams for buffered and small forward seeks.
Use a profile-events namespace for the shared XML multipart write buffer so native GCS XML multipart writes report GCS-prefixed counters while S3 users keep existing S3 counters.

Also thread the selected wait-inflight event through TaskTracker for shared multipart upload users.
Drop the direct Storage::StubInterface client, generated stub wrappers, low-level fake stub, and tests that exercised only that deleted path.

Keep coverage focused on shared status helpers, high-level client options, and native GCS object-storage behavior through the high-level client seam.

Test: ninja -C build clickhouse

Test: ninja -C build unit_tests_dbms

Test: build/src/unit_tests_dbms --gtest_filter='GCSGrpcClientFoundation.*:GCSObjectStorage*.*:GCSDiskType.*:GCSXMLMultipart*.*'
@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [953d90e]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
Build ClickHouse FAIL
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

This PR adds native gcs object-storage disk support with a gRPC path plus optional XML multipart writes, along with new profile events and config parsing. The implementation is close, but there are still unresolved write-path risks: one can cause unbounded memory growth in common copy flows, and another can cause stale temporary-object collisions after restart.

Findings
❌ Blockers
  • [src/Disks/DiskObjectStorage/ObjectStorages/GCS/GCSObjectStorage.cpp:760] s3_allow_parallel_part_upload = false currently disables chunk flushing entirely, so GCSWriteBuffer accumulates full object payload in staged_data and uploads only at finalizeImpl. This turns large writes into O(file_size) RAM usage and can trigger exceptions/OOM, especially because IDisk::copyThroughBuffers explicitly forces that flag to false to reduce memory pressure.
  • Suggested fix: keep chunked upload behavior regardless of this flag, and use the flag only to control concurrency (for example one in-flight/synchronous chunk upload instead of parallel uploads).
⚠️ Majors
  • [src/Disks/DiskObjectStorage/ObjectStorages/GCS/GCSObjectStorage.cpp:749] temporary object naming uses process-local upload_id starting from 1 on restart. If the server is interrupted mid-upload and temp objects remain, a later upload for the same object_name after restart can reuse the same temp names and fail precondition checks (if_generation_match_zero).
  • Suggested fix: include a restart-stable unique component (for example UUID) in the temporary prefix, or otherwise make stale temporary names non-conflicting.
Tests
  • ⚠️ Add a focused regression test for large writes with s3_allow_parallel_part_upload = false that verifies memory-safe chunk progression (not full-object buffering).
  • ⚠️ Add a restart-stale-temp scenario test (or equivalent deterministic unit seam) proving temporary-name uniqueness survives process restarts/crash leftovers.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
  1. Make the non-parallel GCS write path chunked/memory-bounded instead of buffering the full object.
  2. Make temporary upload object naming collision-resistant across restarts.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels May 21, 2026
@tanner-bruce

Copy link
Copy Markdown
Contributor Author

Native GCS / XML multipart benchmark summary

I ran a focused benchmark set on the native GCS branch to cover the cases most relevant to this PR:

  • single large realistic part upload
  • full scan from GCS on a single large realistic part
  • reading multiple large parts
  • reading many small parts
  • same logical bytes with different active part shapes

I did not include the multipart abort benchmark in this PR comment.

Environment

  • Branch: gcs-grpc-high-level-clean
  • Commit: 953d90e8a75
  • ClickHouse version: 26.5.1.1
  • Pod: clickhouse-builder-0
  • Bucket: shp-clickhouse-gcs-staging
  • Read benchmarks disabled/dropped ClickHouse-side caches before each measured query:
    • query cache
    • mark cache
    • uncompressed cache
    • filesystem cache
    • page cache / object-storage page cache
    • distributed/local remote-storage caches where applicable

1. Single large realistic part upload

Source table:

  • Rows: 40,000,000
  • Compressed bytes: 25,325,893,619 (23.59 GiB)
  • Uncompressed bytes: 106,052,517,928 (98.77 GiB)
  • Active parts: 1

Operation:

ALTER TABLE target ATTACH PARTITION ID '1778709600'
FROM p04_real_part.core_n4_v0_base
Variant Seconds Effective upload MiB/s Validation
s3 157.985 152.9 pass
xml 69.277 348.6 pass
xml_64m20 66.618 362.6 pass
native 76.652 315.1 pass

Takeaway: XML multipart was the fastest upload path in this run. Native GCS upload was also much faster than GCS-as-s3.


2. Single large realistic part full scan

Source database:

  • Each table: 40,000,000 rows, 23.59 GiB compressed, 1 active part

Query shape:

SELECT
    sum(length(message))
    + sum(length(`attrs.url.query`))
    + sum(arraySum(arrayMap(x -> length(x), mapValues(json_attributes))))
    + sum(arraySum(arrayMap(x -> length(x), mapValues(string_attributes))))
    + sum(arraySum(arrayMap(arr -> arraySum(arrayMap(x -> length(x), arr)), mapValues(string_array_attributes)))) AS payload_bytes
FROM table
SETTINGS
    use_query_cache = 0,
    use_uncompressed_cache = 0,
    enable_filesystem_cache = 0,
    use_page_cache_for_object_storage = 0,
    max_threads = 4
Variant Runs (s) Avg (s) Median (s) Avg read bytes/query Avg object read requests/query
s3 184.8, 179.1, 159.4 174.440 179.148 ~9.05 GiB ~31.7k
xml 102.7, 109.7, 101.4 104.595 102.656 ~9.06 GiB ~31.6k
xml_64m20 103.5, 102.6, 108.8 104.947 103.474 ~9.06 GiB ~31.6k
native 110.7, 135.5, 80.0 108.771 110.745 ~9.06 GiB ~31.6k

Takeaway: XML tables read through the native GCS read path, as expected. The native-read variants were much faster than GCS-as-s3 for this full scan, though native GCS still showed visible run-to-run variance.


3. Same bytes, different active part shape

3a. Full read by part shape

Query:

SELECT count(), sum(length(payload)), sum(metric)
FROM table
SETTINGS ... no ClickHouse-side caches ..., max_threads = 4
Shape Native avg (s) Native median (s) S3 avg (s) S3 median (s) Avg read requests/query
~1 part 2.175 2.242 1.858 1.824 ~224
16 parts 1.541 1.484 0.821 0.805 ~224
256 parts 9.371 9.249 16.277 16.304 ~1,024
1024 parts 48.741 44.872 70.601 70.640 ~4,096

Takeaway: once active part count gets high, native GCS reads scale better than GCS-as-s3 for the same logical full scan.

native is susceptible to cold start

3b. Subset / partition-pruned read

Query reads partitions in [parts / 4, parts / 2). For the ~1-part case this degenerates to the single partition.

Shape Native avg (s) Native median (s) S3 avg (s) S3 median (s) Avg read requests/query
~1 part 2.228 2.242 1.588 1.588 ~36-39
16 parts 2.760 2.745 8.721 8.589 ~68
256 parts 1.620 1.164 1.568 0.812 ~405
1024 parts 16.764 14.927 23.564 21.139 ~1,621

Takeaway: native GCS was much better on the 16-part subset and better on the 1024-part subset. The 256-part case was effectively tied/noisy.

3c. Point/index lookup

Query:

SELECT count(), sum(length(payload)), sum(metric)
FROM table
WHERE token = '<sample token>'
SETTINGS ... no ClickHouse-side caches ..., max_threads = 4
Shape Native avg (s) Native median (s) S3 avg (s) S3 median (s) Avg read requests/query
~1 part 3.066 2.807 2.555 2.668 ~308-316
16 parts 3.150 2.848 4.015 3.954 ~368-369
256 parts 9.094 7.595 14.958 13.279 ~977
1024 parts 24.940 16.982 27.767 20.109 ~2,029

Takeaway: native GCS wins from 16 parts onward, with variance on high part counts.

3d. EXPLAIN indexes = 1 point lookup

Shape Native avg (s) Native median (s) S3 avg (s) S3 median (s) Avg read requests/query
~1 part 1.005 0.999 0.748 0.686 1-2
16 parts 0.555 0.466 1.450 1.402 16
256 parts 4.128 4.231 10.827 10.715 256
1024 parts 15.058 15.015 27.226 27.239 1024

Takeaway: index analysis is very sensitive to active part count. Native GCS is significantly faster for many-part shapes.


Coverage summary

This benchmark set covers:

  • Single large part upload: realistic 23.59 GiB part upload.
  • Full scan from GCS on a single large part: realistic 23.59 GiB one-part scan.
  • Reading multiple large parts: 16-part, 4 GiB synthetic shape.
  • Reading many small parts: 256-part and 1024-part synthetic shapes.
  • Same bytes / different part shape: ~1, 16, 256, and 1024 active part shapes, each around 4 GiB compressed.

Caveats

  • The shape full scan reads payload and metric, not every column. It is still a full-row scan over all active parts, but not a full-byte scan of every column file.

return;

staged_data.append(working_buffer.begin(), size);
if (!allow_parallel_upload || (!parallel_mode && staged_data.size() <= parallel_write_threshold))

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.

write_settings.s3_allow_parallel_part_upload = false is used by IDisk::copyThroughBuffers specifically to reduce memory pressure, but this branch makes GCSWriteBuffer keep appending to staged_data until finalizeImpl. For large objects that turns writes into O(file_size) RAM usage and can cause exceptions/OOM during background copy/move flows.

Can we keep chunked uploads in this mode and only disable concurrency (for example, one in-flight/synchronous chunk upload) instead of falling back to a full-buffer single upload?

@tanner-bruce
tanner-bruce marked this pull request as ready for review May 21, 2026 13:33

static UInt64 nextUploadId()
{
static std::atomic_uint64_t counter{1};

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.

upload_id is process-local and restarts from 1 after server restart, while temporary object names are derived from {object_name, upload_id, part/compose index}. If ClickHouse is interrupted mid-upload and leaves temp objects behind, the first retry for the same object_name after restart can reuse the same temp names and fail on if_generation_match_zero preconditions.

Using a restart-stable unique suffix (for example a UUID) for the temporary upload prefix would avoid these stale-temp collisions.

@pamarcos pamarcos assigned pamarcos and unassigned pamarcos May 21, 2026
@abashkeev abashkeev added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 4, 2026
@alexey-milovidov

alexey-milovidov commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Continued in #109455.

alexey-milovidov added a commit that referenced this pull request Sep 24, 2026
`GCSObjectStorage::copyObject` and the same-client branch of `copyObjectToAnotherObjectStorage`
issued an unconditional `RewriteObject`, dropping `object_storage_write_if_none_match` /
`object_storage_write_if_match` from the write settings, while `WriteBufferFromGCS` enforces them
as generation preconditions. A copy creates its destination just like an upload, so both now pass
the same `IfGenerationMatch` (it applies to the destination of a rewrite), and reject the
preconditions the upload rejects. The helper moves from an anonymous namespace to
`makeGCSWritePrecondition` so both paths share it.

A failed precondition on the cross-storage rewrite is now reported instead of falling back to a
buffer copy, which would only have repeated the same conditional write.

Found while comparing with #105505, which honoured
`If-None-Match` in its rewrite.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Thank you @tanner-bruce for this work. The native GCS integration continues in #109455, and its changelog entry credits you with the initial implementation. Here is how the two differ.

Transport. This PR uses the gRPC client, with optional DirectPath (google-c2p://). #109455 uses the GCS JSON REST API of the vendored google-cloud-cpp, over a Poco-based transport instead of libcurl. So it builds without gRPC or opentelemetry (the build problem noted in #91012), and it goes through ClickHouse's own connection pool, proxy resolver, keep-alive and TLS handling. DirectPath is not available there.

Writes. This PR can also write through the S3 XML multipart path (write_transport = xml_multipart), and through gRPC compose-based parallel upload. #109455 does neither. It writes each object as one resumable upload stream, and anyone who wants the XML multipart path keeps the existing S3-compatibility path (use_native_gcs = 0, or an s3 disk). Given your benchmark (XML multipart ~349 MiB/s, compose ~315 MiB/s, S3-compatibility ~153 MiB/s), parallel upload is the main thing #109455 still lacks.

Scope and surfaces. This PR adds a disk type. #109455 adds the gcs object-storage and disk type, dynamic disk(object_storage_type = gcs, ...), the gcs(...) table function (behind the experimental use_native_gcs setting), and Iceberg tables on a native GCS disk. ENGINE = GCS stays on the S3-compatibility path.

Credentials. Both support Application Default Credentials (including workload identity) and an inline service-account key. #109455 adds a service-account key file (server config only), the google_adc_* refresh-token flow with automatic renewal, and anonymous access (NOSIGN / use_environment_credentials = 0). It rejects S3-only keys (HMAC, role_arn, SSE, ...) with an error instead of ignoring them.

Reliability.

  • Retries: a bounded LimitedErrorCountRetryPolicy (retry_attempts, default 10) with exponential backoff, instead of the SDK's 15-minute default.
  • Reads: every ranged read is pinned to the object generation (IfGenerationMatch), so a concurrent overwrite cannot be stitched into one read.
  • Conditional writes and server-side copies enforce If-None-Match: * / If-Match as generation preconditions.
  • Listing streams page by page instead of collecting everything into memory.

Not ported (yet).

Request-rate throttlers (max_get_rps / max_put_rps, as for S3) are being added to #109455 now.

@alexey-milovidov alexey-milovidov self-assigned this Sep 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 comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Contributing GCS GRPC support

5 participants