Repository navigation
Vector search rescoring with fixed-width point read - #111180
shankar-iyer wants to merge 31 commits into
Conversation
For a dense-vector column carrying a `Quantized(...)` codec (a fixed-length `Array(Float32/BFloat16)`), set the table's `max_compress_block_size` and `min_compress_block_size` to `dimensions * sizeof(element)` at CREATE time, i.e. one vector per compressed block. Because the base vector is stored uncompressed and fixed-stride, this makes each row occupy a whole compressed block at a constant on-disk stride (`16 + 9 + row_size`), which is the precondition for the upcoming single-block point-read rescore in the two-phase quantized-codes vector search (avoids decompressing a full granule to fetch one vector). Derived deterministically from the column and re-applied on every load; only applies when the user has not set the block size explicitly, and is skipped when two vector columns have conflicting row sizes (a single table-level block size cannot align both). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extend the lazy-materialization path with a point-read fast path for the two-phase quantized-codes vector search rescore. When the (single) lazy column is a fixed-size `Array(Float32/BFloat16)` carrying a `Quantized(...)` codec and every part stores it one-vector-per-block (element `.bin` size == rows * (25 + row_size), the layout guaranteed by the CREATE-time block-size alignment), `LazyReadFromMergeTreeSource::buildReaders` builds a `MergeTreePointReadSource` per part instead of the granule-scanning `MergeTreeSelectProcessor`. The source seeks directly to each shortlisted row's single compressed block at `row * (25 + row_size)` (framing = 16-byte checksum + 9-byte header), reads and checksum-verifies just that block, and appends the vector to the output column. File access goes through `IDataPartStorage::readFile`, so it works for both local and object storage (SharedMergeTree) - a local positioned read or an S3 byte-range GET. This turns a rescore that read ~one whole granule (~thousands of rows) per shortlisted vector into a single-vector read. Eligibility is decided per batch from the on-disk layout (no write-path flag); if any part is not one-vector-per-block, it falls back to the existing granule read. Reads are sequential for now (parallelism is a later change). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Drop the intermediate per-row buffer in MergeTreePointReadSource::generate: extend the nested column by `dimensions` elements and readStrict the one-row block directly into that storage, instead of reading into a scratch buffer and then memcpy-ing into the ColumnArray. Removes one of the two per-vector copies (the block is still copied once out of the checksummed CompressedReadBuffer). Behaviour is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Replace the table-level block-size alignment with a per-column one. Instead of setting the table's `max_compress_block_size`/`min_compress_block_size` (which shrank the compressed blocks of every column - hurting compression and adding framing overhead on id/codes/other columns), set a per-column `max_compress_block_size = dimensions * sizeof(element)` on the vector column carrying the `Quantized(...)` codec only. The Wide part writer already honors a per-column `max_compress_block_size` (MergeTreeDataPartWriterWide::addStreams), so only that column is written one-vector-per-block; all other columns keep the default block size. Skipped if the user already set a per-column override. This keeps the single-block point-read rescore (see MergeTreePointReadSource) while removing the collateral damage to the rest of the table. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Previously the point-read fast path only engaged when the vector column was the sole lazily-materialized column (buildReaders gated on lazy_header.columns()==1), so a common query like `SELECT id, payload ... ORDER BY cosineDistance(vec, ref) LIMIT k` - where payload columns are also lazily materialized - fell back to the whole-granule read (measured ~14x more I/O). Now MergeTreePointReadSource handles the full lazy header in one pass: it point-reads the fixed-size Quantized vector column and reads the remaining lazy columns with a standard MergeTreeReaderWide (per-offset readRows), assembling both into one chunk in header order. Keeping it in a single source avoids chunk/row alignment issues between two readers. Only the heavy vector column is point-read; the other (possibly variable-width) columns pay the usual granule read, which is unavoidable for them. buildReaders now looks for an eligible vector column anywhere in the lazy header (not only when it is the single column) and passes the rest as other_columns. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [b417c52] Summary: ❌
AI ReviewSummaryThis PR adds a point-read fast path for lazy rescoring of Findings
Final VerdictNot ready to merge: the remaining remote/object-storage range issue still undermines the core performance claim of the optimization. LLVM Coverage ReportMeasured on commit b417c52.
Changed lines: Changed C/C++ lines covered: 249/261 (95.40%) · Uncovered code |
The `std::move(vector_col)` inside the header-order assembly loop tripped `bugprone-use-after-move`, since clang-tidy cannot prove the moving `push_back` runs at most once across iterations. Move the column into a `ColumnPtr` once before the loop and push copies of the shared pointer (a cheap refcount bump) instead. Behavior is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…column normalization
Address the PR review comments and the 02354_vector_search_quantize_codec_pq_multigranule
CI failure (amd_tsan/s3, amd_llvm_coverage).
1. Elements-only block alignment (fixes the pq_multigranule failure, keeps PQ point-readable).
The per-column `max_compress_block_size` auto-injection applied to the whole vector column,
so for a `Quantized('product', ...)` column it re-blocked the single-value
`product_quantization_codebook` (65536 bytes) into many tiny blocks, breaking its read
("Cannot read all data of type FixedString. Bytes read:65280. String size:65536", on s3).
Moved the alignment into `MergeTreeDataPartWriterWide::addStreams` and applied it to ONLY the
`ArrayElements` substream (the full-precision vectors that are point-read); offsets, the
`.quantized` codes and the PQ codebook keep the default block size. Reverted the per-column
setting injection in registerStorageMergeTree. The full-precision Array elements of every
`Quantized(...)` column - including `product` - are still one-vector-per-block, so PQ is a
point-read target too.
2. Fall back for parts with pending conversions (review comment: stale rescore values).
MergeTreePointReadSource reads the base `.bin` directly and bypasses `MergeTreeReadTask`'s
on-the-fly mutations / patch parts / lightweight deletes / renames. buildReaders now falls
back to the granule read for any part that has such conversions, so those are never bypassed.
3. Post-read normalization for the other lazy columns (review comment: missing defaults/offsets).
readOtherColumns now runs fillMissingColumns / evaluateMissingDefaults / performRequiredConversions
after readRows, so ALTER-added columns and partially read Array/Nested payloads are normalized
exactly like the standard read path.
4. Honor a min-only opt-out: skip the auto-alignment when the column sets either
`min_compress_block_size` or `max_compress_block_size` explicitly.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
The point-read rescore for `Quantized`-codec vector search requires the
full-precision `Array` elements to be stored one vector per compressed block.
Previously `MergeTreeDataPartWriterWide` derived this block size automatically
(setting `max_compress_block_size` to the vector's byte size), which was
invisible in `SHOW CREATE TABLE` and drew review push-back for silently
overriding a documented column setting. It also left a latent bug: a
user-supplied per-column `max_compress_block_size` on a `Quantized('product', ...)`
column re-blocked the single-value PQ codebook and broke its read.
Make the alignment explicit and opt-in instead:
- Remove the auto-derivation. The user sets `max_compress_block_size` on the
vector column to exactly one vector's size (`dimensions * sizeof(element)`),
which now shows up in `SHOW CREATE TABLE`.
- For a `Quantized(...)` column, apply that per-column setting to the
`ArrayElements` substream only; the companion `.quantized` codes and the
per-part `product_quantization_codebook` keep the default block size (the
single-value codebook must stay in one block). Non-quantized columns keep the
standard behaviour of applying the setting to every substream. This also fixes
the codebook re-blocking bug for a manually configured `product` column.
- Drop the now-unused `DataTypes/DataTypeArray.h` include.
Document the setting (with the exact byte sizes and caveats) in the vector
search docs, and add a stateless test that checks the block-aligned
(point-read) path returns the same results as the unaligned (granule-read) path
for the `int8` and `product` codecs over `Array(Float32)` and `Array(BFloat16)`,
including a regression guard that the PQ codebook stays intact.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two findings from the review of ClickHouse#111180: 1. `MergeTreePointReadSource::readOtherColumns` called `MergeTreeReaderWide::readRows` once per shortlisted row with `continue_reading = false`, so every candidate seeked back to its granule's mark and skipped forward to its row again. `readRows` also clears its substream caches at the end of each call. When a granule spans several compressed blocks, each candidate therefore re-decompressed everything between the mark and its own row - quadratic in the number of candidates per granule, and far more expensive than the granule read this source replaces. The row offsets are ascending, so candidates from one granule arrive consecutively: keep the streams where the previous call left them and skip the rows in between via `rows_offset`. Every granule is now decompressed at most once. Measured on a single 8192-row granule of ~2 KB strings with all of its rows shortlisted (`Quantized('int8', 64)` vector column, `SELECT id, payload ... ORDER BY L2Distance(vec, ref)`): decompressed bytes 36,995,676,588 -> 20,965,804, bytes read from disk 276 MB -> 4.9 MB, query time 7.49 s -> 0.199 s. Results are unchanged - this was purely a performance defect. 2. `LazyReadFromMergeTreeSource::buildReaders` picked the first `Quantized(...)` column in the lazy header as the point-read target, with nothing tying it to the column the search actually ranks by. With two quantized vector columns lazily materialized it could point-read the payload one and leave the rescored one on the whole-granule read. The step has no access to the search column, so the fast path is now declined unless the lazy header holds exactly one quantized vector column. New test `04648_vector_search_quantize_codec_point_read_multi_column` covers the multi-column lazy read: the payload of every rescored row must belong to that row (a skip-accounting error shifts it), for a shortlist inside one small granule, for a granule spanning many compressed blocks, and for a lazy header holding two quantized vector columns. Without the first fix that test takes 13.4 s instead of 0.47 s. Also fixed the `aligned == unaligned` comparisons in `02354_vector_search_quantize_codec_point_read`: they sorted by `L2Distance(vec, ref), id`, and the two-stage rewrite only engages when `ORDER BY` holds the distance alone, so both sides ran an exact full-precision scan and the assertions could not fail. They now sort by the distance only and compare order-independently. Co-Authored-By: Claude Opus 5 <[email protected]>
All vector search tests share the `02354_vector_search` prefix, so rename `04648_vector_search_quantize_codec_point_read_multi_column` to `02354_vector_search_quantize_codec_point_read_multi_column`. It sits next to the `02354_vector_search_quantize_codec_point_read` test it extends, and the number it was given by `add-test` no longer collides with an unrelated test on another branch. Co-Authored-By: Claude Opus 5 <[email protected]>
…isting exclusions Follow-up to the review of ClickHouse#111180, which found two more ways for the point read to return data the ordinary read path would not. `MergeTreePointReadSource` addresses a part's base `.bin` files directly and builds its secondary reader without alter conversions, so it applies none of the read-time machinery that `MergeTreeReadTask` provides and cannot synthesize a column the part does not store. The eligibility check answered that by naming the conversions to refuse - data mutations, patches, lightweight deletes, renames - which admits by default every kind not on the list: * A pending `DROP COLUMN` is metadata-only and populates only `AlterConversions::dropped_columns`, leaving `mutation_commands` empty, so it passed the check. After `DROP COLUMN payload` followed by `ADD COLUMN payload String DEFAULT 'NEW'`, a block-aligned table returned the pre-drop values for all 50 rescored rows where the same table without alignment returned the defaults. * A column added by a later `ALTER` is absent from older parts. When it is the only lazy column besides the vector one, nothing carries the row count into the default evaluation and the query failed with `EMPTY_LIST_OF_COLUMNS_PASSED`, again where the granule read returned the defaults. Invert the check: serve a part from the point read only when it needs no conversion at all (`AlterConversions::hasAnyConversions`, added here) and stores every lazy column (`hasColumnFiles`). Kinds of conversion added later are then excluded until someone deliberately allows them, rather than silently taking the fast path. This costs nothing in practice - the optimization targets large, freshly written vector tables, which carry no pending conversions. `evaluateMissingDefaults` is now also given a row-count carrier, as `MergeTreeReadersChain::executeActionsBeforePrewhere` does, so the normalization matches the standard path even though the eligibility rule above keeps missing columns off this path. The point-read block is moved out of `LazyReadFromMergeTreeSource::buildReaders` into `tryBuildPointReadSources`, with the column choice and the per-part rule as `findPointReadVectorColumn` and `canPointReadPart`. Both scenarios are added to `02354_vector_search_quantize_codec_point_read_multi_column`. Verified that the fast path still engages on ordinary tables and declines on these two. Co-Authored-By: Claude Opus 5 <[email protected]>
…d-width-point-read
The point read copies the stored bytes of the vector column straight into `ColumnVector`, bypassing `SerializationNumber`, which converts numeric substreams from their little-endian on-disk form on big-endian targets. The write path performs that conversion, so on a big-endian host the rescored vector would be byte-swapped and the nearest-neighbour results wrong. Make `MergeTreePointReadSource::isEligible` return false there, so those hosts keep using the ordinary granule reader. Co-Authored-By: Claude Opus 5 <[email protected]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 186/194 (95.88%) · Uncovered code |
`master` moved the documentation from the Docusaurus tree under `docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every file this branch edits. The edits are replayed at the new paths: - `docs/en/engines/table-engines/mergetree-family/annindexes.md` -> `docs/reference/engines/table-engines/mergetree-family/annindexes.mdx`
`IMergeTreeReader::readRows` lost two parameters on master:
`current_task_last_mark` (in `Remove current_task_last_mark from MergeTree
readers`) and `rows_offset` (in `Remove rows_offset from the deserialization
API`, which dropped the skip machinery from the serializations on the grounds
that `rows_offset` is always zero for every caller). This branch was the one
caller that passed it non-zero, so the merge broke the build:
MergeTreePointReadSource.cpp:219:38: error: too many arguments to function
call, expected 4, have 6
`readOtherColumns` used `rows_offset` to step over the rows between two
survivors of the same granule without re-seeking, so that a granule is
decompressed at most once no matter how many of its rows survive. Keep that
property by skipping the same way `MergeTreeRangeReader::DelayedStream::finalize`
already does it - read the rows in between into throwaway columns and drop
them. They are decompressed either way; only the copy into the columns is
wasted, and it is bounded by the granule.
`readRows` now also takes `MutableColumns`, while `fillMissingColumns`,
`evaluateMissingDefaults` and `performRequiredConversions` still take
`Columns`, so the read accumulates into a `MutableColumns` that is moved into
the result before the normalization step.
The two tests also needed the gate renamed: master replaced
`allow_experimental_codecs` (now obsolete and a no-op) with the per-codec
`enable_quantized_codec` in `Add a setting to enable each experimental codec
individually`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
Every comment this branch adds is now at most two lines. No code changes. Also drops the claim that the per-part PQ codebook must stay in a single compressed block: master `00e8eea9392` fixed the short read at the source, and a codebook larger than the default `max_compress_block_size` reads correctly across blocks. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
One part that cannot be point-read - a Compact part from a recent insert, a pending mutation, an unaligned layout - no longer disables the fast path for every other part. Sources are keyed by the part's global row offset so the point-read and granule ones stay interleaved in the order the consumer expects. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The one-value-per-block layout moves into `FixedWidthPointReadLayout`, so the eligibility check and the addressing derive the stride from the same place and cannot drift apart. The hand-rolled `CompressedReadBufferFromFile` gives way to `MergeTreeReaderStreamSingleColumnWholePart`, which seeks by absolute file offset and brings the point read back onto the standard stream machinery. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The source reported `chunk.bytes()` through `ISource`'s auto-progress, which misses the rows read and dropped to reach a mid-granule row and the larger ranges a remote reader fetches. Both readers now feed a profile callback and `generate` reports what was actually read, as `MergeTreeSource` does. Since this path never reaches `MergeTreeReadTask`, the runtime-statistics sample is marked unsupported rather than cached short of the rescoring read. `pq_aligned_eq_unaligned` compared two approximate searches below full recall, where both sides miss true neighbours and match only by luck, so any shift of shortlist membership at the cut flipped it. The multiplier now keeps the shortlist above full recall. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`canPointReadPart` refuses a part that does not store every lazy column, so a column added later is synthesized by the granule read with `vec` in hand. That guard was untested: the existing case uses a constant default. Removing the guard turns both new assertions from 50 to 0. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`readOtherColumns` reads and discards rows to reach a mid-granule survivor, so reporting `batch` under-enforced `max_rows_to_read` and under-charged the `READ_ROWS` quota. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
No functional change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
| ::: | ||
|
|
||
| ```sql | ||
| CREATE TABLE vectors |
There was a problem hiding this comment.
Before I review the PR in detail some questions:
max_compress_block_size applies to column vec. It is compressed by codec Quantized that has two streams - the original values and the quantized values. If the block size is a single vector, does quantization still work? I mean it only sees a single vector at a time but for example for product quantization, we need to train the cookbook ... and that requires many more vectors.
If we do set max_compress_block_size to one vector in CREATE TABLE, it will be smaller than the granule size (4096 rows), an unusual situation. Can that have any side effects?
Is decreasing the granule size a viable alternative to "mini block"?
How much does rescoring cost in the grand scheme of things?
Would a query-plan-level optimization (like we did for HNSW #105591) be an alternative?
There was a problem hiding this comment.
Decreasing granule size will impact all columns and primary key memory will increase. But read amplification does not go away with that. Instead of 6000 rows, maybe we will still read 2048 rows. If we go down to a granularity like 64 or 256, overall read performance of the 1st pass suffers.
How much does rescoring cost in the grand scheme of things?
Huge. This is from one of the runs -
At nprobe=256, k=100, mult=20, the rescore with BFloat16 currently reads 921 MiB to fetch 2,000 vectors whose actual payload is 3 MiB — about 300× amplification, and 51% of total query bytes.
If we do set max_compress_block_size to one vector in CREATE TABLE, it will be smaller than the granule size (4096 rows), an unusual situation. Can that have any side effects?
With this PR, each vector is a block of its own and will get a header + checksum. So that is a minor storage overhead of ~1% of 768-D vector and much less for higher dim vectors.
max_compress_block_size applies to column vec. It is compressed by codec Quantized that has two streams - the original values and the quantized values. If the block size is a single vector, does quantization still work? I mean it only sees a single vector at a time but for example for product quantization, we need to train the cookbook ... and that requires many more vectors.
Good point. But PQ training happens at granule serialization (serializeBinaryBulkWithMultipleStreams) where we have full granule of rows, so PQ is not impacted by this PR
I am opening a simpler, handwritten PR : #123300
The rescore phase of a two-phase quantized vector search reads the full-precision vector of every shortlisted candidate, but it reads and decompresses a whole granule per candidate and could throw almost all of those bytes away.
When the vector column's
max_compress_block_sizeis set to exactly one vector's byte size (dimensions * sizeof(element)), each vector occupies its own compressed block, and the newMergeTreePointReadSourcefetches each candidate with a single-block point read - roughly an order of magnitude less logical I/O in the rescore phase. The optimization is an opt-in per-column setting and falls back to the ordinary granule reader whenever any touched part is not laid out this way.Note : Storage read (Disk or S3) would still use the optimal and appropriate chunk/block size. This PR is to minimize the memcpy's/deserialize.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up rescoring for
Quantized(...)vector search: setting the vector column'smax_compress_block_sizeto one vector's byte size (dimensions * sizeof(element)) stores one vector per compressed block, so each candidate is rescored with a single-block point read instead of reading and decompressing a whole granule.Workflow [PR]
Sync PR [sync-upstream/pr/111180]