Skip to content

Fix buffer overflows on data from external servers - #115706

Merged
alexey-milovidov merged 89 commits into
masterfrom
fix-external-server-buffer-overflows
Sep 15, 2026
Merged

alexey-milovidov merged 89 commits into
masterfrom
fix-external-server-buffer-overflows

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Places where data that comes from an external server was used without checking it against what was
requested locally:

  • ReadBufferFromAzureBlobStorage::readBigAt requests n bytes and copies body_stream->Length()
    bytes into a buffer that has room for n. The length is the Content-Length of the response, so
    an endpoint that returns more data than the requested range overflows the buffer. The S3
    implementation caps the copy at n; do the same here.
  • The handler of a MySQL BIT field copies value.size() bytes into a UInt64 on the stack. The
    length comes from the MySQL wire protocol, while a BIT value holds at most 64 bits.
  • The sequential Azure read path had the same "do not trust the remote length" defect:
    initialize derived total_size from BodyStream::Length, so with read_until_position = 100,
    offset = 0 and a 64-byte buffer, an endpoint answering the 100-byte ranged request with
    Content-Length = 128 delivered 28 bytes from outside the requested range to the caller before
    the right-bound check tripped on the following call. The bound is now derived from
    read_until_position, which is set locally.
  • ETag is an optional response header, and Azure::ETag::ToString aborts the process when the
    tag is absent - in release builds too, because AZURE_ASSERT_MSG expands to a bare std::abort
    under NDEBUG, dropping the message with it. Three call sites converted it unconditionally on a
    value taken straight from a response: setMetadataFromResponse on the details of every
    Download, AzureObjectStorage::getObjectMetadata on the answer to GetProperties, and both
    listing paths (listObjects and the async iterator) on the Etag element of every blob in the
    answer to ListBlobs. All of them are reachable by an endpoint that simply omits the header, and
    all but the first are outside the read-buffer flow. The guard now lives in one place,
    AzureBlobStorage::getETagOrEmpty, and every call site goes through it; no unguarded
    Azure::ETag::ToString is left in the tree.

Additionally, readBigAt reported the full requested size even when the endpoint kept returning
short responses and the retry budget was exhausted, so callers could use uninitialized data; it
now returns the number of bytes actually copied, and says so at warning level. It does not throw:
readBigAt is documented to stop at the end of the file and return the number of bytes read, and
the callers that cannot accept a short read (CachedInMemoryReadBufferFromFile, for one) already
turn it into UNEXPECTED_END_OF_FILE themselves.

parseMySQLBitValue also decoded short BIT payloads incorrectly on a big-endian host: the bytes
were written into the object representation of the result and reversed only on a little-endian one,
so a value shorter than 8 bytes stayed left-aligned and "\x01\x02" read back as
0x0102000000000000 instead of 0x0102. It is now assembled by shifting, which needs no byte
order at all.

Beyond the overflows, the Azure read and copy paths trusted the endpoint about where an object
ends and about which generation of it they were talking to:

  • Where the data ends is decided locally. read_until_position when the caller set one,
    otherwise the size the object had when it was listed or headed. That size is not an optional
    hint: it is the length of the file for every layer above the buffer -
    ReadBufferFromRemoteFSGather lays the next object of a file out right behind it,
    AsynchronousBoundedReadBuffer takes it as its own right bound, ReaderExecutor clamps object
    reads to it, and both caches address the data inside a file of that length - so the buffer ends
    the read there as well, and an endpoint that answers with more cannot push the excess under
    offsets that belong to something else. It is also the size the buffer reports: getFileSize
    answers with it without a HEAD, so a wrapper that sizes itself before it reads (the page cache,
    CachedInMemoryReadBufferFromFile) cannot learn the length of a newer generation at the key and
    expect bytes the buffer ends before. Where neither is available, reaching the Content-Range
    total of a response is treated as a question rather than an answer: the download is reopened at
    that offset and the end of the file is reported only if the fresh response delivers nothing
    either, or if the endpoint refuses the range with 416, which is how a real one answers a range
    past the end of a blob. An endpoint that caps an open-ended GET therefore cannot truncate the
    file silently.
  • Which generation is read is pinned. Every request of one logical read - the first Download,
    a retry, and a reopen after a premature end of the response - carries If-Match on the
    generation selected at read setup, and the ETag of every response is compared with it, so a
    blob overwritten in place mid-read raises FILE_CHANGED_DURING_READ instead of handing the
    caller bytes stitched together from two objects. The offset of the returned Content-Range is
    checked against the requested one, so an endpoint that ignores the range cannot deliver the wrong
    bytes under the right offsets.
  • Which generation is copied and deleted is pinned too. A native copy carries
    x-ms-source-if-match, the read-and-write fallback pins its reads, and a DELETE that follows a
    copy removes only the generation that was copied. The paths that copy-then-delete - the
    after_processing step of ObjectStorageQueue, the MOVE and unlink operations of a
    plain_rewritable disk, and backups - name the generation once and use it for every request, and
    refuse to act at all when the endpoint will not name one, rather than acting blind. The one
    one shape that cannot be pinned is a plain_rewritable move or hard link whose endpoint names no
    generation in its response to the copy to the destination: the operation is refused before the
    source is deleted, and its rollback does not delete the destination either - a delete by key alone
    could take away a generation another writer has put there since - but leaves the blob the copy
    wrote at its key and logs it. load rebuilds a directory from the blobs under its key, so that
    blob comes back as the uncommitted file on the next start until it is removed by hand; that is
    the fail-closed side of the trade, a copy of the source left behind rather than a blob deleted blind.
    The generation the copy wrote is named by the response to the copy itself:
    IObjectStorage::copyObject returns the ETag the endpoint reported for the object it created
    (CopyObject / PutObject / CompleteMultipartUpload on S3, Copy Blob From URL / Put Blob /
    Put Block List on Azure; an asynchronous Azure copy is trusted only when the destination
    properties report the copy that was started as the one that wrote the blob), and
    nameTheGenerationThatWasJustWritten makes no request of its own. No HEAD of the destination
    follows the copy, so a writer that replaces the destination right after it cannot have its
    generation bound to the operation: the rollback delete carries the copy's ETag and is refused.
  • The S3 copies have the same shape, as far as S3 allows. copyS3File and copyS3FileRange
    carry the ETag of the selected generation as x-amz-copy-source-if-match on the CopyObject
    and on every UploadPartCopy, and map a 412 to S3_OBJECT_CHANGED_DURING_READ before any other
    route is tried. The S3 backup writer (copyFileFromDisk, copyFile) and reader name the
    generation of the source with one HeadObject, check the measured size against the file being
    backed up or against the backup metadata (a restore of a backup file replaced by a longer object
    is refused rather than restored as its first bytes or copied whole), and use it for the native
    copy and for the pinned ReadBufferFromS3 of the fallback; the after_processing
    move and delete of ObjectStorageQueue pin their copy and their delete to the generation the
    listing reported, pin the read that ingests the file to that same generation whatever
    s3_validate_etag_on_read says (as they do on Azure), and a
    S3_OBJECT_CHANGED_DURING_READ anywhere in the post-processing aborts the batch like
    FILE_CHANGED_DURING_READ does on Azure. s3_validate_etag_on_read = 0 opts the S3 backup
    copies out of the pinning only, as it does every other S3 read, and not out of the size check;
    with the pinning off, though, the check holds for the object at the HeadObject only, and a
    same-key replacement between that HeadObject and the GET or CopyObject is not caught,
    because the read carries no generation to refuse it by - that window is what opting out gives
    up, for backups as anywhere else, while the replacement that is already there when the restore
    or backup starts is still refused. A backup opened as S3('...?versionId=...') is read at that
    version, and the native copy of a restore to an S3 disk addresses the same version
    (bucket/key?versionId=... on the CopyObject and on every UploadPartCopy), so it cannot
    restore the latest version of the key in place of the selected one.
    The read-and-write fallback of the backup writer reads through the disk (so it honours
    read_from_filesystem_cache) for every disk whose object keys are generated and never
    rewritten in place, and checks after the buffer is built that the file still names the object
    that was measured (a file rewritten in between names a new key, and is refused with
    S3_OBJECT_CHANGED_DURING_READ); only a plain / plain_rewritable disk gets the direct read
    pinned with If-Match. A plain_rewritable move or hard link names the generation of its
    source on Azure and on S3 (pinToTheGenerationThatIsThereNow), copies exactly that one, and
    refuses a source generation whose size is not the one the metadata records for the file
    (refuseAGenerationOfAnotherSize), so a target can never be recorded with the size of a
    generation it did not copy. The S3 delete is pinned too: S3 evaluates If-Match on a
    DeleteObject and the ETag element of every object of a DeleteObjects on general purpose
    buckets, so the delete that follows a copy (plain_rewritable unlink, move and hard link, the
    after_processing move of ObjectStorageQueue), the rollback deletes of a move and a hard link,
    and after_processing = 'delete' carry the generation that was copied or ingested and are refused
    with FILE_CHANGED_DURING_READ when another writer has replaced it; a batch deletes every object
    it can before it reports the replaced one. An S3-compatible endpoint that ignores If-Match on a
    DELETE deletes by key, as it did before the header was sent. The rollback of a
    plain_rewritable unlink or move whose delete already went through restores the blob it saved
    aside without writing over a key that another writer has recreated since, on Azure and on S3
    alike (restoreTheSavedBlobWithoutWritingOver): the saved blob is read pinned to its generation
    and put back with a create-if-absent write (If-None-Match: *), and a refused restore leaves the
    saved blob in the bucket at its temporary key rather than being retried blind.

src/Disks/tests/gtest_azure_read_buffer.cpp drives the reader, the copies, the deletes, the queue
post-processing and the plain_rewritable move operations against a fake Azure HTTP transport that
misbehaves in each of the ways above - a response longer than the requested range, a response
shorter than it, a Content-Range total that under-reports or shrinks, a range refused with 416,
a HEAD without an ETag or with a 404, an ignored range, and an overwrite placed at an exact
point of a request sequence. src/Disks/tests/gtest_azure_object_storage_metadata.cpp covers
getObjectMetadata, listObjects and iterate against an endpoint that omits the header;
src/Processors/tests/gtest_mysql_bit_value.cpp covers the BIT payload at every width from 0 to
8 bytes, with expectations written as numbers so that they hold on a host of either endianness.
src/IO/tests/gtest_writebuffer_s3.cpp drives the pinned S3 copies and deletes, and the
plain_rewritable move and hard-link operations on S3, against an S3 mock that keeps a
generation per object, keeps versions of a key, and evaluates x-amz-copy-source-if-match,
?versionId= on a copy source, If-Match on DeleteObject
and the ETag element of DeleteObjects; 05211_s3_backup_native_copy_etag
backs a table on an S3 disk up to S3 with a failpoint that makes the pinned copy carry a generation
the source never had, and 05210_s3_backup_plain_read_etag / 05194_s3_backup_archive_reopen_etag
do the same for the reads of a backup; 05212_s3_backup_restore_replaced_file replaces a data file
inside an S3 backup with a longer object and asserts that both the buffered restore and the native
copy of the restore refuse it; 05213_s3_backup_archive_without_etag makes HeadObject report no
ETag (failpoint s3_head_omit_etag) and asserts that the restore of an archive is refused up front,
because its reopens could not be pinned to one generation.

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fix buffer overflows and a server abort on malformed responses from external servers: an Azure Blob Storage endpoint that returns more data than was requested or omits the ETag header, and a MySQL server that returns an oversized BIT value. Azure reads, copies and deletes, and S3 copies made by backups and by S3Queue post-processing, are now pinned to the object generation they selected, so an object overwritten in place is reported instead of silently mixing two generations. Also fix the decoding of a MySQL BIT value shorter than 8 bytes on big-endian hosts.


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

Version info

  • Merged into: 26.9.1.1544 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [192b935]

Summary: ✅


AI Review

Summary

This PR substantially hardens Azure/S3 object reads, copies, and backup paths against malformed external responses and mid-read object replacement, and the latest S3 versionId and Azure async-copy fixes are present in the current code. One completeness gap remains in the archive-backed ObjectStorageQueue path: the generation carrier that the new queue logic relies on is still dropped before the read is opened, so the new after_processing contract is not yet upheld there.

Findings

⚠️ Majors

  • [src/Storages/ObjectStorage/StorageObjectStorageSource.cpp:2364-2424] Archive-backed ObjectStorageQueue inputs still lose the listed generation before createReadBuffer sees them. ReadTaskIterator::createObjectInfoInArchive rebuilds archive_object from RelativePathWithMetadata{path_to_archive, std::nullopt}, and ObjectInfoInArchive then copies only read_source_index, so both the listed etag and require_read_pinned_to_generation are dropped. With after_processing = 'move' or 'delete', generateImpl therefore still treats every archive member as “generation not reported” and fails it even when the outer LIST did return an ETag; if that guard were ever relaxed, the archive read would still be unpinned for s3_validate_etag_on_read = 0. Propagate the full RelativePathWithMetadata into the archive wrapper, or have ObjectInfoInArchive delegate metadata and pinning to archive_object.
Final Verdict

Changes requested: the new generation-pinning contract is still incomplete for archive-backed ObjectStorageQueue reads.

LLVM Coverage Report

Measured on commit 192b935.

Metric Baseline Current Δ
Lines 89.10% 89.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.60% +0.10%

Changed lines: Changed C/C++ lines covered: 3536/3856 (91.70%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 192b93557 with master 22be00763 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

54 object files changed (+415.60 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 351.87 KiB 421.27 KiB +69.40 KiB (+19.72%)
src/CMakeFiles/dbms.dir/Backups/BackupIO_S3.cpp.o 321.84 KiB 388.22 KiB +66.39 KiB (+20.63%)
src/CMakeFiles/dbms.dir/Disks/IO/ReadBufferFromAzureBlobStorage.cpp.o 239.13 KiB 290.64 KiB +51.51 KiB (+21.54%)
src/CMakeFiles/dbms.dir/Backups/BackupIO_AzureBlobStorage.cpp.o 279.51 KiB 321.30 KiB +41.80 KiB (+14.95%)
src/CMakeFiles/clickhouse_common_io.dir/IO/S3/copyS3File.cpp.o 561.39 KiB 590.38 KiB +28.99 KiB (+5.16%)
src/CMakeFiles/clickhouse_common_io.dir/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/Azu… 410.74 KiB 437.23 KiB +26.48 KiB (+6.45%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureObjectStorage.… 410.74 KiB 437.23 KiB +26.48 KiB (+6.45%)
src/CMakeFiles/dbms.dir/Storages/ObjectStorageQueue/ObjectStorageQueuePostProcessor.cpp.o 349.74 KiB 372.40 KiB +22.66 KiB (+6.48%)
src/CMakeFiles/dbms.dir/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp.o 259.98 KiB 281.81 KiB +21.83 KiB (+8.40%)
src/CMakeFiles/clickhouse_common_io.dir/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp.o 259.98 KiB 281.81 KiB +21.83 KiB (+8.40%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

366 translation units recompiled, 2434 s compile time in total, 366 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.93 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -258.5 s (-10%) in total before that adjustment.

Job report

Comment thread src/Processors/Sources/MySQLSource.cpp Resolved
… tests

Address review: `ReadBufferFromAzureBlobStorage::readBigAt` returned the requested size even when
the endpoint kept returning short responses and the retry budget was exhausted, so callers
could use uninitialized data. Return the number of bytes actually copied instead.

Extract `copyFromAzureBodyStream` and `parseMySQLBitValue` and cover both fixes with unit
tests: an endpoint returning more data than requested, a short response, and an oversized
MySQL `BIT` payload.
`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, instead of trusting the length of the response. 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.

Fold the tests of `copyFromAzureBodyStream` into a new
`src/Disks/tests/gtest_azure_read_buffer.cpp` and add regressions that drive `nextImpl`
through `setReadUntilPosition` against a fake Azure HTTP transport whose response is
longer than the requested range. Without the change they fail with
`Attempt to read beyond right offset (128 > 99)`.
`ETag` is an optional response header, and `Azure::ETag::ToString` calls
`AZURE_ASSERT_MSG`, which aborts the process - in release builds too, because that macro
is not compiled out with `NDEBUG`. `setMetadataFromResponse` called it unconditionally
on the response of every `Download`, both on the sequential path and in `readBigAt`, so
an endpoint that answers without an `ETag` took the server down.

Found while writing the regression for the ranged-read bound: a mocked response without
that header aborted the unit test binary with `SIGABRT`.
@SmitaRKulkarni SmitaRKulkarni self-assigned this Aug 24, 2026
Comment thread src/Processors/Sources/MySQLSource.cpp Resolved
Comment on lines +488 to +492
/// The endpoint kept returning short responses. Report how much was actually copied:
/// the caller must not treat the tail of its buffer as initialized.
LOG_DEBUG(log, "AzureBlobStorage readBigAt for file {} got only {} bytes out of {} requested after {} attempts",
path, initial_n - n, initial_n, max_single_download_retries);
}

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.

Maybe we should throw error (like UNEXPECTED_END_OF_FILE) here or increase level of log to warning. wdyt ?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 I took the second half of your suggestion and raised it to LOG_WARNING (it went in with 8329b8c, which touches the same file - the commit message only mentions the ETag work). Exhausting the retry budget against an endpoint that keeps answering short is not a normal condition and should be visible without turning up the log level of the whole server.

I did not make it throw, and I would rather leave that to you to overrule if you disagree. readBigAt is documented in SeekableReadBuffer as "Stops either after n bytes, or at end of file, or on exception. Returns number of bytes read", so a short return is the documented end-of-file signal, and the callers that cannot accept one already convert it into UNEXPECTED_END_OF_FILE themselves - see CachedInMemoryReadBufferFromFile, which compares the result against the requested size and throws exactly that. Throwing inside readBigAt would duplicate that error and take the choice away from callers that legitimately read up to the end of the file. What this pull request fixes is the previous behaviour of returning initial_n unconditionally, which told the caller that bytes it never received were initialized.

@SmitaRKulkarni SmitaRKulkarni left a comment

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.

Rest all LGTM

`parseMySQLBitValue` copied the payload into the object representation of the
result and reversed it only on a little-endian host. On a big-endian host a
value shorter than 8 bytes therefore stayed left-aligned: `"\x01\x02"` read
back as `0x0102000000000000` instead of `0x0102`, a wrong result for every
`MYSQL_TYPE_BIT` column on the big-endian targets we build for.

Assemble the integer by shifting instead, which needs no byte order at all.
The unit test now covers every width from 0 to 8 bytes; its expectations are
numbers rather than byte patterns, so they hold on a host of either
endianness.
…d` path

`Azure::ETag::ToString` aborts the process when the tag is absent, in release
builds too, because `AZURE_ASSERT_MSG` expands to `std::abort` under `NDEBUG`.
Guarding it in `ReadBufferFromAzureBlobStorage::setMetadataFromResponse` left
three call sites that take the same untrusted value straight from a response:
`AzureObjectStorage::getObjectMetadata` on the answer to `GetProperties`, and
the two listing paths (`listObjects` and the iterator) on the `Etag` element
of every blob in the answer to `ListBlobs`. All three are reachable outside
the read-buffer flow, so an Azure-compatible endpoint that omits the optional
tag could still take the server down.

Put the guard in one place, `AzureBlobStorage::getETagOrEmpty`, and route all
four call sites through it. There is no unguarded `Azure::ETag::ToString` left
in the tree.

`src/Disks/tests/gtest_azure_object_storage_metadata.cpp` drives
`getObjectMetadata`, `listObjects` and `iterate` against a fake Azure HTTP
transport that answers without an `ETag`.
The transport policy of the Azure SDK buffers the body of every response it
does not stream, by calling `ReadToEnd` on the body stream unconditionally. A
response constructed without one therefore dereferences a null pointer, which
is what the answer to the HEAD request of `GetProperties` did: the test
crashed before it ever reached the `ETag` conversion it was meant to cover.

Serve every response, including the empty body of the HEAD, from a body stream
that owns its data.
alexey-milovidov and others added 2 commits August 27, 2026 03:34
The AI review on #115706 found two remaining
gaps in the Azure hardening:

- `getTotalSizeOfCurrentDownload` shrank the bound of a right-bounded read to the remote
  `Content-Length`, so a short `206` response moved the end of the file before the locally
  requested `read_until_position`, breaking the `supportsRightBoundedReads` promise. The local
  bound is now authoritative: on a premature end of the response, `nextImpl` reopens the
  download at the current offset, and throws `UNEXPECTED_END_OF_FILE` once the retry budget is
  exhausted, instead of silently reporting a truncated file.
- `copyFromAzureBodyStream` capped the copy by the reported `Content-Length`, so an endpoint
  under-reporting it truncated a `readBigAt` even when the bytes were already in the response
  body. The size of the destination is the only bound needed: `ReadToCount` stops at the actual
  end of the body.

The unit tests now drive the reader through a range-aware fake transport: `ShortRangeResponse`
asserts that a bounded read reassembles the full range through reopens, the new `TruncatedBlob`
asserts the exception when the blob really ends before the bound, and the new
`LengthSmallerThanData` pins down that a lying short `Content-Length` does not truncate the copy.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115706&sha=439fb44121b960987a8ab86ba3fa2d9e46e1d1f1&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 — 03312_squashing_with_low_card_mem_usage failed in Fast test (arm_darwin), and it is unrelated to this PR: the same test failed on 2026-08-25, 2026-08-22, 2026-08-19, 2026-08-18, 2026-08-05, and 2026-08-01 across unrelated PRs (#116225, #111985, #111694, #112805, #107075, #115297, and others), so it looks like a recurring flaky memory-usage threshold test. Please provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already open: #113605 (CI: apply the runner free-space guard on macOS runners too), open since 2026-08-06 with a review requested from @ leshikus and no review yet.

One correction to the diagnosis: this is disk, not memory. The only failing leaf in the report you linked is

Code: 243. DB::Exception: Cannot reserve 317.74 MiB, not enough space. (NOT_ENOUGH_SPACE) (version 26.9.1.1)

on runner ip-172-31-9-239. All 13 failures of this test on Fast test (arm_darwin) in the last 30 days are that same code 243, with the requested reservation constant at 317.51-317.82 MiB and zero MEMORY_LIMIT_EXCEEDED rows, so the test's own footprint is not the variable. The host is: in the same window that check has 31 code-243 rows spread over 11 different tests, 18 pull requests and 6 runners, 0 on master, and 7 of them failed to reserve only 1.00-2.00 MiB (02476_analyzer_identifier_hints, 03640_skip_indexes_with_or, 04043_text_index_in_with_preprocessor and others). A volume that cannot hand out 1 MiB has no large test to blame. 03312_squashing_with_low_card_mem_usage is the most frequent victim only because it asks for the most space, so shrinking or tagging it would move the failures to the next-largest test instead of stopping them.

What #113605 changes: Runner.check_post_run() returns early on macOS before it ever runs df (ci/praktika/infrastructure/runner/runner-init.py:430), so those long-lived hosts have never enforced the free-space threshold Linux runners do. It runs the check on macOS as well, at job start in addition to post-run, and pins df -k so the block count means the same on BSD and GNU df.

…null `memcpy` in the test

`supportsReadAt` advertises positioned reads on a buffer on which nothing has been read yet, but
`readBigAt` dereferenced `blob_client`, which is only created by the sequential path and by
`tryGetFileSize`. It is also called concurrently on the same buffer, so it must not create the
shared member either: it now uses a call-local `BlobClient` when the shared one does not exist.

`AzureReadUntilPosition.TruncatedBlob` failed under UBSan because the fake transport served an
empty response body, and `memcpy` was then called with a null source pointer.
@groeneai

Copy link
Copy Markdown
Collaborator

Sent as #120303.

I took the caller-side retry policy rather than teaching clickhouse_execute_http a deadline: the stacktrace dump now takes one attempt, so it fails at 120 s and the diagnostic branch reports what it saw with the rest of the 600 s hung_check.wait left, instead of the group being killed during attempt five. Because the change is in the collector rather than in a per-caller budget, the stateless and fast-test callers get it too. If you meant a budget inside clickhouse_execute_http itself, say so and I will redo it that way.

One thing I did not expect: the retry budget was not the only reason the log held nothing but dots. The child's stdout is a block-buffered pipe (stress.py gives it stdout=tee.stdin, and neither the stress image nor the job's own docker run sets PYTHONUNBUFFERED), and after printing the failure the arm spends up to ~150 s collecting stacks, so a kill inside that window discarded the report too. Measured with two copies of the runner differing only in one sys.stdout.flush(), both killed at 230 s: without it the log carries no failure line at all, with it the line reached the log 19.5 s before the kill. Both halves are in the PR.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 16, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 16, 2026
…llision-114847

Master landed ClickHouse#115706, which pins an S3Queue read, copy and delete to the generation of the
SOURCE that was ingested. This branch guards the DESTINATION of a move. The two overlap, so the
merge is not textual:

- `copyS3File` and `copyAzureBlobStorageFile` keep master's positional `src_etag` / `src_version_id`
  and its `String` return; `S3CopyFileSettings` loses `source_if_match` and `source_version_id`,
  which said the same thing, and keeps the destination guard and the header and tag restatement
  the guard forces. `makeCopySource` goes, master has `copySource()`.
- `deleteFileFromS3` takes master's `etag_to_match` and then this branch's `version_id`. They are
  different operations: `If-Match` refuses a delete of a newer generation, a version id removes one
  named version and leaves no delete marker. Passing a version id in master's slot would have sent
  it as an `ETag`.
- The Azure read-and-write fallback is pinned to `src_etag` by master, so the refusal this branch
  raised there is gone.
- A source that is no longer the ingested generation now raises `FILE_CHANGED_DURING_READ` or
  `S3_OBJECT_CHANGED_DURING_READ` and is rethrown once the batch is done, so the file is not
  committed and the newer generation is read later. This branch logged it and committed the file,
  which left that generation in the bucket unread. `MoveResult::SourceRewritten` goes with it, and
  `removeCopiedSource` drops its head-then-delete check, which master's `If-Match` makes atomic.
- The queue source takes master's `ProcessedFile`, which carries the size as well as the `ETag`,
  and its fail-closed refusal to read a file whose generation the listing did not report.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 17, 2026
…ails, and skip if it is unavailable

`LogCluster.select` returned None for every kind of read failure and printed
only the last response's text, so its one caller could say no more than
"CI logs cluster query failed: <SQL>" and the reader had to open the job log to
find that the endpoint had answered `Code: 241 ... (MEMORY_LIMIT_EXCEEDED)`.

One shape was worse than a bad message. A failure raised after the status line
is already on the wire arrives in the body, in an `exception` field next to the
rows produced before it, and `response.ok` is true. Against a stub endpoint
answering `200` with that field and an empty `data`, master's `has_pr_data` gets
`[]`, the job posts "No arm_release build profile data for commit ..." and
completes OK: a failed read is a green check.

`select` now classifies every response with one module-level predicate - a body
that is a JSON object with a non-empty `exception`, otherwise a status that is
not ok - retries such an in-band failure like a 5xx, and raises `ReadFailure`
with the status and the cluster's own error. `Db.query` keeps no failure branch.

A cluster that cannot answer at all is not the commit's fault, so when every
observed failure was a `>= 500` or a `requests` timeout, `select` raises
`TransientReadFailure` and the job is SKIPPED with a pinned comment saying the
comparison did not run. One non-5xx refusal, a probe answering something other
than `1`, or a comment that did not post keeps the check red, so a 403 is still
a failure. The skip is not cached: the verdict is the cluster's health, which no
digest input captures, and a cached success would turn one pressure spike into
a permanent skip.

The readiness probe is classified the same way. It used to return a bare False
after printing `No connection to LogCluster` with neither status nor body, so a
run that failed there was red with nothing to attribute it to; it now prints
both, and a `>= 500` or a timeout there is transient like the read itself.

Requested in ClickHouse#115706 (comment)
and ClickHouse#118708 (review) .
Supersedes ClickHouse#120121 , closed in
favour of this one.

Co-Authored-By: Claude Opus 5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 17, 2026
…collision-114847

Master reverted ClickHouse#115706, which this PR is built on. The revert is kept everywhere
(backups, plain_rewritable, the Azure read buffer, MySQLSource, their tests), while the
S3/Azure copy-and-delete generation pinning this PR needs is carried by the PR itself.

Resolved: AzureObjectStorage.cpp, S3ObjectStorage.cpp, gtest_azure_read_buffer.cpp,
copyAzureBlobStorageFile.cpp, copyS3File.cpp, deleteFileFromS3.{cpp,h}, getObjectInfo.cpp,
ObjectStorageQueuePostProcessor.{cpp,h}.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
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.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
…ails, and skip if it is unavailable

`LogCluster.select` returned None for every kind of read failure and printed
only the last response's text, so its one caller could say no more than
"CI logs cluster query failed: <SQL>" and the reader had to open the job log to
find that the endpoint had answered `Code: 241 ... (MEMORY_LIMIT_EXCEEDED)`.

One shape was worse than a bad message. A failure raised after the status line
is already on the wire arrives in the body, in an `exception` field next to the
rows produced before it, and `response.ok` is true. Against a stub endpoint
answering `200` with that field and an empty `data`, master's `has_pr_data` gets
`[]`, the job posts "No arm_release build profile data for commit ..." and
completes OK: a failed read is a green check.

`select` now classifies every response with one module-level predicate - a body
that is a JSON object with a non-empty `exception`, otherwise a status that is
not ok - and raises `ReadFailure` with the status and the cluster's own error.
`Db.query` keeps no failure branch.

A cluster that could not serve the read is not the commit's fault, so in that
case `select` raises `TransientReadFailure` and the job is SKIPPED with a pinned
comment saying the comparison did not run. Three observations mean the read was
not served: a `>= 500`, a `requests` timeout, and an error the server reports
after it has already committed an ok status, which is the condition a `>= 500`
reports when it happens before the status goes out. The two are the same event
seen at different points of one answer, so they are classified alike.

Anything else keeps the check red: a 403 or any other refusal (an `exception`
field does not make one transient, the committed ok status does), a probe
answering something other than `1`, a non-timeout connection failure, or a
comment that did not post. One such observation is enough, which is why the
classification needs no more than the one flag that records it. The skip is not
cached: the verdict is the cluster's health, which no digest input captures, and
a cached success would turn one pressure spike into a permanent skip.

The readiness probe is classified the same way. It used to return a bare False
after printing `No connection to LogCluster` with neither status nor body, so a
run that failed there was red with nothing to attribute it to; it now prints
both, and a `>= 500` or a timeout there is transient like the read itself.

Requested in ClickHouse#115706 (comment) ,
ClickHouse#118708 (review)
and ClickHouse#118708 (comment) .
Supersedes ClickHouse#120121 , closed in
favour of this one.

Co-Authored-By: Claude Opus 5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Sep 19, 2026
The `ignore_range` mode of the fake endpoint - answering every request with `200 OK` and the
blob from byte 0, the way a proxy that does not understand ranges does - and the
`HTTP_RANGE_NOT_SATISFIABLE` and `LOGICAL_ERROR` error codes are left over from
#115706, where the check of the range an endpoint
returns lived in the same change as the premature end. No test here uses them.

That check is #120955, and it brings its own
range-ignoring endpoint in `src/Disks/tests/gtest_azure_read_buffer_range_check.cpp`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants