Skip to content

WIP : Experimental IVF method for vector_similarity indexes - #124210

Open
shankar-iyer wants to merge 22 commits into
ClickHouse:masterfrom
shankar-iyer:ivf_index_bootstrap
Open

shankar-iyer wants to merge 22 commits into
ClickHouse:masterfrom
shankar-iyer:ivf_index_bootstrap

Conversation

@shankar-iyer

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

Copy link
Copy Markdown
Member

Adds an experimental IVF method for vector_similarity indexes on MergeTree tables sorted by a cluster id. The index trains centroids from a sample table in the background, persists them in an internal table and dictionary owned by the table, and enables low latency vector search queries. The feature is intended for tables with millions to billions of vectors.

[Not yet ready for review]

Changelog category

  • Experimental Feature

Changelog entry

  • Add the experimental ivf method for vector_similarity indexes, which enables vector search queries on a table sorted by cluster id. Enabled with the setting allow_experimental_vector_ivf_index

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

shankar-iyer and others added 3 commits October 6, 2026 10:10
Add the experimental index type `vector_similarity('ivf', distance, dimensions,
samples = ..., clustering = f(k, ...))` on `(vec, cid)` for cluster-organized
MergeTree tables, gated by `allow_experimental_vector_ivf_index`.

- The index stores the row count per cluster id in each granule.
- CREATE TABLE creates an internal centroids table and dictionary owned by the
  table, and trains the centroids from the samples table in the background, as
  the creating user. Both objects are dropped with the table.
- `IvfClusterPruningPass` rewrites `ORDER BY dist(vec, q) LIMIT k` to read only
  the `ivf_nprobe` nearest clusters (settings `ivf_nprobe`, `ivf_epsilon`).
- `assignCentroid` accepts the name of an IVF table and rejects incomplete
  centroids.
- Documentation in annindexes.mdx.

Related: ClickHouse#112578

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table will also hold the product quantization codebook.

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

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3b0eed5]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) FAIL
02354_vector_search_ivf_index_inner_objects FAIL cidb
02354_vector_search_ivf_index_rewrite_conditions FAIL cidb
05316_secret_arguments_declared_by_engines FAIL cidb
02354_vector_search_ivf_index_rename FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) FAIL
02354_vector_search_ivf_index FAIL cidb
02354_vector_search_ivf_index_clustering_result FAIL cidb
02354_vector_search_ivf_index_end_to_end FAIL cidb
02354_vector_search_ivf_index_training_dimensions FAIL cidb
02354_vector_search_ivf_index_access FAIL cidb

AI Review

Summary

This PR adds an experimental IVF backend for vector_similarity on MergeTree: hidden centroid storage, background training, cluster-splitting maintenance, assignCentroid integration, and a pruning rewrite for ORDER BY <distance>(vec, q) LIMIT k queries. Several earlier review points are fixed in the current head, but the branch still has one wrong-results bug in the pruning gate, one access-context bug in deferred training, and one realistic restart fragility that leaves an IVF table permanently unusable after an interruption.

Findings
  • ❌ Blockers
    • [src/Analyzer/Passes/IvfClusterPruningPass.cpp:198] The pruning rewrite turns on as soon as the centroids table is merely non-empty. Training and split writes are generation-based and can fail mid-write; assignCentroid already rejects an incomplete generation, but the pruning pass does not. In that state it can rewrite a query to an incomplete cid set and silently drop matching rows from the result when rows were inserted with explicit cids. Suggested fix: gate the rewrite on a complete generation, reusing the same generation / generation_size completeness check as assignCentroid, or expose that validation through a shared helper.
    • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarityIvf.cpp:886] The deferred training read still does not replay the full submitting identity. samples_context->setUser(*user_id) drops external roles and authentication grant limits, and setCurrentRoles(context->getCurrentRoles()) re-validates effective roles against local grants. For pushed-role sessions this can make CREATE TABLE fail with SET_NON_GRANTED_ROLE; for limited credentials it can also run the training SELECT under broader privileges than the creating session. Suggested fix: mirror the replay pattern already used in AsynchronousInsertQueue, DDLTask, and StorageQueryRunner: call setUser(*user_id, context->getExternalRoles(), context->getAuthenticationGrants(), context->getAuthenticationValidUntil()), then setCurrentRoles(context->getCurrentRoles(), /*check_grants=*/ false), and restore the originating client-info names.
  • ⚠️ Majors
    • [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/124210#discussion_r4198257706] [src/Interpreters/InterpreterCreateQuery.cpp:2430] IVF training is still fire-and-forget only at CREATE TABLE time. A restart or ATTACH during the training window leaves the centroids table empty forever, so default assignCentroid inserts fail and IVF pruning never activates until the user drops and recreates the table. Documenting this helps, but the runtime behavior is still a realistic availability failure for a feature that explicitly expects long-running training. Suggested fix: persist a “training pending” state and resume idempotently on attach/startup, or otherwise detect and recover from an untrained IVF table.
Final Verdict

❌ Not ready to merge. The pruning rewrite can still return incomplete results, and the deferred training path still replays access state incorrectly. The restart fragility is also still real even though it is documented.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-vector-index Vector similarity index in MergeTree: ANN/HNSW index build/query, usearch integration, vector ind... label Oct 6, 2026
Reading the metadata of every dropped table resolved the targets of alias tables
and recursed for a self-referencing alias. The failed DROP left a cycle in the
dependency graph, which broke all later tests that add dependencies.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124210&sha=c800582edc1cf682fb314d6a346f9cb94ac0c7b0&name_0=PR&name_1=Fast%20test
PR: ClickHouse#124210

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The CREATE and DROP hooks forced deferred tables (table functions, lazily loaded
tables) to load. The CREATE hook now skips deferred tables, and the DROP hook finds
IVF indexes in the stored CREATE query instead of the storage.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124210&sha=6ac477f248c260b4e066572085e7dc4dff47f502&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: ClickHouse#124210

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Trains 256 centroids from a sample table, inserts 200k rows through the DEFAULT
assignment, and checks pruning, ivf_epsilon and recall against the exact search.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
try
{
createVectorSimilarityIvfInnerObjects(table_id, table->getName(), *metadata, getContext());
scheduleVectorSimilarityIvfTraining(table_id, *metadata, getContext());

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 fire-and-forget scheduling is not crash-safe. CREATE TABLE returns before training finishes, but on restart / ATTACH we never call scheduleVectorSimilarityIvfTraining again, so a server restart during the minutes-or-hours training window leaves the centroids table permanently empty: assignCentroid(vec, 'table') keeps failing for the default cid, and IVF pruning stays disabled forever because IvfClusterPruningPass sees zero centroids and bails out. We need persisted training state or an attach/startup requeue when the inner objects are still uninitialized.

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.

This is correct. Training is scheduled only at CREATE TABLE and is not resumed on ATTACH or
server startup, so a crash restart during training leaves the quantizer table empty or partially filled. Results
stay correct in that state: assignCentroid rejects INSERTs while the centroids are missing or incomplete
(the per-generation row count check), and the query rewrite is not applied. But the table can't be used
until it's recreated.

For this experimental first version, I have documented the limitation in annindexes.mdx. Resuming training at
startup will be a follow-up. It needs two decisions:

  • the identity under which the training runs when no session exists;
  • a guard so that only one replica retrains in ClickHouse Cloud.

The follow-up will also add a way to check the training status

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 3b0eed5ae67ac9d231331a02fdedad2b05c3706e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

shankar-iyer and others added 2 commits October 7, 2026 08:38
Support `RENAME` and `EXCHANGE TABLES` within a database, reject `CREATE TABLE ... AS` and `CLONE AS`, check the
dimensions and count of the trained centroids, quote the samples table name in the training query, and document
that training is not resumed after a restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check rejects test names containing `fail`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
"Centroids table {} of IVF vector similarity index {} does not exist", centroids_id.getNameForLogs(), ivf_index->name);

/// Until the centroids are trained there are no clusters to prune by, and every row must be read.
const auto centroids_rows = centroids_storage->totalRows(context);

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 gate is too weak for correctness: the training path writes generation_size specifically so readers can distinguish a complete centroid generation from a partially written one, and assignCentroid already rejects incomplete generations. The pruning rewrite ignores that and turns on as soon as there is any row in the centroids table, so a failed training INSERT can still rewrite queries to an incomplete cid set. Because manual INSERTs may provide cid directly, that silently drops matching rows from query results. Please require a complete centroid generation here, not just totalRows() > 0.

…able

A concurrent `RENAME`, `EXCHANGE` or `DROP` could otherwise see the table before its hidden objects exist. The
rollback now drops the table without taking the guard again, which it already holds.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shankar-iyer and others added 2 commits October 8, 2026 10:36
The clustering function may return `Array(Array(Float32))` or a tree as named tuples
`(vec, level, cid, parent[, radius])`. Training checks the whole result (k leaves, dimensions,
unique non-zero ids, parents one level up) before storing it; leaf ids now start at 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tic query vectors

A filter on the cluster id column already chooses the clusters, and a query vector that is not deterministic
would choose the clusters for another vector. Also document that the samples table must stay until training completes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Functions/assignCentroid.cpp Resolved
The hidden table and dictionary are created, trained and read internally, like the inner table of a materialized
view: searching needs `SELECT` on the table, `assignCentroid` needs `SELECT` or `INSERT` on it, and `CREATE TABLE`
needs `SELECT` on the samples table. `assignCentroid` now assigns only to leaves of a tree of centroids.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// The training runs after CREATE returns and outlives the session, so it gets a context of its own, with the settings
/// of the query which created the table. It writes the hidden objects, which need no grants of the user (see
/// createVectorSimilarityIvfInnerObjects, which also checks that the user may read the samples).
auto training_context = Context::createCopy(context->getGlobalContext());

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.

Training now runs from Context::createCopy(context->getGlobalContext()), but the only access check before that is the coarse checkAccess(SELECT, db, table, column) above. That drops the creator's current roles, row policies, and column masks for the actual SELECT ... FROM samples: a user who can read only a filtered subset of the samples table still trains centroids from the full underlying data, and can then observe that state indirectly through assignCentroid / IVF pruning. Please preserve the caller's access context for the read side (or otherwise enforce the same row-policy / masking semantics) and use internal privileges only for writing the hidden objects.

shankar-iyer and others added 2 commits October 8, 2026 15:52
With the new index argument `target_cluster_size`, a background task splits clusters with more than twice
that many rows into round(rows / target_cluster_size) children, trained by the clustering function of the
index on a sample of the cluster. All children of a round are written by one insert with `split_from`,
which retires the split clusters. Internal queries now run in a thread group of their own query context,
and the centroids dictionary reloads by itself when its invalidate query detects a change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shankar-iyer and others added 3 commits October 9, 2026 05:04
The cluster id of an IVF index is `UInt64`. Training gives every leaf a range of cluster ids below 2^63, and a
split gives its two children the halves of the rest of the range of the cluster, so that a cluster and all
clusters split from it are stored next to each other. Splits now happen when a cluster exceeds
`target_cluster_size`, into two children. `assignCentroid` returns `UInt64` for a dictionary or an IVF table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The hidden centroids table gets `created_at DateTime DEFAULT now()`, so that every generation (training, split)
carries the time it was written, for later policies based on age.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
shankar-iyer and others added 4 commits October 9, 2026 09:18
…te self-references on ALTER

Training reads the samples table with the user and roles of the user who created the table, so that row
policies and column masks apply, and writes the hidden centroids table internally. A reference to the table
itself in `assignCentroid` set by `ALTER TABLE ... MODIFY COLUMN ... DEFAULT` is now rewritten to the centroids
dictionary as well, so that it survives `RENAME` and `EXCHANGE`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI runs with `table_engines_require_grant`, so the user who creates tables in the test needs
`TABLE ENGINE ON MergeTree`; without it the checks failed for the wrong grant and the row policy case timed out.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=124210&sha=eae3c20ed07428f1692a817d1412a045c7dc89b2&name_0=PR&name_1=Fast%20test
PR: ClickHouse#124210

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tables register themselves when their metadata with an IVF index is set (`CREATE`, `ATTACH`, startup), and the
background task visits only registered tables instead of every table of the server. Tables which no longer
exist leave the registry when the task finds them gone.

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

This branch has not been deployed

No deployments
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... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant