Skip to content

Read vectors from part when loading usearch index - #101843

Closed
shankar-iyer wants to merge 23 commits into
ClickHouse:masterfrom
shankar-iyer:read_vectors_from_part
Closed

shankar-iyer wants to merge 23 commits into
ClickHouse:masterfrom
shankar-iyer:read_vectors_from_part

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Apr 6, 2026 •

Copy link
Copy Markdown
Member

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_vectors option (code here) to not serialize vectors into the usearch index file. Instead, the vectors are loaded from the column (using MergeTreeReader) and plugged into usearch.

Benefit:

  • lower disk space consumption when there are millions of vectors
  • faster vector index serialization after an index build

Compatibility testing to be done.

Changelog category (leave one):

  • Performance Improvement

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 part column during index deserialization/loading, reducing disk space consumption for indexes over millions of vectors and speeding up vector index serialization after a build.

@clickhouse-gh

clickhouse-gh Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [125aec9]

Summary: ❌

job_name test_name status info comment
Stress test (arm_debug) FAIL
Cannot start clickhouse-server FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR switches vector_similarity index persistence to write v2 .idx files without embedded vectors and to rebuild the USearch vector matrix from the part column during deserialization. The current head still has two merge-blocking gaps: it unconditionally produces a forward-incompatible on-disk format, and the new read-from-part path bypasses the per-part read conversions that normal MergeTree readers use.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:155-160,253-266] serialize now always sets exclude_vectors = true and serializeBinary always stamps FILE_FORMAT_VERSION = 2. That means any new or merged part produced by an upgraded node becomes unreadable by older ClickHouse binaries that only understand the legacy embedded-vector payload, so rolling upgrades and downgrades break as soon as a vector_similarity part is rewritten. Suggested fix: gate v2 writes behind a compatibility-tied setting or explicit index parameter, and keep emitting v1 until every reader in the cluster understands v2.
  • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:323-347] loadVectorsFromPart constructs LoadedMergeTreeDataPartInfoForReader with a fresh AlterConversions, so it drops the rename map and any other read-time conversions that ordinary MergeTree readers apply. After ALTER TABLE ... RENAME COLUMN, an old part still stores the vector data under the old column name, but this path asks the reader for the new name and throws instead of loading the index. Suggested fix: thread the real per-part AlterConversions into MergeTreeIndexDeserializationState and reuse it here.
Tests
  • ⚠️ Add a focused stateless regression that attaches or loads a pre-change v1 vector-index part and runs a vector-search query. The current suite exercises the new v2 round-trip, but it still does not prove the backward-read path in deserializeBinary.
  • ⚠️ Add a RENAME COLUMN-after-index-build regression once the real AlterConversions are threaded through loadVectorsFromPart; that is the smallest focused test that would catch the current bug.
  • ⚠️ Add before/after measurements for index file size, serialization/build time, and index load latency, especially quantized cases. Without those numbers, the Performance Improvement claim remains unproven.
Final Verdict

Status: ❌ Block

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR. labels Apr 6, 2026
@rschu1ze rschu1ze self-assigned this Apr 6, 2026
/// 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;
///

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.

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.

@shankar-iyer shankar-iyer Apr 7, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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 parts merge 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 has Float32 vectors and the index is bf16 quantized. But if the index is binary quantized, then it is better to just persist the quantized vectors in usearch index itself and read them from there. This PR is good only for when vector column datatype is Float32 or BFloat16 and usearch datatype is f32 or bf16.
  • 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_position call 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

hnsw_v2 (for the lack of a better term). Also note how the parameter quantization is 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?

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.

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_v2 now, 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;

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

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.

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.

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.

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.

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

@alexey-milovidov

This comment was marked as outdated.

alexey-milovidov and others added 2 commits May 16, 2026 08:29
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]>
@alexey-milovidov

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.

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 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 f32 column + bf16/b1 index).

Without measurements, the claimed net performance improvement is not yet demonstrated.

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.

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.

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

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — master-tracking summary, all 4 patterns CIDB-checked against head_ref='master' over the last 14 days.

Verdict: all 4 are already resolved on master. No new investigation tasks needed.

1. DROP TABLE timeouts — RESOLVED

CIDB: 5 master hits / 14d, all on Stateless tests (amd_msan, WasmEdge, parallel) (01516_drop_table_stress_long ×3, 04039_merge_tree_snapshot_teardown_race ×1, 02015_async_inserts_2 ×1 on TSan curl-timeout — different family). Every one shows Failure is not reproducible (likely a transient issue) after re-run. Distribution:

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

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)

Comment thread contrib/usearch Resolved
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>());

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.

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.

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.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

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.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master into the branch (it was ~911 commits behind and red). The merge is conflict-free; the only nuance was the contrib/usearch, contrib/NuRaft, and contrib/delta-kernel-rs submodule pointers, which resolved correctly (PR's usearch bump preserved, master's NuRaft/delta-kernel-rs bumps taken).

I rebuilt clickhouse against current master — it compiles cleanly — and verified the v2 "load vectors from part" path end-to-end: a vector_similarity('hnsw', 'L2Distance', 3) index built and persisted with exclude_vectors = true, then read back in a fresh process, is recognized by EXPLAIN indexes=1 and returns correct nearest neighbors.

The red CI was solely Performance Comparison noise — the failing queries (rand, join_reserve, async_remote_read) are unrelated to vector indexes, and the machine-readable report shows "No significant performance changes detected."

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 AlterConversions fix for RENAME COLUMN, forward-compatibility gating of v2 writes, and the perf measurements) — left untouched as they are design decisions for the index owner.

@alexey-milovidov

Copy link
Copy Markdown
Member

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 chassert was added specifically to catch this in CI; the azure one is a runner-wide memory exhaustion). If fixes are already in progress, link them here.

Also fixed the red CH Inc sync: the private sync branch failed to build against the then-current private master (duplicated forward declaration of estimateReadRowsCount in optimizeJoin.cpp produced by the automatic merge). Merging the current private master into the sync branch resolves it cleanly; pushed the merge to the sync PR.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Investigated both. I agree with your read on each; specifics and the in-progress fix below.

1. Keeper chassert (Integration tests (amd_tsan, 2/6)): fix already exists as #107141, closed by the Keeper owner in favor of #106842.

This is the bug I root-caused: chassert(false) at KeeperStateMachine.cpp:1549 in read_logical_snp_obj, hit when NuRaft's async_io_loop requests a chunk with obj_id > 0 after the peer's snapshot_sync_ctx reset leaves user_snp_ctx == nullptr. Introduced by #104941.

My #107141 unit test still aborts on current master, so the invariant is reachable if nuraft_use_bg_thread_for_snapshot_io is ever re-enabled. The same question is open on #79991. Your call (and antonio2368's, as he closed it as owner): reland #107141 as defense-in-depth in a separate PR, or treat it as resolved by the off-by-default mitigation. I will not reland owner-declined code without your confirmation.

2. Azure (Stateless tests (arm_asan_ubsan, azure, parallel)): runner-wide OOM, as you said; not this PR.

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 (02354_vector_search_queries, 03463_numeric_indexed_vector_overflow) both failed with return code: 241 (MEMORY_LIMIT_EXCEEDED), not wrong results, with server RSS sitting at the 53.69 GiB ceiling.

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.

@rschu1ze rschu1ze self-assigned this Jun 13, 2026
alexey-milovidov and others added 4 commits June 13, 2026 18:46
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Brought this PR up to date with master (merge 947c920fa38; the branch was ~3820 commits / ~9 days behind). The merge is conflict-free — the net PR diff still touches only the four intended files (MergeTreeIndexReader.cpp, MergeTreeIndexVectorSimilarity.{cpp,h}, MergeTreeIndicesSerialization.h).

Submodule pointers resolved as expected: the PR's contrib/usearch bump to v2.24.0 (13ae946) was preserved, and master's NuRaft/delta-kernel-rs/zstd bumps were taken. v2.24.0 is a descendant of master's usearch commit (1ae009a, fix/sorted-buffer-heap-overflow), so it already contains that heap-overflow fix — no regression.

Rebuilt clickhouse against the merge (compiles and links cleanly) and re-ran the 02354_vector_search_* suite; the "load vectors from part" v2 path is verified end-to-end, including the serialize → deserialize round-trip in 02354_vector_search_detach_attach and the quantized binary_quantization path.

The only red public CI check is AST fuzzer (amd_debug) failing with Logical error: 'Equal values are not contiguous within the range assumed to be sorted'. This is a known, master-wide AST-fuzzer flake unrelated to this PR (it hit ~11 unrelated PRs over the last two weeks and has an open tracking issue, #109216) — it originates in DistinctSortedStreamTransform / optimize_distinct_in_order, not in the vector-index code.

The pre-merge follow-ups discussed above (the use_vectors_from_column opt-in parameter and forward-compat gating for the v2 write path, the per-part AlterConversions threading for RENAME COLUMN, the v1-read compatibility regression, and the load-latency measurements) remain with @shankar-iyer and @rschu1ze; none of them are addressed in this refresh.

@alexey-milovidov

Copy link
Copy Markdown
Member

Brought this PR up to date with master (merge 22d89279fbc; the branch was ~2359 commits / ~7 days behind and had gone red). The merge is conflict-free — the net PR diff still touches only the four intended files: MergeTreeIndexReader.cpp, MergeTreeIndexVectorSimilarity.cpp, MergeTreeIndexVectorSimilarity.h, and MergeTreeIndicesSerialization.h.

Submodules: preserved the PR's contrib/usearch at v2.24.0 (13ae946, a descendant of master's 1ae009a fix/sorted-buffer-heap-overflow, so it keeps that heap-overflow fix); took master's newer contrib/delta-kernel-rs (88ff5a9) and contrib/libarchive (v3.8.8, 7219b01); contrib/NuRaft and contrib/zstd unchanged.

Rebuilt clickhouse (ASan) locally — links clean. Ran the full 02354_vector_search_* suite plus 04040_vector_search_cache_eviction_on_mutation: every test that can run in a local environment passes, including the ones most relevant to this change — 02354_vector_search_detach_attach (v2 index round-trip: serialize without vectors → detach → attach → re-read vectors from the part column), 02354_vector_search_binary_quantization, 02354_vector_search_distributed_index_analysis (DistributedIndexAnalysisScheduledReplicas=3, USearchSearchCount>0), and 02354_vector_search_random_parameters (serialization stress). The only local failure, 04040_vector_search_cache_eviction_on_mutation, is environmental — it needs S3/MinIO and fails at CREATE TABLE ... storage_policy = 's3_no_cache' (UNKNOWN_POLICY) before any vector-index code runs.

Public CI will re-run fresh on the new head. The five open review threads remain reserved for the index owner / author (opt-in use_vectors_from_column param, forward-compat gating of the v2 on-disk format, per-part AlterConversions in loadVectorsFromPart, the v1-read compatibility regression test, and the performance numbers) — untouched here.

@rschu1ze
rschu1ze marked this pull request as draft July 14, 2026 11:09
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master into the branch again (22d89279fbc → 125aec9c741, conflict-free; the branch was ~4175 commits / 8 days behind). The net diff is still exactly the same 4 files, and the usearch submodule stays at v2.24.0 (13ae946).

Verification on the merged branch (release build):

  • All 52 02354_vector_search_* .sql tests pass (49 via clickhouse local, and distributed_index_analysis, pre_and_post_filtering, vector_similarity_index_cache, queries via a local server through clickhouse-test), including detach_attach (v2 round-trip) and binary_quantization.
  • 02354_vector_search_random_parameters.sh passes as well.

The only CI red on the previous run was test_replicated_database/test.py::test_replicated_table_structure_alter — a known flaky test tracked in #110036, unrelated to this PR. Fresh CI is now running on the new head.

The open review threads (opt-in index parameter, forward-compatibility gating of the v2 format, per-part AlterConversions in loadVectorsFromPart, slot/key completeness check, v1 read-compat regression test, and performance numbers) remain with @shankar-iyer / @rschu1ze as before.

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 98/127 (77.17%) · Uncovered code

Full report · Diff report

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Jul 20, 2026
@abashkeev abashkeev added the comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... label Sep 4, 2026
@rschu1ze

rschu1ze commented Nov 9, 2026

Copy link
Copy Markdown
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... hold Skip for auto-updating. pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants