Skip to content

Fix short read of product-quantization codebook on wide parts - #110926

Merged
shankar-iyer merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pq-codebook-wide-read-108565
Jul 20, 2026
Merged

shankar-iyer merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-pq-codebook-wide-read-108565

Conversation

@groeneai

@groeneai groeneai commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

...

Description

Fixes a short read (Cannot read all data of type FixedString. Bytes read:49152. String size:65536) of the product-quantization codebook on wide parts, e.g. during two-stage vector search. The Quantized('product', ...) codec is a new experimental feature (behind allow_experimental_codecs) added this cycle in #108565 and not present in any released version, so this is Not for changelog rather than a stable-release bug fix. (The PR was initially filed as Bug Fix; the Bugfix Validation gate then required a regression test that fails on master HEAD without the fix, but the failure is scheduling/prefetch dependent under concurrency and does not reproduce deterministically from a single stateless query, so it cannot satisfy that gate. Recategorized because the fixed feature is unreleased.)

The product quantization codec stores one codebook value (a FixedString) per part, written once at the serialize suffix. SerializationProductQuantizationCodebook::deserializeBinaryBulkWithMultipleStreams reads that value at the codebook stream's current position, trusting the reader to have positioned it. On wide parts, MergeTreeReaderWide::readData's data getter seeks a substream to its own mark only when !was_prefetched && !continue_reading && !read_without_marks. During a multi-granule scan with prefetch (the pattern the two-stage vector search produces under ReadPoolInOrder), that seek is skipped, so the single-value codebook stream is left at the offset of a sibling subcolumn (the codes stream vec.quantized, whose granule-N decompressed offset is N * bytes_per_vector * granularity). The subsequent single-block read then returns fewer bytes than the codebook size, e.g. Bytes read:49152. String size:65536.

Compact parts are unaffected because their getter seeks unconditionally on every call.

Fix: the codebook read now explicitly seeks its stream to the current granule's mark (where the value always begins) via seek_stream_to_current_mark_callback, and that callback is wired into MergeTreeReaderWide::readData (it was previously wired only in MergeTreeReaderCompact). This mirrors how SerializationObjectSharedData positions its streams. The callback is inert for existing wide reads (SerializationObjectSharedData only consumes it on compact parts), and it is skipped in read_without_marks mode where the whole part is read from the start.

Verified with a deterministic mechanism check: injecting the stale offset reproduces the exact Bytes read:49152. String size:65536 without the fix and passes with it; 50 randomized-read runs on local disk and 50 runs on cached_s3 (the failing CI storage) all pass. The added codebook_prefetch test case is coverage that reads the codebook across granules under the CI-failing read settings; note the original failure is scheduling/prefetch dependent (CI's rerun diagnosis was 15/19) and does not reproduce deterministically from a single stateless query.

Found by the amd_tsan, s3 storage CI run of 02354_vector_search_quantize_codec_pq_multigranule (report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110606&sha=1b1d4141cc3db2906ec15f5c033603931f0a3e6b&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%203%2F3%29). The feature was added in #108565.

The `product` quantization codec stores one codebook value per part, read
once and broadcast to every granule. On wide parts the codebook stream was
read at its incidental position: MergeTreeReaderWide's data getter seeks a
substream to its own mark only when not prefetched and not continuing a read,
so under prefetch / continued reading the single-value codebook stream could
be left at a sibling subcolumn's offset and read short, e.g.
"Cannot read all data of type FixedString. Bytes read:49152. String size:65536".

Seek the codebook stream to the current granule's mark explicitly before
reading, and wire seek_stream_to_current_mark_callback into
MergeTreeReaderWide::readData (previously only wired in MergeTreeReaderCompact).
Compact parts were unaffected because their getter seeks unconditionally.

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Injecting the stale codebook-stream offset (compressed=0, decompressed=16384) reproduces the exact Bytes read:49152. String size:65536 on demand. The natural failure is scheduling/prefetch dependent (CI rerun diagnosis 15/19), so the deterministic proof uses this env-gated injection.
b Root cause explained? Yes. The per-part PQ codebook is one FixedString read once at the codebook stream's incidental position. MergeTreeReaderWide::readData's getter seeks a substream to its mark only when !was_prefetched && !continue_reading, so under prefetch/continued reading the codebook stream is left at a sibling subcolumn (codes) offset -> readBig on the single 65536-byte block returns 65536 - 16384 = 49152.
c Fix matches root cause? Yes. The read now explicitly seeks the codebook stream to its own current-granule mark via seek_stream_to_current_mark_callback before reading, instead of trusting the incidental position. Not a guard/retry.
d Test intent preserved / new tests added? Yes. Existing assertions unchanged; added a codebook_prefetch case reading the codebook across granules under the CI-failing read settings (coverage of the fixed path).
e Both directions demonstrated? Yes. With injection: fails (49152/65536) without the seek, passes with it. 50/50 randomized-read runs on local disk and 50/50 on cached_s3 (the failing CI storage) all pass.
f Fix is general across code paths? Yes. Compact parts already seek unconditionally on every getter call, so they were correct; wide was the only broken path. The wired callback is the designed-for primitive (used by SerializationObjectSharedData), not a point patch.
g Fix generalizes across inputs? Yes. The codebook is one fixed blob per part regardless of vector dimensions / m / bits / part size; the fix corrects stream positioning independent of those.
h Backward compatible? Yes. No format / protocol / setting / ABI change. Read-path stream-positioning fix only.
i Invariants and contracts preserved? Yes. Codebook still read once per part and broadcast via ColumnConst; the callback matches its existing (compact) semantics and is skipped in read_without_marks mode (whole-part-from-start, where seekToMark would throw). Verified whole-part read returns correct results with no LOGICAL_ERROR.

Session id: cron:clickhouse-author-slot-2:20260718-040555

@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; 3 distinct findings across 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ Supplied diff was empty, claims unreviewable AGREE — fixed Fix was uncommitted (HEAD==master) so the gate saw no diff; committed the 4 files and re-ran the review on the populated diff.
2 ❌ Callback seeks a mark even in read_without_marks mode AGREE — fixed @ 00e8eea read_without_marks uses a whole-part stream whose seekToMark throws LOGICAL_ERROR. Added if (read_without_marks) return; guard. Verified whole-part read returns correct results, no crash.
3 ⚠️ Regression test not shown to fail without the fix under its pinned settings AGREE (partial) Confirmed empirically: 0/30 runs of the committed test fail on the unpatched binary. The bug is scheduling/prefetch/page-cache dependent (CI rerun diagnosis 15/19) and is not single-query reproducible; a deterministic SQL test would require a test-only stream-position injection in production code, which is not acceptable. Kept codebook_prefetch as coverage; deterministic proof provided via env-gated injection (both directions). Stated in the PR body.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. The delta recheck re-raised finding 3 on the unchanged test hunk; auto-dropped per the delta rule.

Session id: cron:clickhouse-author-slot-2:20260718-040555

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @Avogar — could you review this? It fixes a Cannot read all data of type FixedString short read of the per-part product-quantization codebook on wide parts: MergeTreeReaderWide's data getter skips the per-substream mark seek under prefetch/continued reading, so the single-value codebook stream is left at a sibling (codes) offset. The read now explicitly seeks the codebook stream to its current-granule mark (wiring seek_stream_to_current_mark_callback into the wide reader, as compact already had).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [441a8e5]

Summary: ✅


AI Review

Summary

This PR fixes the wide-part read path for the experimental Quantized('product', ...) codec by explicitly seeking the per-part codebook substream to the current mark before the one-value codebook is deserialized, and it adds coverage for the prefetched multi-granule path. I did not find a remaining correctness, compatibility, or test-gap issue in the current diff.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 18, 2026
The Quantized('product', ...) codec fixed here is an experimental feature
(allow_experimental_codecs) added this cycle in ClickHouse#108565 and not present in
any released version, so this is not a stable-release bug fix. The Bugfix
Validation gate additionally requires a regression test that fails on master
HEAD without the fix, but the failure is scheduling/prefetch dependent under
concurrency and does not reproduce deterministically from a single stateless
query. Empty commit to re-run CI after the changelog category change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 18/21 (85.71%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 441a8e5

CI fully finished (Finish Workflow + Mergeable Check pass; 0 checks queued/in_progress; last real check completed ~35 min ago). No test failures in CIDB for this head. The prior Bugfix-validation red on 00e8eea9392a was PR-caused and is resolved on this head: the fixed Quantized('product', ...) codec is an unreleased same-cycle experimental feature (merged in #108565, 2026-07-16; absent from every release branch), so Bug Fix (...official stable release) was factually wrong. Recategorized to Not for changelog → pr-bugfix label removed → Bugfix Validation no longer runs → Mergeable Check green.

Check / test Reason Owner / fixing PR
Bugfix validation (functional tests, amd64 + aarch64) / 02354_vector_search_quantize_codec_pq_multigranule PR-caused (wrong changelog category for an unreleased experimental feature) PR-caused → fixed in this PR @ 441a8e5 (recategorized Not for changelog)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260719-013000

@shankar-iyer
shankar-iyer added this pull request to the merge queue Jul 20, 2026
Merged via the queue into ClickHouse:master with commit da4db42 Jul 20, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 20, 2026
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Aug 1, 2026
The `product` method of the `Quantized` codec stores one codebook value for the whole part. It is written
once, in `serializeBinaryBulkStateSuffix`, after the data of all granules, so every granule's mark in the
`product_quantization_codebook` stream points at its start and no mark delimits its end.

`MergeTreeReaderStreamSingleColumn::getRightOffset` assumed the opposite. For a read whose mark range ends
before the end of the part it bounds the read at the offset of the first following mark with a greater
compressed offset. For the codebook stream that mark is the part's final mark, which is written right after
the suffix - and with an adaptive write buffer (starting at `adaptive_write_buffer_initial_size`, 16 KiB, and
doubling) the codebook spans several compressed blocks, so the final mark points into the middle of it. For a
64 KiB codebook the marks look like this:

    mark 0..9  (0, 0)          <- the data granules
    mark 10    (49202, 16384)  <- the final mark, inside the codebook

so the read was cut at compressed offset 49202 and threw

    Cannot read all data of type FixedString. Bytes read:49152. String size:65536:
    (while reading column vec.product_quantization_codebook)

The bound is only enforced by read buffers that implement `setReadUntilPosition` - object storage, encrypted
or cached disks - which is why this only showed up on the s3 CI runs, and only with a write-side
`min_columns_to_activate_adaptive_write_buffer` small enough to activate the adaptive buffer.

The codebook stream holds exactly one value for the whole part, so it must be read as a whole file, like the
metadata streams of `Dynamic` and `JSON`. This also repairs reads of parts that are already written.

Closes: ClickHouse#112804
Related: ClickHouse#110926
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…debook-wide-read-108565

Fix short read of product-quantization codebook on wide parts
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 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.

4 participants