Repository navigation
Read vectors from part when loading usearch index - #101843
shankar-iyer wants to merge 23 commits into
Conversation
|
Workflow [PR], commit [125aec9] Summary: ❌
AI ReviewSummaryThis PR switches Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block |
| /// is (at least in theory) agnostic of specific vector search libraries, and 2. additional data (e.g. the number of dimensions) | ||
| /// outside USearch exists which we should version separately. | ||
| static constexpr UInt64 FILE_FORMAT_VERSION = 1; | ||
| /// |
There was a problem hiding this comment.
Thinking about this ... it's all about the trade-offs. I like to understand the trade-offs better.
- Obviously, the total disk space consumption is lower.
- Also, the time needed to deserialize a usearch index is lower (because: less data)
- A nice side effect of the new code is that the pressure on the cache for deserialized vector index granules lowers. The presence and necessity of this cache is an anomaly and not recommended.
- I'm not so sure about DRAM consumption - it's probably bigger than before since the original vectors are not quantized.
- I'm also not sure about the the performance. It theoretically slows down but by how much?
Depending on the actual trade-offs, I thought maybe it's nice to give the user a choice between both internal representations. We have this syntax to create a vector similarity index today:
CREATE TABLE table
(
[...],
vectors Array(Float*),
INDEX index_name vectors TYPE vector_similarity('hnsw', <distance_function>, <dimensions>[, <quantization>, <hnsw_max_connections_per_layer>, <hnsw_candidate_list_size_for_construction>]) [GRANULARITY N]
)
ENGINE = MergeTree
ORDER BY [...]It would be weird to squeeze in another index parameter (this could be done only at the end of the parameter list). Instead, we could have a new index type:
CREATE TABLE table
(
[...],
vectors Array(Float*),
INDEX index_name vectors TYPE vector_similarity('hnsw_v2', <distance_function>, <dimensions>[, <hnsw_max_connections_per_layer>, <hnsw_candidate_list_size_for_construction>]) [GRANULARITY N]
)
ENGINE = MergeTree
ORDER BY [...]hnsw_v2 (for the lack of a better term). Also note how the parameter quantization is gone.
There was a problem hiding this comment.
Thinking about this ... it's all about the trade-offs. I like to understand the trade-offs better.
- Obviously, the total disk space consumption is lower.
- Yes, static disk space consumption is lower. Writes to disk eliminated when intermediate
partsmerge and vector indexes are persisted. The effect will be seen in bigger parts - a write of 50GB+ of vectors could take more than a couple of minutes after the index is built in memory.
- Also, the time needed to deserialize a usearch index is lower (because: less data)
- We will still have to read the vectors from the
part. Time needed to deserialize will not improve and may degrade a bit if the base table hasFloat32vectors and the index isbf16quantized. But if the index isbinaryquantized, then it is better to just persist the quantized vectors inusearchindex itself and read them from there. This PR is good only for when vector column datatype isFloat32orBFloat16andusearchdatatype isf32orbf16.
- A nice side effect of the new code is that the pressure on the cache for deserialized vector index granules lowers. The presence and necessity of this cache is an anomaly and not recommended.
- That does not change with this PR. The vector index with the vectors and graph will still consume same memory in the vector similarity index cache.
- I'm not so sure about DRAM consumption - it's probably bigger than before since the original vectors are not quantized.
- Memory consumption remains the same. The
set_vector_at_positioncall will quantize if needed and stash the vector
- I'm also not sure about the the performance. It theoretically slows down but by how much?
The additional overheads are : 1) If the table has Float32 vectors and usearch index is bf16 quantized, then currently reading from the usearch index is better. We will have to read more from the table part 2) There is negligible CPU usage for re-quantizing at index load time.
But at a high level - vector index is the first heavy weight index in ClickHouse. To store 2 copies of the vectors stands out - there is already write amplification when 2 large parts merge and their vectors are re-written in the new part and then we write the same vectors into the index. I will check the syntax thing and respond in the next message.
There was a problem hiding this comment.
hnsw_v2(for the lack of a better term). Also note how the parameterquantizationis gone.
Did you mean hnsw_v2 is only for a table with column of BFloat16 datatype for storing original vectors and it implies bf16 inside usearch index?
There was a problem hiding this comment.
Thanks for the clarification.
These are all possible combinations:
| Table | Index | Comment |
|---|---|---|
| f64 | f64 | Unlikely. Double-precision vectors are rare in practice. Can ignore. |
| f64 | f32 | Same as ^^ |
| f64 | bf16 | Same as ^^ |
| f64 | i8 | Same as ^^ |
| f64 | b1 | Same as ^^ |
| f32 | f32 | No surprise for users, all good ✅ . |
| f32 | bf16 | set_vector_at_position will do a downsampling. (**) |
| f32 | i8 | set_vector_at_position will do a downsampling (*) (**) |
| f32 | b1 | set_vector_at_position will do a downsampling (**) |
| bf16 | bf16 | No surprise for users, all good ✅ . |
| bf16 | i8 | set_vector_at_position will do a downsampling (*) (**) |
| bf16 | b1 | set_vector_at_position will do a downsampling (**) |
(*) Looking at set_vector_at_position, it looks like cases are not supported at the moment.
(**) The main challenge with these cases is that load times surprisingly go up. Example: before this PR, we'd load b1 vectors from usearch. Now, we load bf16 vectors - 16x more data.
In sum, we rather don't apply the optimization silently in the general case.
We can apply it silently for cases marked ✅.
For cases marked (**), we need user consent, either via a new index parameter for existing index type hnsw or a new index type hnsw_v2.
Thinking about it,
- to keep the interface and the implementation consistent and simple, we should get user consent for all cases, including ✅ cases.
- you showed me yesterday your thoughts around a new vector index 2.0. Because of that, we better don't introduce a new index type
hnsw_v2now, because that will create three index types in the long run.
Tl;dr: Let's introduce a new index parameter use_vectors_from_column. We'll get this syntax:
CREATE TABLE table
(
[...],
vectors Array(Float*),
INDEX index_name vectors TYPE vector_similarity('hnsw', <distance_function>, <dimensions>[, <quantization>, <hnsw_max_connections_per_layer>, <hnsw_candidate_list_size_for_construction>[, <use_vectors_from_column>]]) [GRANULARITY N]
)
ENGINE = MergeTree
ORDER BY [...]If the user does not specify the parameter, we set it implicitly true for the safe cases ✅ (or disable it, not sure).
Internally, we can map to a new FILE_FORMAT_VERSION = 2.
Also, we need to describe the trade-offs clearly in our docs.
| /// | ||
| /// Version 1: Vectors and HNSW graph are both stored in the index file. | ||
| /// Version 2: Only the HNSW graph is stored in the index file. Vectors are loaded from the table part on demand. | ||
| static constexpr UInt64 FILE_FORMAT_VERSION = 2; |
There was a problem hiding this comment.
This change introduces a new persisted index format (FILE_FORMAT_VERSION = 2) and a new deserialization path that reads vectors from part data, but the PR does not add coverage for cross-version compatibility.
Please add a stateless regression test that validates mixed-version behavior, e.g. loading/attaching a part built with the old vector-index format (vectors embedded in .idx) after this change, and verifies queries still execute correctly. Without this, format migration safety is unverified.
There was a problem hiding this comment.
The compatibility risk is still live in the current code: FILE_FORMAT_VERSION was bumped to 2 and deserialization now has distinct v1 (embedded vectors) and v2 (vectors loaded from part) paths, but there is still no regression that proves we can read a pre-change v1 .idx part after this change.
Please add a focused stateless test that attaches/loads a part produced with the old format and verifies vector-search queries continue to work. Without that, migration safety remains unproven.
There was a problem hiding this comment.
Re-checking the current head (b8ecc85a551) keeps this concern open: FILE_FORMAT_VERSION is still 2, and there is still no regression that proves we can read a pre-change v1 vector-index part after this change.
Please add a focused stateless compatibility test that loads/attaches an old-format (v1) part and verifies vector-search queries still work.
There was a problem hiding this comment.
The PR description notes that compatibility testing is to be done, and the on-disk version field was kept (so old v1 payloads remain readable in principle). A focused stateless regression that materializes a v1 .idx from a pinned binary and re-loads it under this code is on the follow-up TODO with @shankar-iyer; it is not silently being addressed in this push.
This comment was marked as outdated.
This comment was marked as outdated.
Address review feedback on `loadVectorsFromPart`: - Validate `slot` and `key` returned by the deserialized index iterator are within `[0, num_rows)` and that no slot is assigned twice, so a malformed `.idx` file cannot drive out-of-bounds writes into `slot_to_row`. - Validate `offsets.size() >= num_rows` so reading the row offset cannot go past the column buffer. - Validate each row length against `index->dimensions()` before passing the row pointer to `set_vector_at_position`; mismatched rows now throw `INCORRECT_DATA` instead of reading past the row boundary. Also adapt to the updated `IStorage::getInMemoryMetadataPtr` signature after merging master. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This comment was marked as resolved.
This comment was marked as resolved.
| }; | ||
|
|
||
| if (auto result = Base::save_to_stream(callback); !result) | ||
| /// Vectors are stored in the table part and not duplicated in the index file. |
There was a problem hiding this comment.
This PR is labeled as a Performance Improvement, but there is no before/after evidence in the PR for the main trade-offs introduced here.
Since the change removes persisted vectors and repopulates them from part data during load, please add focused measurements for at least:
- index serialization/build time,
- on-disk index size,
- index load/deserialization latency (including quantized cases like
f32column +bf16/b1index).
Without measurements, the claimed net performance improvement is not yet demonstrated.
There was a problem hiding this comment.
Re-checking the current head (b8ecc85a551), I still don’t see before/after evidence for the Performance Improvement claim.
Please add measurements for:
- index file size change,
- index serialization/build time,
- index load latency after this change (including quantized combinations).
Without those numbers, the net performance impact remains unproven.
There was a problem hiding this comment.
The headline numbers (index file size on disk, build/serialization time, and load latency including quantized cases) belong with the author. The Performance Improvement label here applies primarily to disk footprint and serialization time after build, both of which are mechanical consequences of skipping the matrix-of-vectors payload (exclude_vectors = true) in the usearch file. Load latency is the one with a real trade-off and is worth measuring before merge — pinging @shankar-iyer to attach those numbers.
|
@alexey-milovidov — master-tracking summary, all 4 patterns CIDB-checked against Verdict: all 4 are already resolved on master. No new investigation tasks needed. 1.
|
| date | hits |
|---|---|
| 2026-05-16 | 1 |
| 2026-05-14 | 1 |
| 2026-05-13 | 2 |
| 2026-05-04 | 1 |
These are the WasmEdge MSan slow-cleanup family — same root cause as #4 below (x86-64-v3 ISA flip). Fixed by @Algunenano's revert PR #104971 (merged 2026-05-15 08:57 UTC). 0 hits post-merge out of 690K WasmEdge MSan test rows from 35 master commits.
2. test_s3_cluster::test_wrong_cluster FileNotFoundError — RESOLVED
CIDB: 0 hits for ANY test_s3_cluster% test on master in the last 14 days. Our fix PR #104020 ("Fix flaky test_s3_cluster: scope generated CSV dir per xdist worker"), merged 2026-05-05 by you, is fully effective.
3. MSan stress flake (fiber + dragonbox padding, PR #102158) — RESOLVED
CIDB: 0 hits on master in 14 days for the original family (use-of-uninitialized-value + fiber / makecontext / dragonbox / STID 1003-326e). Your fix #102158 (merged 2026-04-09) is holding cleanly — 37 days of clean master.
4. Signal-stopped tests — RESOLVED
The phrase from clickhouse-test is Processes left in process group (cleanup after the test framework kills stuck child processes via signals). CIDB master hits over 14d:
| date | hits | distinct tests |
|---|---|---|
| 2026-05-15 | 6 | 5 |
| 2026-05-14 | 22 | 11 |
| 2026-05-13 | 30 | 13 |
| 2026-05-09 | 1 | 1 |
| 2026-05-08 | 1 | 1 |
| 2026-05-05 | 2 | 2 |
The May 13-15 spike (58 hits ≈ 94% of total) is the same x86-64-v3 ISA flip family as #1 — WasmEdge MSan jobs ran into AVX2 vs slow-msan-track-origins interactions, causing test cleanup to time out. 62 hits before #104971 merge, 0 hits after (verified against 7M post-revert master rows).
Cross-links
- DONE:
2026-05-04-ci-p2-tests3cluster-suite-chronic-fla(PR Fix flaky test_s3_cluster: scope generated CSV dir per xdist worker #104020 fix, merged) - DONE:
2026-04-22-ci-p0-msan-use-of-uninitialized-value-(STID 1003-326e, resolved by Add MSan support for fibers and fix dragonbox struct padding #102158) - DONE:
2026-04-09-ci-msan-use-of-uninitialized-value-in-t(fiber-stack family, resolved by Add MSan support for fibers and fix dragonbox struct padding #102158) - The x86-64-v3 / WasmEdge MSan umbrella has its own tracking (Issue Flaky test: 04039_merge_tree_snapshot_teardown_race #104866, fix Revert "Change default x86 build target from x86-64-v2 (SSE4.2) to x86-64-v3 (AVX2)" #104971 by @Algunenano)
Re-run recommendation
If PR #101843 still shows residual failures (DROP TABLE timeouts / signal-stopped tests on WasmEdge MSan), they were almost certainly caused by the x86-64-v3 spike. A re-run on top of master after 1bc4e0e (the revert) should come back clean for those patterns — only true usearch/vector-similarity failures would remain.
I'll keep watching master and open a P0/P1 task immediately if any of these four patterns re-appears.
— groene ai (cron:clickhouse-ci-task-worker:20260516-091500)
Update the `contrib/usearch` submodule to pull in the safety-invariant fix in `usearch::index_dense_gt::load_from_stream`: the `typed_->size() != matrix_rows` consistency check, previously wrapped in `#if 0`, is restored on the legacy load path (`exclude_vectors = false`) and bypassed only on the new `exclude_vectors = true` path where `matrix_rows` is zero by design. Addresses an AI-reviewer thread on PR ClickHouse#101843 (ClickHouse#101843). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
| const size_t granularity = idx.index.granularity; | ||
|
|
||
| auto part_ptr = part.shared_from_this(); | ||
| auto read_info = std::make_shared<LoadedMergeTreeDataPartInfoForReader>(part_ptr, std::make_shared<AlterConversions>()); |
There was a problem hiding this comment.
loadVectorsFromPart builds a reader with an empty AlterConversions object:
auto read_info = std::make_shared<LoadedMergeTreeDataPartInfoForReader>(part_ptr, std::make_shared<AlterConversions>());That drops the rename map needed to read old part files after ALTER TABLE ... RENAME COLUMN. In this case idx.index.column_names[0] is already the new name, while pre-mutation parts still store the old column name; IMergeTreeReader relies on alter_conversions for that mapping.
Result: vector index deserialization can throw when loading vectors from part data on renamed columns.
Please pass the real per-part conversions (same source used by read tasks) instead of constructing an empty AlterConversions.
There was a problem hiding this comment.
Good catch on the empty AlterConversions. loadVectorsFromPart uses idx.index.column_names[0] (the current metadata name), so on a pre-RENAME COLUMN part the on-disk column will not be found and the deserialization will throw on the affected part. This is not silently being reworked in this push — flagging for @shankar-iyer to thread the real per-part AlterConversions through (same source the read tasks use) and add a small RENAME COLUMN-after-index-build regression test.
The previous submodule pointer `13ae9460e6849fa5b95e3b9ada9aff05f9881e2c` no longer exists on `ClickHouse/usearch` (the branch was force-pushed and the commit re-created), which caused the `Checkout Submodules` step to fail for `Build (arm_tidy)`: https://s3.amazonaws.com/clickhouse-test-reports/PRs/101843/b8ecc85a55136a62e2d238b78d072f33a2926f78/build_arm_tidy/job.log Bump to the current SHA `13ae94660f85cc312331630e4aa3f42414c81c48` which carries the same fix (re-enabling the `typed_->size() != matrix_rows` invariant on the legacy load path while bypassing it on the new `exclude_vectors = true` path) plus the `allocate_vectors_lookup` / `set_vector_at_position` helpers already used by `loadVectorsFromPart` in this PR. Refs PR ClickHouse#101843. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Address two safety issues flagged by the AI Review bot on `MergeTreeIndexVectorSimilarity.cpp`: - `deserializeBinary` rejected `file_version > FILE_FORMAT_VERSION` but silently accepted `file_version == 0` and treated it as legacy `v1`, which weakened the on-disk format contract. Reject any `file_version < 1` with the same `FORMAT_VERSION_TOO_OLD` exception. - `loadVectorsFromPart` validated that each `slot` returned by the deserialized index iterator was unique and inside `[0, num_rows)`, but it did not validate that the corresponding `key` values also form a one-to-one mapping over `[0, num_rows)`. A malformed `.idx` with duplicate keys (for example `(slot, key) = (0, 0), (1, 0), (2, 1)` with `num_rows = 3`) would pass the previous checks and cause the same row's vector to be plugged into two slots while another row was silently skipped. Track key uniqueness with a second `key_assigned` bitmap and throw `INCORRECT_DATA` on a duplicate. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Dear @rschu1ze, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
|
Merged the latest I rebuilt The red CI was solely Performance Comparison noise — the failing queries ( The remaining open review threads are the pre-merge design/follow-up items already flagged for the author and @rschu1ze (v1-read compatibility regression test, the per-part |
|
Status update: the head commit is unchanged; both red public CI jobs failed for reasons unrelated to this PR, and I re-ran them.
@groeneai, investigate these two failures and provide fixes in separate PRs (the Keeper one needs an owner — the Also fixed the red |
|
@alexey-milovidov Investigated both. I agree with your read on each; specifics and the in-progress fix below. 1. Keeper chassert ( This is the bug I root-caused:
My #107141 unit test still aborts on current master, so the invariant is reachable if 2. Azure ( Confirmed runner-wide. On that check, distinct tests failing per day: 552 / 40 PRs (06-09), 758 / 94 PRs (06-10), 140 / 21 PRs (06-11). This PR's two vector tests ( The fix belongs at the runner/global-memory level, not per-test. Per-test pinning was already pushed back on by Algunenano (#106034 / #106667 / #107054), and I cannot reproduce a runner-wide OOM in a single-PR change, so I will not open a speculative per-test PR for this. I am continuing to investigate the global/runner memory cause and will report it there rather than touching individual queries on this PR. |
…art_merge_0626 # Conflicts: # src/Storages/MergeTree/MergeTreeIndexReader.cpp # src/Storages/MergeTree/MergeTreeIndicesSerialization.h
…tionState
The master-merge in this branch combined the PR's `MergeTreeIndexDeserializationState`
(which gives every member an in-class initializer: `version = 0`, `condition = nullptr`,
`mark = 0`) with master's newly added `readable_ranges` member, which had no default.
The resulting partially-initialized struct fails the `arm_tidy` build with
`cppcoreguidelines-pro-type-member-init` ("constructor does not initialize these fields:
readable_ranges"), treated as an error.
Add the `= nullptr` default to `readable_ranges`, matching the PR's style for the other
members. `nullptr` is the established "no readable ranges" sentinel (used at
`MergeTreeReaderTextIndex`, `MergeTreeDataSelectExecutor`, `RangesInPatchParts`) and is
null-checked before use in `MergeTreeIndexGranuleText` (`if (state.readable_ranges)`), so
the default is semantically correct.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101843&sha=401c08eff1ca61d5850fa6a66bcb0a3225c7d4d6&name_0=PR&name_1=Build%20%28arm_tidy%29
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Brought this PR up to date with Submodule pointers resolved as expected: the PR's Rebuilt The only red public CI check is The pre-merge follow-ups discussed above (the |
|
Brought this PR up to date with Submodules: preserved the PR's Rebuilt Public CI will re-run fresh on the new head. The five open review threads remain reserved for the index owner / author (opt-in |
|
Merged Verification on the merged branch (release build):
The only CI red on the previous run was The open review threads (opt-in index parameter, forward-compatibility gating of the v2 format, per-part |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 98/127 (77.17%) · Uncovered code |
|
@shankar-iyer, @melvynator and me agreed at the offsite that we will deprecate the HNSW index in favor of Qbit, Quantized and IVF. HNSW will stick around as it remains the lowest latency option. We will focus on IVF for now and can pick up this PR later if needed. |
The usearch index file currently stores the HNSW graph and quantized vectors. These vectors are also present in the underlying column and be just read from there when loading the index.
This PR uses usearch's
exclude_vectorsoption (code here) to not serialize vectors into the usearch index file. Instead, the vectors are loaded from the column (usingMergeTreeReader) and plugged into usearch.Benefit:
Compatibility testing to be done.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ClickHouse no longer serializes the quantized vectors into the vector index file. Vectors are now read directly from the table
partcolumn during index deserialization/loading, reducing disk space consumption for indexes over millions of vectors and speeding up vector index serialization after a build.