Skip to content

Fix GCS native copy - #48981

Merged
nikitamikhaylov merged 2 commits into
masterfrom
gcs-copy-support
Apr 24, 2023
Merged

nikitamikhaylov merged 2 commits into
masterfrom
gcs-copy-support

Conversation

@antonio2368

@antonio2368 antonio2368 commented Apr 20, 2023 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Correctly set headers for native copy operations on GCS.

GCS doesn't support multipart copy, only single object copy.
There is a possibility that we can remove the limitation for object size when it comes to copy, because, based on my tests, it's possible to copy files > 5GB using a single request.

There is a problem of copying an object which was created with a multipart upload. If copy is called on such object this error will be produced:

Rewriting objects created via Multipart Upload is not implemented yet. As a workaround, you can use compose to overwrite the object (by specifying nhsa6s1smucz.us-central1.gcs.gcp.clickhouse-staging.com/file.csv as both the source and output of compose) prior to rewrite

ComposeRequest will be added in future PRs but there is a problem of getting random 503 error codes when I try to call it on completed multipart upload.

Until that is fixed, with this PR, we are sure that the copying will fallback to manual data copying inside CH instead of simply failing.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-improvement Pull request with some product improvements label Apr 20, 2023
@nikitamikhaylov

Copy link
Copy Markdown
Member

test_merge_tree_s3/test.py::test_cache_with_full_disk_space[node_with_limited_disk] and test_merge_tree_s3/test.py::test_freeze_system_unfreeze[node] are flaky (I've checked CI database)

@nikitamikhaylov
nikitamikhaylov merged commit c7d0ee2 into master Apr 24, 2023
@nikitamikhaylov
nikitamikhaylov deleted the gcs-copy-support branch April 24, 2023 12:09
alexey-milovidov added a commit that referenced this pull request Apr 28, 2023
Backport #49194 to 23.4: Revert "Fix GCS native copy (#48981)"
@maxknv
maxknv requested a review from Copilot November 17, 2025 16:47

Copilot AI left a comment

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.

Pull Request Overview

This PR fixes native copy operations for Google Cloud Storage (GCS) by addressing the fundamental difference that GCS doesn't support multipart copy operations like AWS S3. The changes introduce provider type detection and implement appropriate fallback mechanisms.

Key Changes:

  • Introduced ProviderType enum to distinguish between AWS, GCS, and unknown S3-compatible providers
  • Created custom CopyObjectRequest class that converts AWS-specific headers to GCS equivalents (e.g., x-amz-* → x-goog-*)
  • Added fallback logic to use regular upload when multipart copy is not supported

Reviewed Changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/IO/S3/ProviderType.h New header defining provider type enum and utility functions for provider detection and capability queries
src/IO/S3/ProviderType.cpp Implementation of provider type utilities including URL-based detection and multipart copy support checks
src/IO/S3/Requests.h Added custom CopyObjectRequest class and setProviderType() method to support GCS-specific header transformations
src/IO/S3/Requests.cpp Implements header conversion logic for GCS, replacing AWS headers with GCS equivalents
src/IO/S3/copyS3File.h Added CreateReadBuffer type alias and fixed whitespace formatting
src/IO/S3/copyS3File.cpp Core logic changes to detect provider capabilities and fallback to regular upload when multipart copy is unsupported
src/IO/S3/PocoHTTPClient.cpp Added GCS header detection and removal of AWS-specific headers for GCS requests
src/IO/S3/Client.h Added provider type member and getter method
src/IO/S3/Client.cpp Initialize provider type during client construction and propagate it to requests

Comment thread src/IO/S3/Requests.h

class CopyObjectRequest : public ExtendedRequest<Model::CopyObjectRequest>
{
public:

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CopyObjectRequest class overrides GetRequestSpecificHeaders() to handle GCS-specific header transformations. This is a significant behavioral difference from the base class and should be documented with a comment explaining why this custom implementation is needed (i.e., to convert AWS-specific headers to GCS equivalents for compatibility with Google Cloud Storage).

Suggested change
public:
public:
/**
* Override to handle GCS-specific header transformations.
* This custom implementation converts AWS-specific headers to their GCS equivalents
* for compatibility with Google Cloud Storage.
*/

Copilot uses AI. Check for mistakes.
Comment thread src/IO/S3/copyS3File.cpp
Comment on lines +632 to +634
return [&]
{
return std::make_unique<ReadBufferFromS3>(client_ptr, src_bucket, src_key, "", request_settings, Context::getGlobalContextInstance()->getReadSettings());

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lambda captures this by reference ([&]), which means it captures all member variables by reference. This is problematic because the lambda is passed to copyDataToS3File() which stores it and may call it multiple times during the upload process. The lambda references client_ptr, src_bucket, src_key, request_settings, which are all members of the CopyFileHelper object.

If the CopyFileHelper object goes out of scope while the lambda is still being used (e.g., in async operations via schedule), this will result in dangling references.

Consider capturing the necessary variables by value instead:

CreateReadBuffer getSourceObjectReadBuffer()
{
    auto client = client_ptr;
    auto bucket = src_bucket;
    auto key = src_key;
    auto settings = request_settings;
    return [client, bucket, key, settings]
    {
        return std::make_unique<ReadBufferFromS3>(client, bucket, key, "", settings, Context::getGlobalContextInstance()->getReadSettings());
    };
}
Suggested change
return [&]
{
return std::make_unique<ReadBufferFromS3>(client_ptr, src_bucket, src_key, "", request_settings, Context::getGlobalContextInstance()->getReadSettings());
auto client = client_ptr;
auto bucket = src_bucket;
auto key = src_key;
auto settings = request_settings;
return [client, bucket, key, settings]
{
return std::make_unique<ReadBufferFromS3>(client, bucket, key, "", settings, Context::getGlobalContextInstance()->getReadSettings());

Copilot uses AI. Check for mistakes.
case GCS:
return "GCS";
case UNKNOWN:
return "Unknown";

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This switch statement is missing a default case and doesn't explicitly return a value in all code paths. While the compiler may not warn about this due to covering all enum values, adding an explicit __builtin_unreachable() or throwing an exception in a default case would make the code more robust and clarify intent. This prevents undefined behavior if the enum is extended incorrectly in the future.

Suggested change
return "Unknown";
return "Unknown";
default:
__builtin_unreachable();

Copilot uses AI. Check for mistakes.
Comment thread src/IO/S3/Requests.cpp
if (it->first.starts_with("x-amz-meta-"))
{
auto value = std::move(it->second);
auto header = "x-goog" + it->first.substr(/* x-amz */ 5);

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment "/* x-amz */" is misleading. The substr(5) is actually skipping "x-amz" which is 5 characters, so the comment should clarify that this removes the first 5 characters to skip "x-amz". Consider updating the comment to: /* skip "x-amz" (5 chars) */ for clarity.

Suggested change
auto header = "x-goog" + it->first.substr(/* x-amz */ 5);
auto header = "x-goog" + it->first.substr(/* skip "x-amz" (5 chars) */ 5);

Copilot uses AI. Check for mistakes.
Comment on lines +30 to +35
ProviderType getProviderTypeFromURL(const std::string & url)
{
if (url.find(".amazonaws.com") != std::string::npos)
return ProviderType::AWS;

if (url.find("storage.googleapis.com") != std::string::npos)

Copilot AI Nov 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The URL parsing uses std::string::find() which performs substring search on the entire URL. For better performance and more robust detection, consider using URL parsing to check the hostname specifically, or at minimum check for the domain at word boundaries (e.g., using std::string::find("storage.googleapis.com") could match "mystorage.googleapis.com.evil.com"). Using proper URL parsing would be more reliable.

Suggested change
ProviderType getProviderTypeFromURL(const std::string & url)
{
if (url.find(".amazonaws.com") != std::string::npos)
return ProviderType::AWS;
if (url.find("storage.googleapis.com") != std::string::npos)
// Helper function to extract hostname from a URL
static std::string extractHostname(const std::string & url)
{
// Find scheme separator
std::string::size_type scheme_end = url.find("://");
std::string::size_type host_start = (scheme_end == std::string::npos) ? 0 : scheme_end + 3;
// Find end of hostname (start of path, port, or query)
std::string::size_type host_end = url.find_first_of(":/?", host_start);
if (host_end == std::string::npos)
host_end = url.length();
return url.substr(host_start, host_end - host_start);
}
ProviderType getProviderTypeFromURL(const std::string & url)
{
std::string hostname = extractHostname(url);
if (hostname.size() >= std::string(".amazonaws.com").size() &&
hostname.compare(hostname.size() - std::string(".amazonaws.com").size(), std::string(".amazonaws.com").size(), ".amazonaws.com") == 0)
return ProviderType::AWS;
if (hostname == "storage.googleapis.com")

Copilot uses AI. Check for mistakes.
CheSema added a commit that referenced this pull request Sep 9, 2026
…e too

The idempotency id is stamped as custom object metadata, and GCS accepts the
S3 spelling of that header and silently discards it: an upload completes, the
id never lands, and the recovery can never fire. Measured against a real
bucket - `x-amz-meta-*` returns 200 and stores nothing, `x-goog-meta-*` stores
and is returned.

ClickHouse already had the translation, but only on CopyObjectRequest, where
#48981 added it in 2023 to fix GCS native copy. That fix needed
x-amz-copy-source, and collected metadata-directive, storage-class and
x-amz-meta-* alongside it because a copy that replaces metadata needs all four
to agree. Nothing extended it, because copy failed loudly while the others
fail silently.

So the rename moves out of CopyObjectRequest into translateHeadersToGCS,
applied by ExtendedRequest for every request type in ApiMode::GCS.
CopyObjectRequest keeps no override of its own. Of the four headers, only
storage-class and x-amz-meta-* can occur outside the copy path, and both were
being dropped there - so this also fixes storage_class_name, which has never
taken effect on GCS for ordinary writes.

The response needs the mirror: GCS answers with x-goog-meta-*, while the SDK
builds GetMetadata() only from x-amz-meta-* (HeadObjectResult.cpp). PocoHTTPClient
now adds the x-amz-meta- spelling alongside, which is inert on every store that
does not emit the GCS prefix.

Renaming after signing would invalidate SigV4, so note that this fires only in
ApiMode::GCS, where credentials are empty and authorization is a bearer token
set by PocoHTTPClientGCPOAuth. The signed interop path is never translated, and
does not need to be: GCS accepts and returns x-amz-meta-* there, measured.

SSE is deliberately left out. Its mapping is not a rename - S3 uses
x-amz-server-side-encryption plus a key id, GCS uses a single
x-goog-encryption-kms-key-name with a different value - so a prefix rename
would be ignored just as silently.
CheSema added a commit that referenced this pull request Sep 9, 2026
Renaming it can only do harm. The value sets share nothing but STANDARD, and
GetStorageClassForName knows no GCS class, so a GCS one never reaches the wire
whatever the header is called. An S3 one does, and measured against a bucket:

    x-amz-storage-class: GLACIER    -> 200, object stored STANDARD (ignored)
    x-goog-storage-class: GLACIER   -> 400 InvalidStorageClass
    x-goog-storage-class: COLDLINE  -> 200, object stored COLDLINE

So translating it turns a misconfiguration GCS quietly ignores into a failing
write, for a header that can never carry a usable value. A GCS storage class
needs a value mapping, not a rename, which is the same reason server-side
encryption stays out.

This also stops CopyObject translating it, which #48981 has done since 2023.
That path can only carry S3 values too, so all it achieved was a 400 on copies
where every other path silently ignored the same setting.
CheSema added a commit that referenced this pull request Sep 9, 2026
This reverts 76ef5a2. CopyObject has translated x-amz-storage-class since
#48981, and dropping it changed behaviour this pull request did not set out to
change. Google's own migration guide maps the name too.

The value caveat that prompted the removal is real and is now recorded next to
the table instead: the two clouds share no class name but STANDARD, so an S3
one renamed onto GCS answers 400 InvalidStorageClass, and no GCS class can be
sent at all because GetStorageClassForName maps unknown names to NOT_SET.
Making storage_class_name work on GCS means passing the user's string through
instead of the enum, which is a change of its own.
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Sep 12, 2026
GCS spells a handful of headers with an x-goog- prefix and silently ignores
the x-amz- one - the request is accepted, the header is dropped, nothing is
reported. ClickHouse translates them, but only on CopyObjectRequest, where
ClickHouse#48981 added it in 2023 to fix GCS native copy. That fix needed
x-amz-copy-source, and picked up metadata-directive, storage-class and
x-amz-meta-* alongside because a copy that replaces metadata needs all four to
agree. Nothing extended it since, because copy failed loudly while the rest
fail silently.

Measured against a GCS bucket over the XML API with an OAuth token, which is
the x-goog-only mode ClickHouse Cloud uses on GCP:

    CreateMultipartUpload with x-amz-meta-*   -> 200, object has no metadata
    CreateMultipartUpload with x-goog-meta-*  -> 200, object has the metadata

So the rename moves into translateHeadersToGCS, applied by ExtendedRequest for
every request type in ApiMode::GCS; CopyObjectRequest keeps no override of its
own. Of the four headers only storage-class and x-amz-meta-* occur outside the
copy path, and both were being dropped there, so custom object metadata and
storage_class_name start taking effect on GCS for ordinary writes.

The response needs the mirror. GCS answers x-goog-meta-* while the SDK builds
GetMetadata() only from x-amz-meta- (HeadObjectResult.cpp), so PocoHTTPClient
adds the x-amz- spelling alongside for the same closed set of names. Both
directions read one table, so they cannot drift. The translated name is
lower-cased whole: the SDK makes whatever follows the prefix a key in a
case-sensitive map, and a server that answers in mixed case would otherwise
produce a key no lookup finds.

Renaming after signing would invalidate SigV4. It is safe because this fires
only in ApiMode::GCS, where credentials are empty and authorization is a
bearer token from PocoHTTPClientGCPOAuth. The signed HMAC interop path is
never translated and does not need to be - GCS accepts and returns
x-amz-meta-* there, also measured.

Server-side encryption is deliberately excluded. Its mapping is not a rename:
S3 uses x-amz-server-side-encryption plus a key id, GCS a single
x-goog-encryption-kms-key-name with a different value, so a prefix rename
would be ignored exactly as silently as the header it replaced.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants