Skip to content

Revert "Fix buffer overflows on data from external servers" - #120419

Merged
alesapin merged 3 commits into
masterfrom
revert-115706-fix-external-server-buffer-overflows
Sep 17, 2026
Merged

alesapin merged 3 commits into
masterfrom
revert-115706-fix-external-server-buffer-overflows

Conversation

@alesapin

@alesapin alesapin commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Reverts #115706


Workflow [PR]
Sync PR [sync-upstream/pr/120419]

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [75aa603]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR IGNORED

AI Review

Summary

The PR reverts most of #115706 and keeps only the follow-up MySQL BIT fix. That still leaves multiple object-storage safety contracts removed in the current head: I would block this because the revert reintroduces backup corruption races, queue data-loss paths, Azure short-read / bounded-read bugs, and two additional correctness regressions in the reverted code itself.

Findings

❌ Blockers

  • [src/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp:279] moveWithinBucket now queues work with object_from captured by reference from the range-for loop. The worker can run after the loop variable is rebound or out of scope, so it may move/delete the wrong object or hit UB. Capture object_from by value in the task.
  • [src/Backups/BackupIO.h:31] Removing the size- and generation-aware IBackupReader contract reopens the object-replacement races that backup restore still depends on being rejected. BackupImpl::openArchive reopens the archive through a factory and BackupImpl::copyFileToDisk still trusts reader->copyFileToDisk, so S3/Azure backups can now restore a replaced same-key object or splice archive generations instead of failing with S3_OBJECT_CHANGED_DURING_READ / FILE_CHANGED_DURING_READ. Restore a generation-pinned + expected-size read path in the interface and wire the object-storage readers back to it.
  • [src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp:1623] The queue still commits after_processing before Keeper, but this line now records only the path of the object that was ingested. The S3/Azure post-processing paths re-resolve that path later and copy/delete whatever generation is current then, so a producer can overwrite object A with B after ingestion and MOVE / DELETE will act on B even though B was never read. Keep the ingested generation in ProcessedFile and make post-processing conditional on that exact object, or fail the batch when it changed.
  • [src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:1841] The queue-specific “must read the generation that was listed” contract is gone and this falls back to plain s3_validate_etag_on_read. Azure reads are now never pinned, and S3 reads stop being pinned whenever that setting is disabled, so ObjectStorageQueue can read replacement B for a listed generation A and then mark A processed by path. Restore a caller-controlled “pin to the listed generation or fail” path instead of routing queue correctness through the plain-read setting.
  • [src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp:92] setReadUntilPosition no longer moves offset to getPosition() or drops the current working buffer before reopening. Real callers such as the Parquet / Arrow readers adjust this bound mid-read; with buffered bytes present, the next read can reopen at the stale end-of-download offset or throw LOGICAL_ERROR even though the consumer is still inside the requested range. Reinstate the discard/reopen logic here.
  • [src/Disks/IO/ReadBufferFromAzureBlobStorage.cpp:329] total_size is now whatever a single Download response reports, so a prematurely short Azure response becomes a fake EOF again. Once that body is drained, nextImpl() stops at offset == total_size and higher layers ingest only a prefix of the blob instead of reopening or throwing. The removed local size bound / end-of-object probe logic was what distinguished “short response” from “real EOF”; that needs to stay.
  • [src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp:387] Rollback scratch blobs are now written under __root, but MetadataStorageFromPlainRewritableObjectStorage::load enumerates __root as the published root-file namespace. Any failure or process stop after copying aside a file therefore leaves a random temp blob that comes back as a user-visible metadata file on the next startup. Keep temporary rollback blobs under a dedicated scratch prefix that load() does not scan.
Final Verdict

Status: ❌ Block

Minimum required actions:

  • Restore the object-generation / size invariants for backups and ObjectStorageQueue.
  • Fix the Azure bounded-read regressions in ReadBufferFromAzureBlobStorage.
  • Restore transaction-safe temp-object handling for plain-rewritable metadata storage.
  • Fix the async object_from capture in moveWithinBucket.

LLVM Coverage Report

Measured on commit 75aa603.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 792/915 (86.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 16, 2026
Comment thread src/Backups/BackupIO.h
/// what a reader of a storage where a file cannot be replaced in place has to offer.
virtual std::unique_ptr<ReadBufferFromFileBase> readFilePinnedToGeneration(
const String & file_name, std::optional<size_t> expected_file_size, const String & generation);
virtual std::unique_ptr<ReadBufferFromFileBase> readFile(const String & file_name) = 0;

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.

Removing the size- and generation-aware IBackupReader contract reopens the exact object-replacement races that the backup code still assumes are handled below. BackupImpl::openArchive still gives createArchiveReader a factory that reopens the archive object on every handle, and BackupImpl::copyFileToDisk still fast-paths directly to reader->copyFileToDisk without re-checking the checksum. On S3/Azure, a same-key overwrite can therefore be restored as backup data again instead of failing with S3_OBJECT_CHANGED_DURING_READ / FILE_CHANGED_DURING_READ; archive restores can even splice two generations across reopen. Please keep a generation-pinned + expected-size read path in the interface and wire the object-storage readers back to it.

StoredObject ingested_generation(file_metadata->getPath(), /* local_path */ "", bytes_size);
ingested_generation.etag = etag;
successful_files.push_back(std::move(ingested_generation));
successful_files.push_back(StoredObject(file_metadata->getPath()));

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.

commit() still runs after_processing before Keeper commit, but this line now throws away the ETag/size of the generation that was actually ingested. The current moveS3Objects/moveAzureBlobs paths re-resolve the key by path and then copy/delete that current object, so if a producer overwrites k after we ingest generation A but before commit, generation B is moved or deleted without ever being read. That is data loss for s3queue / azurequeue with after_processing = 'MOVE' or 'DELETE'. Please keep the ingested generation in ProcessedFile and make post-processing conditional on that exact object (or fail the batch when it changed).

/// Pin the read to the object generation seen here (etag from the LIST/HEAD): a GET with a
/// different ETag means an in-place overwrite, reported as S3_OBJECT_CHANGED_DURING_READ
/// instead of torn cross-generation data.
if (settings[Setting::s3_validate_etag_on_read] && object_info.metadata.has_value())

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.

This ties generation pinning back to plain s3_validate_etag_on_read, but ObjectStorageQueue needed a stronger contract: for after_processing = 'MOVE' / 'DELETE', it must read the generation the listing claimed, or fail closed. After this change Azure reads are never pinned, and S3 reads stop being pinned whenever that setting is disabled (including through compatibility), so a file listed as generation A can be read as replacement B and then marked processed by path. Generation A is skipped forever. Please restore a caller-controlled “must pin to the listed generation” path instead of making queue correctness depend on the plain-read setting.

total_size = *known_object_size;
else
total_size = std::numeric_limits<size_t>::max();
total_size = data_stream->Length() + offset;

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.

total_size is now whatever this single Download response reports. That makes a prematurely short Azure response look like true EOF again: once bytes_read drains that body, the next nextImpl() sees offset == total_size and stops, even if the caller listed/headed a larger object. Streaming readers that consume until EOF will therefore ingest only a prefix of the blob instead of reopening or throwing. The removed known_object_size / end-of-object probe logic was what distinguished “short response” from “real EOF”; please keep a local size bound and retry-or-throw when a response ends before it.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 16, 2026
/// needs - the source, and the destination derived from it - has to be a copy that
/// does not depend on where the loop over `objects` has got to by then.
task_tracker.add([&, objects_index, object_from = object_from_of_this_iteration]{
task_tracker.add([&, objects_index]{

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.

This async task no longer owns the StoredObject it operates on. object_from is the range-for variable, so [&, objects_index] leaves every queued task referring to a variable that is rebound on the next iteration and is gone once the loop exits. Depending on scheduling, the task can therefore copy/delete the wrong object or hit UB. Please capture object_from by value here, as before.

/// The blob is copied aside and then deleted: both requests must be about the same generation
/// of it, or the delete would take away content that was never copied.
const StoredObject source = pinToTheGenerationThatIsThereNow(*object_storage, remote_source_path);
remote_tmp_path = layout->constructFileObjectKey(PlainRewritableLayout::ROOT_DIRECTORY_TOKEN, getRandomASCIIString(16));

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.

MetadataStorageFromPlainRewritableObjectStorage::load treats every object under constructRootFilesDirectoryKey() / __root as a real root-level file. By storing rollback scratch blobs under __root, any failure or process stop after this copy leaves a random temp object that will be loaded as a user-visible file on the next startup. The removed scratch namespace was what kept these artifacts out of the published layout. Please keep temp blobs under a prefix that load() never enumerates.

if (static_cast<off_t>(position) == read_until_position)
return;

read_until_position = position;

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.

This no longer preserves the current read position when the bound changes. offset is the end of the currently opened download, not getPosition(), so if bytes are still buffered and a caller updates the bound (Parquet/Arrow do this through setReadUntilPosition), the next nextImpl() reopens at the stale offset or even throws LOGICAL_ERROR because read_until_position < offset while the consumer is still before that point. The old logic that moved offset to getPosition() and dropped the working buffer is required here.

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

This is a sync PR that reverts backup read/copy ETag-generation pinning across the backup IO readers and writers (src/Backups/BackupIO*), reverting the readFile signature back to a single-argument form. None of that code runs in a ClickBench SELECT. The only flagged row, ClickBench Q31 (+14.7%), was already deterministically suppressed as within master's current variance band (259-335 ms vs 304 ms median) and the query is intrinsically noisy, so the delta is run-to-run variance rather than a PR effect. No plausible regression or improvement attributable to this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 265 304 +14.7% <0.0001 This PR only reverts backup S3/Azure ETag-pinning plumbing (src/Backups); it cannot touch the SELECT path Q31 executes. The +14.7% is within master's current variance band, and this query is intrinsically noisy.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ac8a3c76-b68a-4c2c-b88f-96c495ee2016
  • MIRAI run: 44f47080-3559-42a4-9835-e2df9e67ea8c
  • PR check IDs:
    • clickbench_565405_1789644941
    • clickbench_565411_1789644941
    • clickbench_565418_1789644941
    • tpch_adapted_1_official_565428_1789644941
    • tpch_adapted_1_official_565440_1789644941
    • tpch_adapted_1_official_565476_1789644941

@alesapin
alesapin added this pull request to the merge queue Sep 17, 2026
Merged via the queue into master with commit 8a94d9e Sep 17, 2026
176 of 178 checks passed
@alesapin
alesapin deleted the revert-115706-fix-external-server-buffer-overflows branch September 17, 2026 13:58
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 17, 2026
alexey-milovidov added a commit that referenced this pull request Sep 19, 2026
`ReadBufferFromAzureBlobStorage::setReadUntilPosition` only recorded the new bound and
marked the download as not initialized, leaving the working buffer as it was. When the
bound was lowered below the end of the buffered bytes, those bytes were still handed out
past the bound, and the next download was then opened where the previous response ended
rather than at the bound, so the following `nextImpl` failed with the logical error
`Attempt to read beyond right offset (100 > 39)`. Formats that adjust the bound mid-read
(Parquet, Arrow, ORC through `AsynchronousBoundedReadBuffer`) are the callers.

The buffered bytes that lie past a lowered bound are now cut off the working buffer, and
the next download, if any, starts at the bound. Buffered bytes within the new bound are
kept, so raising the bound goes on reopening the download after them, as before, without
downloading them again. Setting the bound that is already in effect no longer drops the
download. The download itself is always reopened under a changed bound, since the current
one was requested under the previous bound.

`src/Disks/tests/gtest_azure_read_buffer_right_bound_change.cpp` lowers the bound below
already buffered bytes (fails with the logical error without the change), raises it after
some bytes were consumed, and sets the same bound twice, checking the bytes delivered, the
final position, and the offsets the fake endpoint was asked for.

This is one of the independent parts of
#115706, which was reverted in
#120419.
PedroTadim pushed a commit to JiaQiTang98/ClickHouse that referenced this pull request Sep 19, 2026
…ure copy

`BlobProperties::CopySource` and `CopyStatusDescription` are `Nullable` in the Azure
SDK, and `Nullable::Value()` of an empty one calls `std::abort` in a release build
(`AZURE_ASSERT_MSG` expands to a bare `std::abort` under `NDEBUG`). The completion of
an asynchronous native copy (`StartCopyFromUri` polled to the end) logged
`CopySource.Value()` and reported `CopyStatusDescription.Value()`, and the properties it
polls come from the remote endpoint, which is under no obligation to send either header.
The log names `src_blob` instead, and the failure message says `<none>` for a missing
description.

`src/IO/tests/gtest_azure_copy_blob_optional_properties.cpp` drives the asynchronous copy
against a fake Azure HTTP transport that reports the copy as completed without
`x-ms-copy-source`. Without the change, the unit test binary dies with `SIGABRT`.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419.
alexey-milovidov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 20, 2026
…equested one

A successful `Download` is not enough to trust the body: an endpoint, or a proxy in front
of it, that ignores the requested range answers `200 OK` with the whole object from byte 0,
and the reader consumed that body as if it started at the requested offset - both on the
sequential path (after a seek or on a reopen) and in `readBigAt`. The caller then got the
wrong bytes under the right offsets, which is silent data corruption.

The start of the returned range (`Content-Range`, which the SDK reports as 0 for a
`200 OK` response) is now checked against the requested offset before the body is read,
and a mismatch is `HTTP_RANGE_NOT_SATISFIABLE`. A full-object response is accepted exactly
when the request started at 0, where it is a correct answer, the same as in
`ReadWriteBufferFromHTTP`.

`src/Disks/tests/gtest_azure_read_buffer_range_check.cpp` drives a positioned read and a
sequential read after a seek against a fake endpoint that ignores ranges, and a read at
offset 0 and a well-behaved endpoint as controls.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419.
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 27, 2026
…hin one storage

`IObjectStorage::copyObjectToAnotherObjectStorage` handled the case where the destination
storage is the same instance by calling `copyObject`, and then fell through to the
generic path, which read the source and wrote the destination a second time through
buffers. The object ended up correct, but every such copy transferred the data twice: natively,
and then once more over the network through the server.

Return after the native copy. The default implementation is reached by every object
storage that does not override the method (Azure, Local, Web, HDFS, and S3 for a
cross-storage copy, which forwards to it), through `DiskObjectStorageTransaction`
and `BlobCopierThread`.

`src/Disks/tests/gtest_copy_object_to_another_object_storage.cpp` copies an object within
one local object storage and counts the reads and writes: exactly one of each.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419.
pull Bot pushed a commit to infdahai/ClickHouse that referenced this pull request Sep 27, 2026
`ReadBufferFromAzureBlobStorage::nextImpl` took the end of the response body as the end of
the data. For a read with a right bound that is wrong: the bound is set locally by the
caller, and every layer above the buffer takes it as the length of the data, so an endpoint
or a proxy that caps its responses - or a blob that is shorter than the size it was listed
with - silently truncated the file at the end of the first response.

A response that ends before the bound is now a premature end: the download is reopened at
the offset the read has reached and counted against `max_single_read_retries`, and when the
endpoint keeps ending its responses before the bound the read fails with
`UNEXPECTED_END_OF_FILE` instead of returning truncated data. A read without a right bound
keeps its behaviour. The amount left of the current download is measured per attempt, so a
reopened download is read from where it was reopened.

`src/Disks/tests/gtest_azure_read_buffer_premature_end.cpp` reassembles a 100-byte blob
from an endpoint that caps every response to 40 bytes, fails on a blob truncated at 40 bytes
after the retries are spent, and checks that an exact response and an unbounded read are
not reopened.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419.
groeneai pushed a commit to groeneai/ClickHouse that referenced this pull request Oct 4, 2026
…the response length

`ReadBufferFromAzureBlobStorage::initialize` derived `total_size` from
`BodyStream::Length`, which is the `Content-Length` chosen by the remote endpoint.
With `read_until_position = 100`, `offset = 0` and a 64-byte reading buffer, an
endpoint that answers the 100-byte ranged request with `Content-Length = 128` made
`nextImpl` hand out 64 bytes twice and only trip the right-bound check on the
following call, so 28 bytes from outside the requested range had already escaped into
the caller. With a reading buffer larger than the range, all 28 escape in a single call.

Derive the bound of the current download from `read_until_position`, which is set
locally by the caller, and let the length of the response only shorten it. The size
of the blob from the same response is not used for this: it comes from the same
untrusted place, and an endpoint that answers a ranged request with `200 OK` would
make it truncate a legitimate read.

`src/Disks/tests/gtest_azure_read_buffer.cpp` gains regressions that drive `nextImpl`
through `setReadUntilPosition` against a fake Azure HTTP transport whose response is
longer than the requested range, with a reading buffer both smaller and larger than
the range. Without the change they fail with
`Attempt to read beyond right offset (128 > 99)`.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419. The positioned read path,
`readBigAt`, was fixed separately in
ClickHouse#119054.
grantholly-clickhouse pushed a commit to grantholly-clickhouse/ClickHouse that referenced this pull request Oct 10, 2026
`ReadBufferFromAzureBlobStorage::setReadUntilPosition` only recorded the new bound and
marked the download as not initialized, but left the working buffer as it was. The bytes
that the current response had already delivered were still handed out - past a lowered
bound too - and the next download was then opened where the previous response ended
rather than where the reader was, so the following `nextImpl` failed with the logical
error `Attempt to read beyond right offset`, whether the bound was lowered or raised.
Setting the bound that was already in effect did the same, because it also dropped the
download.

A change of the right bound is now a new logical read, the same way a seek is: the working
buffer is dropped, the position is kept, and the download is reopened at the position under
the new bound. Setting the bound that is already in effect does nothing, so a caller that
sets it repeatedly does not reopen the download. `setReadUntilEnd` uses the same path.

`src/Disks/tests/gtest_azure_read_buffer_right_bound_change.cpp` lowers the bound below
already buffered bytes, raises it after some were consumed, and sets the same bound twice,
checking the bytes delivered, the final position, and the offsets the endpoint was asked for.

This is one of the independent parts of
ClickHouse#115706, which was reverted in
ClickHouse#120419.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants