Skip to content

Fix LOGICAL_ERROR on premature S3 connection close through the filesystem cache - #108950

Closed
arsenmuk wants to merge 20 commits into
masterfrom
arsenmuk/core-incident-1894-unexpected-eof
Closed

arsenmuk wants to merge 20 commits into
masterfrom
arsenmuk/core-incident-1894-unexpected-eof

Conversation

@arsenmuk

@arsenmuk arsenmuk commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Description

When an S3 connection closes mid-read while the object still reports its full size, the read used to surface as a cache-layer LOGICAL_ERROR (Having zero bytes, but range is not finished) for what is really a transient I/O failure.

ReadBufferFromS3 now heals a premature stream close by reconnecting and resuming from the current offset instead of reporting a truncated EOF. The expected end of the read is taken from read_until_position when set and from the known object file_size otherwise, so both the filesystem-cache range-reader path and full-object reads (S3ObjectStorage::readObject, BackupWriterS3::readFile, which read with read_until_position == 0) are covered. It falls back to a regular retryable CANNOT_READ_ALL_DATA only when no progress can be made (an empty response for a non-finished range) and reports S3_OBJECT_CHANGED_DURING_READ if the object was overwritten during the read.

Includes failpoints and stateless tests (04417, 04506, 04507, 04509) that reproduce the premature-close, empty-response, changed-object, and full-object recovery paths.

Closes: #108948

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a LOGICAL_ERROR (Having zero bytes, but range is not finished) that could occur when an S3 connection was closed prematurely while reading (both through the filesystem cache and for full-object reads). ClickHouse now reconnects and resumes the read from the current offset, and reports a regular retryable read error only when no progress can be made or the object changed during the read.


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

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f8d558a]

Summary: ❌

job_name test_name status info comment
Build (amd_freebsd) FAIL
Build ClickHouse FAIL cidb
Build (wasm64) FAIL
Build ClickHouse FAIL cidb

AI Review

Summary

This PR teaches ReadBufferFromS3 to distinguish premature EOF from a clean end-of-object on full-object reads, propagates object size/ETag into backup / Keeper / MeCab callers, and tightens the filesystem-cache error classification around truncated S3 reads. I found one remaining compatibility regression: the new Keeper lock-file read forces ETag validation even when s3_validate_etag_on_read is globally disabled, so I would not merge as-is.

Missing context / blind spots
  • ⚠️ The historical Praktika report links currently available on the PR return expired/forbidden artifacts, so I could not re-check the old CI logs beyond the discussion history and the code/tests in this checkout.
Findings
  • ❌ Blocker [src/Coordination/KeeperSnapshotManagerS3.cpp:264] uploadSnapshotImpl now always passes lock_file_info.etag into ReadBufferFromS3. That unconditionally enables If-Match / response-ETag validation on the Keeper snapshot lock-file read, so deployments that globally restore the pre-26.7 behavior with s3_validate_etag_on_read = 0 (including through compatibility) will still start failing Keeper snapshot uploads on S3-compatible backends with unstable ETags. The setting no longer restores the previous behavior on this path, which is a backward-compatibility break.
    Suggested fix: read Context::getGlobalContextInstance()->getSettingsRef()[Setting::s3_validate_etag_on_read] here and pass lock_file_info.etag only when the setting is enabled, matching the other full-object S3 readers updated in this PR.
Final Verdict

Status: ❌ Block
Minimum required action: gate the Keeper lock-file expected_etag on s3_validate_etag_on_read, or add an explicit Keeper-specific setting if the stricter behavior is intentional.

LLVM Coverage Report

Measured on commit f8d558a.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 155/214 (72.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 30, 2026
@kssenii kssenii self-assigned this Jun 30, 2026
@arsenmuk
arsenmuk marked this pull request as draft July 1, 2026 12:50
@arsenmuk
arsenmuk force-pushed the arsenmuk/core-incident-1894-unexpected-eof branch from 87bbb0a to f0b6806 Compare July 6, 2026 11:52
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

alexey-milovidov and others added 2 commits July 14, 2026 11:39
…ion = 0)

The premature-EOF recovery added for the filesystem-cache range-reader path only
triggered when `read_until_position` was set. Callers such as
`S3ObjectStorage::readObject` and `BackupWriterS3::readFile` read a whole object
with `read_until_position == 0` but a known `file_size`, so a connection that
closed mid-stream still fell through to a clean EOF and could silently truncate a
full-object read.

Derive an `expected_read_end` bound from `read_until_position` first and
`file_size` second, and use it in both premature-EOF checks in
`ReadBufferFromS3::nextImpl` (the reconnect-and-resume path and the
`CANNOT_READ_ALL_DATA` fail-loud path) and in the `s3_read_buffer_force_premature_eof`
failpoint so the recovery covers full-object reads too.

Adds `04509_s3_full_object_premature_eof`, which reads a whole object through
`ReadBufferFromS3` without the filesystem cache and proves the read is healed
transparently using `file_size` as the expected upper bound.

Addresses the AI review blocker on #108950

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
…ent-1894-unexpected-eof

# Conflicts:
#	src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp
…EOF detection

Address review (clickhouse-gh AI review blocker): the full-object premature-EOF
recovery in `ReadBufferFromS3::nextImpl` only covers callers that pass a
`file_size`. `BackupReaderS3::readFile` constructed `ReadBufferFromS3` without a
size, and `BackupImpl::readBackupMetadata` consumes the `.backup` object with
`readStringUntilEOF`, which never queries the size. A mid-stream S3 close would
therefore return a clean EOF and silently truncate the backup metadata (or a data
file) instead of resuming or failing loudly, so `RESTORE` could read a corrupt
backup.

Fetch the object size via `getFileSize` and thread it into `ReadBufferFromS3`,
mirroring `BackupWriterS3::readFile`. Now `expected_read_end` is known for backup
reads and a premature close is healed by reconnect-and-resume, or surfaced as
`CANNOT_READ_ALL_DATA` / `S3_OBJECT_CHANGED_DURING_READ`.

Add `04616_s3_backup_read_premature_eof`, which backs up a table to S3, enables the
`s3_read_buffer_force_premature_eof` failpoint, and verifies `RESTORE` round-trips
the data intact while the premature-EOF recovery path fires.
Comment thread src/Backups/BackupIO_S3.cpp Resolved
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
…OF path

Three changes:

1. `CachedOnDiskReadBufferFromFile`: keep master's classification of a
   remote object truncated between listing and reading as
   `CANNOT_READ_ALL_DATA` as a special case, checked before the broader
   size-mismatch check this pull request added. The previous merge
   resolution turned that case into `S3_OBJECT_CHANGED_DURING_READ`, which
   broke `FileCacheTest.CachedReadBufferTruncatedObject` and
   `FileCacheTest.CachedReadBufferTruncatedObjectReadBigAt`. Now the
   stream ending exactly at the current (smaller) object size is reported
   as a truncation, any other size change as
   `S3_OBJECT_CHANGED_DURING_READ`, and an unchanged size as a premature
   connection close - in both the plain-read and the predownload paths.

2. `BackupReaderS3::readFile`: fetch `getObjectInfo` and thread both the
   size and the ETag into `ReadBufferFromS3`. `ReadBufferFromS3` only
   sends `If-Match` and validates the response ETag when `expected_etag`
   is set, so for a non-versioned bucket an in-place overwrite to exactly
   the same size would otherwise pass the size check and `RESTORE` could
   stitch together bytes from two object generations. Addresses the AI
   review blocker.

3. `BackupWriterS3::copyFile`: pass the known `size` into the
   direct-buffer fallback reader. `createS3UploadBody` reads exactly that
   many bytes with `readStrict`, so a mid-stream S3 close in the fallback
   path is now reconnected and resumed instead of failing the `BACKUP`.
   Addresses the AI review major.

Also stop `04616_s3_backup_read_premature_eof` from failing on the
`BackupsWorker` warning about `s3_disable_checksum` halving the effective
`max_backup_bandwidth`, which the stateless CI config triggers: the
warning landed on stderr and failed the test even though its stdout was
correct. The `BACKUP` query now sets `s3_disable_checksum = 1`.
Comment thread src/Backups/BackupIO_S3.cpp Resolved
Comment thread src/Backups/BackupIO_S3.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 113/167 (67.66%) · Uncovered code

Full report · Diff report

alexey-milovidov and others added 2 commits August 6, 2026 14:18
…opyFile fallback source

Address AI review: `BackupReaderS3::readFile` passed `expected_etag`
unconditionally, making `s3_validate_etag_on_read = 0` ineffective for
`RESTORE` and breaking backends with unstable ETags. Snapshot the setting
in both `BackupReaderS3` and `BackupWriterS3` and pass the ETag only when
it is enabled.

Also close the same-size overwrite hole in the `BackupWriterS3::copyFile`
direct-buffer fallback: now that the reader resumes after a premature EOF,
pin the source object generation with its ETag (gated on the same setting),
so a source rewritten in place between the original and the resumed GET
fails with `S3_OBJECT_CHANGED_DURING_READ` instead of producing a torn
backup copy.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f8d558a47 with master 7dead7203 (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

11 object files changed (+61.50 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/IO/CachedOnDiskReadBufferFromFile.cpp.o 466.91 KiB 495.62 KiB +28.71 KiB (+6.15%)
src/CMakeFiles/clickhouse_common_io.dir/IO/ReadBufferFromS3.cpp.o 300.25 KiB 319.02 KiB +18.77 KiB (+6.25%)

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

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

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

Job report

…ding the MeCab dictionary from S3

`loadJapaneseDictionary` uses the global context, so `openS3Source` read
`s3_validate_etag_on_read` from the server default profile and
`SELECT tokens(...) SETTINGS s3_validate_etag_on_read = 0` could not turn the
ETag pinning off for the first dictionary download. Take the flag from
`CurrentThread::tryGetQueryContext` when a query context is available and fall
back to the global settings otherwise.

Added an integration test that enables the `s3_read_inject_etag_mismatch`
failpoint and checks both directions on a fresh instance.
The AI review pointed out that `test_truncated_object_predownload_no_logical_error`
accepted a successful query, which is exactly the pre-fix fabricated-EOF failure
mode in release builds (the cache returns garbage successfully). The query now
must raise, and the raised error is checked to not be one of the forbidden
LOGICAL_ERROR messages.
Comment thread src/IO/ReadBufferFromS3.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 4, 2026
… lock verification

`KeeperSnapshotManagerS3::uploadSnapshotImpl` reads back the `.lock` object it
has just written with `readStringUntilEOF` over a bare `ReadBufferFromS3`. With
neither `read_until_position` nor `file_size` set, the reader had no expected
end, so an S3 connection closed mid-stream looked like a clean EOF: the leader
saw a short UUID, logged `Failed to create a lock file` and skipped the snapshot
upload even though the lock object was intact.

Fetch the lock object's info once with `S3::getObjectInfo` and pass both `size`
and `etag` to `ReadBufferFromS3`, the same way the backup and MeCab full-object
callers already do. The known end turns a premature close into a transparent
reconnect-and-resume (or a loud `CANNOT_READ_ALL_DATA` when no progress is
possible), and the pinned `ETag` reports a concurrent leader overwriting the
lock file between the two requests instead of stitching two object generations.
lock_file_info.size,
ReadBufferFromS3::S3CredentialsRefreshCallback{[] { return nullptr; }},
/* blob_storage_log_= */ BlobStorageLogWriterPtr{},
/* expected_etag_= */ lock_file_info.etag

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 is a compatibility regression: ReadBufferFromS3 treats any non-empty expected_etag as an unconditional If-Match / response-ETag check, so this lock-file verification now ignores s3_validate_etag_on_read. Deployments that globally restore the pre-26.7 behavior (s3_validate_etag_on_read = 0, including via compatibility) will still start failing Keeper snapshot uploads on S3-compatible backends with unstable ETags, and there is no setting left to opt out on this path.

Can we read Context::getGlobalContextInstance()->getSettingsRef()[Setting::s3_validate_etag_on_read] here and pass lock_file_info.etag only when it is enabled, consistent with BackupReaderS3 and openS3Source?

@arsenmuk arsenmuk closed this Sep 23, 2026
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-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[LOGICAL_ERROR] "Having zero bytes, but range is not finished" on premature S3 connection close through the filesystem cache

3 participants