Repository navigation
crud named vectors - #8605
crud named vectors#8605
Conversation
Introduce EmptyDenseVectorStorage and EmptySparseVectorStorage as placeholder storages for newly created named vectors on immutable segments. These report all vectors as deleted, consume no disk space, and are reconstructed from segment config on load via the new VectorStorageType::Empty and SparseVectorStorageType::Empty variants. Key design decisions: - is_on_disk is derived from original user config, not hardcoded - MultiVectorConfig is preserved for multi-vector support - Config mismatch optimizer skips Empty storage to avoid false rebuilds - Quantization delegates normally (handles 0 vectors gracefully) - get_vector includes debug_assert to catch unexpected access Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAdds named-vector lifecycle support end-to-end: REST and gRPC endpoints for PUT/DELETE /collections/{collection_name}/vectors/{vector_name}; new protobuf and gRPC messages and internal RPCs; collection-level create/delete operations wired through consensus, TOC, dispatcher, and storage; segment-level creation/deletion and reconciliation (including empty dense/sparse storage placeholders for immutable segments); payload-index and proxy-segment support for schema/has-vector semantics; RBAC and validation for vector names; Python/Edge bindings and extensive tests (unit, integration, consensus, OpenAPI). Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes 🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
lib/collection/src/collection/vector_name_schema.rs (2)
76-93:⚠️ Potential issue | 🟠 MajorReject
size == 0instead of rewriting it to1.Line 85 silently normalizes an invalid dense dimension to
NonZeroU64::MIN. That makes the stored schema differ from the request and from the comparison on Line 189, so the same invalid create can later fail the idempotency check instead of being rejected up front.Proposed fix
-fn dense_config_to_params(config: &DenseVectorConfig) -> VectorParams { +fn dense_config_to_params(config: &DenseVectorConfig) -> CollectionResult<VectorParams> { let DenseVectorConfig { size, distance, multivector_config, datatype, } = config; - VectorParams { - size: NonZeroU64::new(*size as u64).unwrap_or(NonZeroU64::MIN), + Ok(VectorParams { + size: NonZeroU64::new(*size as u64) + .ok_or_else(|| CollectionError::bad_input("Dense vector size must be greater than 0"))?, distance: *distance, hnsw_config: None, quantization_config: None, on_disk: None, datatype: datatype.map(storage_datatype_to_collection), multivector_config: *multivector_config, - } + }) }Then propagate the
CollectionResultthroughadd_vector_to_config.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/collection/src/collection/vector_name_schema.rs` around lines 76 - 93, dense_config_to_params currently coerces a zero size into NonZeroU64::MIN which silently accepts an invalid DenseVectorConfig; instead validate and reject size == 0 and propagate a CollectionResult error up through add_vector_to_config so invalid requests fail early. Update dense_config_to_params to return a Result<VectorParams, CollectionError> (or CollectionResult) and check the incoming size, returning an explicit error when size is 0; then adapt add_vector_to_config to handle and propagate that Result rather than assuming construction always succeeds.
64-72:⚠️ Potential issue | 🟠 MajorDon’t mutate the live schema before the save succeeds.
Line 70 updates
config.paramsfirst, then Line 71 can fail. On that path this method returnsErr, but the in-memorycollection_configis already changed while disk still has the old schema.Based on learnings, "Use SaveOnDisk from common::save_on_disk for atomic persist-then-swap semantics when a config or in-memory struct must be kept in memory and persisted atomically on mutation."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/collection/src/collection/vector_name_schema.rs` around lines 64 - 72, The current update_collection_vector_config mutates collection_config.params in-memory before calling config.save, causing in-memory state to diverge on save failure; instead, apply the mutate closure to a temporary/owned CollectionParams (or use common::save_on_disk::SaveOnDisk<...>) so you first persist the updated params atomically, and only after save succeeds swap/replace the in-memory collection_config (or call its write lock to assign the new params). Update update_collection_vector_config to perform mutate -> save -> swap (persist-then-swap) using SaveOnDisk<T> semantics to ensure atomicity between disk and collection_config.
🧹 Nitpick comments (3)
lib/shard/src/proxy_segment/vector_name_changes.rs (1)
370-384: Use explicit field ignoring instead of..in struct destructuring.The struct patterns use
..which can silently ignore new fields ifIntendedVector::Presentis extended later.♻️ Suggested fix
if self_taints && let IntendedVector::Present { - supersedes_wrapped, .. + supersedes_wrapped, + config: _, + version: _, } = &mut winner { *supersedes_wrapped = true; } *self_intent = winner; } else if other_taints && let IntendedVector::Present { - supersedes_wrapped, .. + supersedes_wrapped, + config: _, + version: _, } = self_intent {As per coding guidelines: "Prefer explicit field ignoring using
: _over using..in Rust struct destructuring"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/shard/src/proxy_segment/vector_name_changes.rs` around lines 370 - 384, The patterns matching IntendedVector::Present use `..` which can silently ignore future fields; update both destructuring occurrences (the one binding `winner` inside the self_taints branch and the one matching `self_intent` in the other_taints branch) to explicitly ignore any other fields by naming them with explicit ignore patterns (e.g., list each existing field and use `field_name: _` for the rest) so that only `supersedes_wrapped` is extracted while new fields will not be accidentally skipped; keep the bindings for `winner`, `self_intent`, and the `supersedes_wrapped` field as-is.lib/common/common/src/validation.rs (2)
78-80: Use explicitCow::from(...)instead of implicit.into()Line 79 and Line 104 use implicit
.into()for error message conversion. Please use explicit conversion for clarity and consistency with repo Rust style.Proposed diff
- err.message - .replace(format!("{kind} cannot contain \"{c}\" char").into()); + err.message + .replace(Cow::from(format!("{kind} cannot contain \"{c}\" char"))); @@ - err.message - .replace(format!("vector name must be at most {MAX_LEN} bytes long").into()); + err.message + .replace(Cow::from(format!("vector name must be at most {MAX_LEN} bytes long")));As per coding guidelines,
**/*.rs: Prefer explicitSomeType::from(x)over implicitx.into()in Rust.Also applies to: 103-104
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/validation.rs` around lines 78 - 80, Replace implicit .into() conversions used when updating error messages with an explicit Cow::from(...) call: change the err.message.replace(format!("{kind} cannot contain \"{c}\" char").into()) invocation and the similar occurrence around lines 103-104 to use std::borrow::Cow::from(format!(...)) (or Cow::from(...) if already in scope) so the formatted String is explicitly converted to a Cow before calling err.message.replace(...).
90-109: Add direct unit tests forvalidate_vector_nameboundariesThis validator is new but currently has no dedicated unit tests in this module. Please add coverage for 200-byte pass, 201-byte fail, and filesystem-unsafe characters.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/common/common/src/validation.rs` around lines 90 - 109, Add unit tests for validate_vector_name: create three tests that call validate_vector_name — one constructs a 200-byte string (e.g., 'a' repeated 200) and asserts Ok(()), another constructs a 201-byte string and asserts Err(ValidationError) (optionally assert the error kind is "length" or message contains "at most 200"), and a third passes a string containing a filesystem-unsafe character from INVALID_NAME_CHARS (e.g., '/' or '\\') and asserts Err(ValidationError) (optionally assert the error message mentions "vector name" or invalid character). Place tests in this module’s #[cfg(test)] mod tests and import validate_vector_name and relevant helpers to keep assertions clear and specific.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/collection/src/collection/vector_name_schema.rs`:
- Around line 108-120: The doc comment for add_vector_to_config is stale: it
describes returning Ok(true)/Ok(false) but the function signature returns
CollectionResult<()); update the comment above fn add_vector_to_config (which
takes params: &mut crate::config::CollectionParams, vector_name: &VectorNameBuf,
config: &VectorNameConfig) to accurately describe the current behavior and
return type (i.e., that it returns Ok(()) on success and Err(BadInput) on
conflict) and remove any mention of boolean return values or idempotent
true/false semantics so the documentation matches CollectionResult<()>'s
semantics.
- Around line 19-39: The create/delete vector APIs currently hardcode
non-blocking behavior by calling update_all_local(..., WaitUntil::from(false)),
violating the caller's wait contract; modify the relevant functions (e.g.,
create_named_vector and the corresponding delete_named_vector) to accept a wait
parameter (or a WaitUntil) and propagate it into the update_all_local call
instead of using WaitUntil::from(false), keeping the existing call to
update_collection_vector_config as-is; ensure the signature change is applied
consistently where these functions are invoked so callers can pass the requested
wait flag and schema application will be respected at the shard layer.
---
Duplicate comments:
In `@lib/collection/src/collection/vector_name_schema.rs`:
- Around line 76-93: dense_config_to_params currently coerces a zero size into
NonZeroU64::MIN which silently accepts an invalid DenseVectorConfig; instead
validate and reject size == 0 and propagate a CollectionResult error up through
add_vector_to_config so invalid requests fail early. Update
dense_config_to_params to return a Result<VectorParams, CollectionError> (or
CollectionResult) and check the incoming size, returning an explicit error when
size is 0; then adapt add_vector_to_config to handle and propagate that Result
rather than assuming construction always succeeds.
- Around line 64-72: The current update_collection_vector_config mutates
collection_config.params in-memory before calling config.save, causing in-memory
state to diverge on save failure; instead, apply the mutate closure to a
temporary/owned CollectionParams (or use common::save_on_disk::SaveOnDisk<...>)
so you first persist the updated params atomically, and only after save succeeds
swap/replace the in-memory collection_config (or call its write lock to assign
the new params). Update update_collection_vector_config to perform mutate ->
save -> swap (persist-then-swap) using SaveOnDisk<T> semantics to ensure
atomicity between disk and collection_config.
---
Nitpick comments:
In `@lib/common/common/src/validation.rs`:
- Around line 78-80: Replace implicit .into() conversions used when updating
error messages with an explicit Cow::from(...) call: change the
err.message.replace(format!("{kind} cannot contain \"{c}\" char").into())
invocation and the similar occurrence around lines 103-104 to use
std::borrow::Cow::from(format!(...)) (or Cow::from(...) if already in scope) so
the formatted String is explicitly converted to a Cow before calling
err.message.replace(...).
- Around line 90-109: Add unit tests for validate_vector_name: create three
tests that call validate_vector_name — one constructs a 200-byte string (e.g.,
'a' repeated 200) and asserts Ok(()), another constructs a 201-byte string and
asserts Err(ValidationError) (optionally assert the error kind is "length" or
message contains "at most 200"), and a third passes a string containing a
filesystem-unsafe character from INVALID_NAME_CHARS (e.g., '/' or '\\') and
asserts Err(ValidationError) (optionally assert the error message mentions
"vector name" or invalid character). Place tests in this module’s #[cfg(test)]
mod tests and import validate_vector_name and relevant helpers to keep
assertions clear and specific.
In `@lib/shard/src/proxy_segment/vector_name_changes.rs`:
- Around line 370-384: The patterns matching IntendedVector::Present use `..`
which can silently ignore future fields; update both destructuring occurrences
(the one binding `winner` inside the self_taints branch and the one matching
`self_intent` in the other_taints branch) to explicitly ignore any other fields
by naming them with explicit ignore patterns (e.g., list each existing field and
use `field_name: _` for the rest) so that only `supersedes_wrapped` is extracted
while new fields will not be accidentally skipped; keep the bindings for
`winner`, `self_intent`, and the `supersedes_wrapped` field as-is.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: dcb15af6-61f8-4842-a370-1eb4eaee1e91
📒 Files selected for processing (11)
lib/collection/src/collection/vector_name_schema.rslib/common/common/src/validation.rslib/segment/src/index/struct_payload_index.rslib/segment/src/segment/vector_name_ops.rslib/shard/src/optimize.rslib/shard/src/proxy_segment/mod.rslib/shard/src/proxy_segment/segment_entry.rslib/shard/src/proxy_segment/vector_name_changes.rslib/storage/src/content_manager/collection_meta_ops.rssrc/actix/api/vector_name_api.rssrc/common/update.rs
🚧 Files skipped from review as they are similar to previous changes (6)
- lib/shard/src/proxy_segment/mod.rs
- lib/shard/src/optimize.rs
- lib/storage/src/content_manager/collection_meta_ops.rs
- src/common/update.rs
- lib/shard/src/proxy_segment/segment_entry.rs
- lib/segment/src/segment/vector_name_ops.rs
| pub async fn create_named_vector( | ||
| &self, | ||
| vector_name: VectorNameBuf, | ||
| config: VectorNameConfig, | ||
| hw_acc: HwMeasurementAcc, | ||
| ) -> CollectionResult<()> { | ||
| self.update_collection_vector_config(|params| { | ||
| add_vector_to_config(params, &vector_name, &config) | ||
| }) | ||
| .await?; | ||
|
|
||
| let operation = CollectionUpdateOperations::VectorNameOperation( | ||
| VectorNameOperations::CreateVectorName(CreateVectorName { | ||
| vector_name, | ||
| config, | ||
| }), | ||
| ); | ||
|
|
||
| self.update_all_local(operation, WaitUntil::from(false), hw_acc) | ||
| .await?; | ||
|
|
There was a problem hiding this comment.
Honor the caller’s wait contract here.
Line 37 and Line 56 hardcode WaitUntil::from(false), and these methods do not accept a wait argument. That makes the new create/delete APIs fire-and-forget at the shard layer even when the caller requested wait=true, so follow-up operations can race schema application. The wait parameter on update_all_local in lib/collection/src/collection/point_ops.rs:32-37 is the blocking control.
Proposed fix
pub async fn create_named_vector(
&self,
vector_name: VectorNameBuf,
config: VectorNameConfig,
+ wait: WaitUntil,
hw_acc: HwMeasurementAcc,
) -> CollectionResult<()> {
self.update_collection_vector_config(|params| {
add_vector_to_config(params, &vector_name, &config)
})
.await?;
@@
- self.update_all_local(operation, WaitUntil::from(false), hw_acc)
+ self.update_all_local(operation, wait, hw_acc)
.await?;
@@
- pub async fn delete_named_vector(&self, vector_name: VectorNameBuf) -> CollectionResult<()> {
+ pub async fn delete_named_vector(
+ &self,
+ vector_name: VectorNameBuf,
+ wait: WaitUntil,
+ ) -> CollectionResult<()> {
self.update_collection_vector_config(|params| {
remove_vector_from_config(params, &vector_name);
Ok(())
})
.await?;
@@
self.update_all_local(
operation,
- WaitUntil::from(false),
+ wait,
HwMeasurementAcc::disposable(),
)
.await?;Also applies to: 43-59
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/collection/src/collection/vector_name_schema.rs` around lines 19 - 39,
The create/delete vector APIs currently hardcode non-blocking behavior by
calling update_all_local(..., WaitUntil::from(false)), violating the caller's
wait contract; modify the relevant functions (e.g., create_named_vector and the
corresponding delete_named_vector) to accept a wait parameter (or a WaitUntil)
and propagate it into the update_all_local call instead of using
WaitUntil::from(false), keeping the existing call to
update_collection_vector_config as-is; ensure the signature change is applied
consistently where these functions are invoked so callers can pass the requested
wait flag and schema application will be respected at the shard layer.
| /// Insert a new named vector into the stored collection params. | ||
| /// | ||
| /// Returns `Ok(true)` if the vector was newly added, `Ok(false)` if a vector with the | ||
| /// same name and an identical config already exists (idempotent no-op), or | ||
| /// `Err(BadInput)` if a vector with the same name exists with a conflicting config or | ||
| /// a conflicting kind (dense vs. sparse). This guards against silently overwriting the | ||
| /// stored schema with a different one while shards keep the old one — shard-level | ||
| /// `CreateVectorName` is idempotent and will not re-apply the new config. | ||
| fn add_vector_to_config( | ||
| params: &mut crate::config::CollectionParams, | ||
| vector_name: &VectorNameBuf, | ||
| config: &VectorNameConfig, | ||
| ) -> CollectionResult<()> { |
There was a problem hiding this comment.
Update the doc comment to match the function signature.
The comment still says this helper returns Ok(true) / Ok(false), but the function now returns CollectionResult<()>. That stale contract is easy to misread when touching the call sites later.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/collection/src/collection/vector_name_schema.rs` around lines 108 - 120,
The doc comment for add_vector_to_config is stale: it describes returning
Ok(true)/Ok(false) but the function signature returns CollectionResult<());
update the comment above fn add_vector_to_config (which takes params: &mut
crate::config::CollectionParams, vector_name: &VectorNameBuf, config:
&VectorNameConfig) to accurately describe the current behavior and return type
(i.e., that it returns Ok(()) on success and Err(BadInput) on conflict) and
remove any mention of boolean return values or idempotent true/false semantics
so the documentation matches CollectionResult<()>'s semantics.
* Add empty placeholder vector storage types for named vector CRUD Introduce EmptyDenseVectorStorage and EmptySparseVectorStorage as placeholder storages for newly created named vectors on immutable segments. These report all vectors as deleted, consume no disk space, and are reconstructed from segment config on load via the new VectorStorageType::Empty and SparseVectorStorageType::Empty variants. Key design decisions: - is_on_disk is derived from original user config, not hardcoded - MultiVectorConfig is preserved for multi-vector support - Config mismatch optimizer skips Empty storage to avoid false rebuilds - Quantization delegates normally (handles 0 vectors gracefully) - get_vector includes debug_assert to catch unexpected access Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * [AI] segment-level operations for creating and deleting anmed vectors * [AI] implement named vector creation and deleting in proxy segment * [AI] Step 3: Proxy Segment Handling for Named Vector Operations * [AI] implement for Edge * [AI] implement consensus operations for named vector operations * [AI] refactor VectorNameConfig, remove VectorNameConfigInternal * [AI] handle vector schema inconsistency in raft snapshot recovery * [AI] rest + grpc API * [AI] clippy * [AI] generate openAPI schema * fmt * ci fixes * [AI] fix jwt access test * [AI] nop operation for awaiting of consensus-commited update ops * [AI] move vector name operations into points service * [AI] implement internal api for vector name operations * [AI] change collection-level config along with segment level operation * [AI] vector schema reconceliation instead of error * fmt * missing compile-time option * [AI] integration test * [AI] fix missing JWT tests * [AI] remove NOP * [AI] openapi test * [AI] fix initialization of mutable segment * [AI] more simple integration tests * fmt * [AI] make cluster test a bit harder * [AI] make test less flacky * [AI] rabbit comments * [AI] check params compatibility before writing vector config * [AI] make sure to register vector storages in structure payload index * [AI] vector name validation * lower vector length validation to 200 chars to account for prefix in filename * [AI] proxy segment: prevent stale data leak through optimization * fmt * [AI] filter out removed vectors from proxy response * [AI] handle vector name in proxy * fmt * adjust proxy info based on dropped vectors * [AI] proxy segment: update filters to correct has_vector condition * fmt * clippy * Fix consensus snapshot applicaiton for vector schema --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
This PR enables possibility to create and delete named vectors (both dense and sparse) after collection is already created.
Example:
API allows to specify only minimal parameters (for example, it doesn't allow specifying quantization).
This is done for simplicity, as quantization can always be configured later.
AI Summary
What
Adds the ability to create and delete named vectors on existing collections at runtime — without recreating the collection or triggering segment optimization.
New API Endpoints
Architecture (bottom-up)
Empty placeholder storages — EmptyDenseVectorStorage and EmptySparseVectorStorage are read-only stubs for immutable segments. They report all vectors as deleted and consume no disk space. This avoids copying data when a new vector
name is added to segments that are already built.
Segment-level ops (vector_name_ops.rs) — create_vector_name_impl builds real writable storage on appendable segments and empty placeholders on immutable ones. delete_vector_name_impl removes storage, index, and config from disk.
update_all_vector_names reconciles segments to match a target schema.
Proxy segment — Records create/delete operations as ProxyVectorNameChange entries and flushes them to the wrapped segment during optimization, preserving version ordering.
Shard / WAL — New VectorNameOperations enum (CreateVectorName / DeleteVectorName) is serializable through WAL and forwarded to local/remote shards.
Collection layer (vector_name_schema.rs) — Updates the collection-level config (adds/removes from vectors_config or sparse_vectors_config) and dispatches the operation to all shards.
Consensus — Operations are propagated through Raft. apply_vector_name_schema in state_management.rs reconciles segments during snapshot recovery, creating missing vectors and deleting stale ones.
Edge — Full support in the Edge shard, including in-memory config updates.
Config refactor — Introduces VectorNameConfig (dense/sparse) as a clean public-facing config type, removes the internal VectorNameConfigInternal.
RBAC
Both operations require write + extras permissions. JWT access tests updated.
Tests
Key Design Decisions