Skip to content

Fix CompressedReadBufferFromFile::seek taking a block left by readBig for the current position - #125446

Merged
Blargian merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/compressed-read-buffer-stale-block-seek
Nov 9, 2026
Merged

Blargian merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/compressed-read-buffer-stale-block-seek

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #118560

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 reading wrong data from a Compact part when a column whose substreams use different codecs (for example an Array column with CODEC(Delta, ZSTD)) is followed by a read that starts inside a shared compressed block: SELECT a, c.y could return the values of c.x, a mutation reading such a subcolumn could write them into the new part, and with compress_per_column_in_compact_parts = 0 mutations could fail with CANNOT_READ_ALL_DATA. Closes #118560.

Description

On 26.9.11.2 (also 26.3 and 26.8), with default settings, SELECT a, c.y from a Compact part of CREATE TABLE t (a Array(UInt32) CODEC(Delta, ZSTD), c Tuple(x UInt64, y UInt64)) ENGINE = MergeTree ORDER BY tuple() returns the values of c.x; on 26.8 and 26.9, with an extra column z UInt64, ALTER TABLE t UPDATE z = c.y + length(a) WHERE 1 writes them into the new part. With compress_per_column_in_compact_parts = 0 the same defect fails mutations with CANNOT_READ_ALL_DATA, as in CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=106734&sha=382decb770b0f39b864ac6a8248d66f80505d7c7&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

readBig decompresses a block that fits the caller's buffer straight into it, and it left the previous, exhausted block in working_buffer with size_compressed = 0. seek(P, S) treated "the buffer is not empty and offset() == S" as "already positioned", so when the stale block had exactly S bytes the seek was a no-op and the next read started at offset 0 of block P. In Compact parts the sizes of a get only ZSTD and are a separate block from its elements, and the substream mark of c.y points 8 bytes into the block of c.

readBig now accounts and resets the exhausted block before it reads the next one, so size_compressed = 0 always means an empty working_buffer. The header states this invariant and seek checks it with a chassert. Under the invariant the buffer arm of the seek shortcut is dead, so it is removed, also from CachedCompressedReadBuffer::seek, and both seeks use the same shortcut. A seek that used to return early takes the lazy-seek branch to the position the file buffer is already at; the block is decompressed once either way. The change is in the buffer, so every reader of it is covered, Wide parts included.

The new test fails on master (20/20 randomized runs) and passes with the change (30/30).


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

Version info

  • Merged into: 26.11.1.1769-master (included in 26.11 and later)

…BufferFromFile::seek`

`readBig` decompresses a block that fits the caller's buffer straight into it and sets
`size_compressed = 0`, leaving the previous, exhausted block in `working_buffer`. In that
state `seek(P, S)` treated "`working_buffer` is not empty and `offset() == S`" as "already
at the required position", so when `S` happened to equal the size of the stale block the
seek was a no-op and the next read started at offset 0 of block `P`.

In Compact parts the substreams of a column with a type-specific codec land in separate
blocks (the sizes of an `Array` with `CODEC(Delta, ZSTD)` get only `ZSTD`, the elements
`Delta, ZSTD`), and a following substream mark can point into a shared block at a non-zero
offset. With default settings `SELECT a, c.y` returned the values of `c.x`, and with
`compress_per_column_in_compact_parts = 0` mutations failed with `CANNOT_READ_ALL_DATA`
(ClickHouse#118560).

Without a block only the pending lazy offset (`nextimpl_working_buffer_offset`) says where
the next read starts, so the shortcut now checks only that. A seek that used to return
early now takes the lazy-seek branch to the position `file_in` is already at; the block is
decompressed once either way.

Closes ClickHouse#118560

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 rounds, 1 finding) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The mutation case used identity updates, so its final SELECT could not tell rewritten parts from skipped mutations AGREE, fixed @ ecef54b both mutations now change values; on master the SELECT row is the unmutated one and the first ALTER fails with Code: 33
2 💡 CachedCompressedReadBuffer::seek keeps the same condition noted unreachable there (no cell means an empty buffer, no readBig override); with use_uncompressed_cache = 1 master already returns the correct row

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7b4fafb]

Summary: ✅


AI Review

Summary

Reviewed #125446 at 7b4fafb8554d62390de16ea9e546f5bf613c105a. The change clears exhausted buffers before reading another compressed block, preventing stale offsets from corrupting subcolumn reads and mutations, and aligns the cached reader's seek shortcut. No actionable findings remain in the current code.

Missing context / blind spots
  • ⚠️ Latest-head CI is still running; remaining jobs must finish before merge. Regression evidence comes from the preceding merge commit: the new test passed 50 ASan/UBSan targeted repetitions and the debug lane. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 12, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Oct 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ecef54b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, targeted) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested not from this PR (it only changes CompressedReadBufferFromFile::seek and adds a stateless test): #117198 broke this test on master, where it failed on all 6 commits between that merge and its revert, and on 77 PRs. The tested tree predates the revert #125455 (external, merged)
Integration tests (amd_tsan, targeted) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested same cause as the row above #125455 (external, merged)
Integration tests (arm_binary, distributed plan, targeted) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested same cause as the row above #125455 (external, merged)
Integration tests (arm_binary, 1/4) / test_storage_delta/test.py::test_writes_timestamp_ntz_annotation_nested same cause as the row above #125455 (external, merged)
Integration tests (arm_binary, 1/4) / test_storage_delta/test_writes_interop.py::test_write_to_table_with_unsupported_writer_feature_is_rejected same cause as the row above #125455 (external, merged)
Mergeable Check, PR praktika rollups of the rows above #125455 (external, merged)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-003012

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai 🕵️ CachedCompressedReadBuffer::seek (lines 102-105) still has the same !buffer().empty() && offset() == offset_in_decompressed_block clause. I agree it can't be reached today: without owned_cell the buffer is empty, and the class has no readBig. Could you still drop it here too, so that the two seeks keep the same shortcut? As it stands the clause is dead code that would bring this bug back if someone later adds a readBig that decompresses into the caller's memory, the way the one in CompressedReadBufferFromFile does.

PedroTadim and others added 2 commits October 15, 2026 13:33
…eek`

Without `owned_cell` the working buffer of `CachedCompressedReadBuffer` is
always empty, so the `!buffer().empty() && offset() == ...` arm of its seek
shortcut is unreachable. Remove it anyway so that both compressed read
buffers use the same shortcut, and a future `readBig` that decompresses into
the caller's memory cannot bring back the no-op seek fixed in the previous
commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done in 69e1fb7: CachedCompressedReadBuffer::seek now uses the same shortcut as CompressedReadBufferFromFile::seek (nextimpl_working_buffer_offset only), and the description is updated. The uncompressed cache tests (02124_uncompressed_cache, 04489_compact_part_mixed_codec_uncompressed_cache, 05355_uncompressed_cache_read_past_read_range on an S3 disk) and 05366 pass 30/30 with randomized settings.

@PedroTadim PedroTadim self-assigned this Oct 15, 2026
@PedroTadim
PedroTadim enabled auto-merge October 15, 2026 15:05
@rienath
rienath disabled auto-merge October 15, 2026 15:29
@rienath rienath self-assigned this Oct 15, 2026
void CompressedReadBufferFromFile::seek(size_t offset_in_compressed_file, size_t offset_in_decompressed_block)
{
/// Nothing to do if we already at required position
/// Nothing to do if we already at required position.

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.

The fix is correct, but it leaves the stale block in working_buffer and relies on an unchecked property instead of removing it. Think about these three

  1. Reset the buffer in readBig where it zeroes size_compressed:
bytes += offset();
resetWorkingBuffer();
size_compressed = 0;

and drop the two later bytes += offset() lines. Then no stale block exists and seek is correct by construction.
2. Header invariant: size_compressed = 0 and working_buffer is empty.
3. At the top of seek: chassert(size_compressed || working_buffer.empty());, so a future path that zeroes size_compressed with bytes pending fails in debug builds instead of returning wrong data.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done in b58c6f8, all three points. One change from the suggestion: the reset runs just before readCompressedData instead of after it, because with CODEC(NONE) working_buffer points into compressed storage that the next read may reallocate. The buffer arm of the seek shortcut is dead under the invariant, so it stays removed. On a debug build the chassert held across about 500 related stateless tests.

@PedroTadim PedroTadim removed their assignment Oct 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7b4fafb85 with master e0ae5a4bb (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d2ac903cf; 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.

Compile time of recompiled translation units

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

Job report

Before `readBig` reads the next compressed block, which moves `file_in` past
the block held in `working_buffer`, account the bytes of that block and reset
the buffer where `size_compressed` is zeroed. State (a) of the class invariant
(`size_compressed == 0`) then always has an empty `working_buffer`, so no stale
block is left for `seek` to take for the current position. The two later
`bytes += offset()` become no-ops and are removed.

The reset runs before `readCompressedData`, not after it: with `CODEC(NONE)`
`working_buffer` points into the compressed storage, which the next read may
reallocate, so `offset()` must be taken first. This is also the order of
`ReadBuffer::next`.

Document the invariant in the header and check it at the top of `seek`, so a
future path that zeroes `size_compressed` with bytes pending fails in debug
builds instead of returning wrong data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b58c6f8

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05345_text_index_prewhere_read_step_order flaky, not from this PR (it only changes the compressed read buffers and adds a stateless test): the known read_order_index_first 0 -> 1 diff in the ParallelReplicas lane, 65 of 65 reruns passed; it failed on 68 PRs and on master in the last 30 days #125892 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125892 (mine, open)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261015-210016

@groeneai

Copy link
Copy Markdown
Collaborator Author

Another CI failure caused by this bug: 05241_vector_search_quantize_codec_read_task_subcolumn (Compact part section, wrong groupBitXor(cityHash64(id, vec.quantized))) in Stateless tests (arm_binary, parallel) of an unrelated PR. The server of that job got default_compression_codec = ZSTD(1) from install.sh, and the runner reduced the red to index_granularity = 7952 (102/102 red with the run's settings, 110/110 green without them).

With 7952 the last granule has 4096 rows, so its vec elements fill exactly one 1 MiB block and the vec.quantized mark is (block, 1048576). The reads of id and vec.size0 before it are decompressed straight into the columns, the seek takes the stale-block shortcut, and vec.quantized gets the float elements from offset 0. It is not arm-specific: on x86 I get the same wrong hash with ZSTD(1)/ZSTD(3) and the right one with LZ4.

A smaller case that needs only a ZSTD default codec: on 26.3.55.2-lts, id UInt32, t Tuple(a FixedString(128), b FixedString(128)), default_compression_codec = 'ZSTD(1)', default granularity, 24576 rows: reading id with t.b returns the values of t.a for all 8192 rows of the second granule.

Both are correct with b58c6f8 (checked with this PR's amd_release build).

@rienath rienath 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.

Is there a fix or issue open for that @groeneai?

@groeneai

Copy link
Copy Markdown
Collaborator Author

This PR is the fix. Both cases are the same stale-block seek and give the right result with b58c6f8. There is no separate issue: in CIDB this 05241 failure appears only in that PR 124808 run in the last 30 days, never on master.

@rienath rienath 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.

Merge master. The flakes were fixed

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master in 1c379a9 (no conflicts, the diff against master is unchanged). Today's master still reproduces the bug; the merged build returns the right values, and 05366 passes 30/30 with randomized settings.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1c379a9

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, sequential) / 05339_iceberg_top_k_query_condition_cache master breakage, not from this PR (it changes CompressedReadBufferFromFile and CachedCompressedReadBuffer only): the test failed on all 12 master commits from the #126987 merge 41d5f3406f9d until its revert, and the tested merge tree 253f2b58b3e2 contains #126987 but not the revert #127378 (external, merged revert)
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_asan_ubsan, azure, sequential, 2/2) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Stateless tests (arm_binary, s3 storage, DBReplicated, sequential) / 05339_iceberg_top_k_query_condition_cache same master breakage #127378 (external, merged revert)
Mergeable Check, PR praktika rollups of the rows above #127378 (the owner of the rows above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261022-150010

@PedroTadim

Copy link
Copy Markdown
Member

Sorry to break master, it's now fixed

@rienath
rienath added this pull request to the merge queue Nov 9, 2026
@Blargian
Blargian removed this pull request from the merge queue due to a manual request Nov 9, 2026
@Blargian
Blargian added this pull request to the merge queue Nov 9, 2026
Merged via the queue into ClickHouse:master with commit 840c468 Nov 9, 2026
180 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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.

Stale buffer after readBig turns CompressedReadBufferFromFile::seek into a no-op

5 participants