Compare commits

...
Author SHA1 Message Date
user.email 04cb124275 vector: evaluate metadata filters row-wise on legacy text columns
When the stored metadata column is not jsonb, the S3 Vectors filter
document is checked per row over a key+metadata scan and the ANN query is
constrained to the matching keys. NULL rows and missing fields compare as
SQL NULL: nothing matches, including $ne/$nin.
2026-10-26 18:04:40 -07:00
user.email 1aaadc21b8 vector: carry the raw filter document to the engine
Indexes written before metadata became jsonb keep a plain Utf8 column, and
lance's json_get_* filter functions only plan against LargeBinary. Send the
S3 Vectors filter document next to the translated SQL so the engine can fall
back to row-wise evaluation there; the SQL field stays for engines that only
know it.
2026-10-26 18:01:49 -07:00
Devin 308e3c91d1 vector: store index metadata as lance jsonb so filters resolve
The metadata field was plain Utf8, but the filter functions lance's
planner registers (json_get_string, json_get_float, json_exists) take a
LargeBinary jsonb column, so QueryVectors with a metadata filter failed
to plan. Declare the field with the arrow.json extension — lance encodes
it to jsonb on write and back on read — and encode the batch's strings
when the stored column is LargeBinary. Also rename the filter's
json_get_str call to json_get_string, the name lance registers.
2026-10-26 17:23:45 -07:00
Devin 25880a7279 vector: take the list item field from the schema when batching vectors
Lance stores the fixed-size list item as nullable even when the write
schema declared it non-null, so PutVectors built batches that no longer
matched: expected FixedSizeList(4 x Float32) but found FixedSizeList(4 x
non-null Float32).
2026-10-26 17:21:54 -07:00
Devin 5f79d55fb5 test/vectors: give the vector server static storage credentials
The e2e harness ran weed-vector-server without credentials, so lance's
AWS object store fell back to IMDS and CreateIndex died on the runner's
411 from the token endpoint. Point it at the test credentials the s3
gateway now reads from s3.json.
2026-10-26 17:21:36 -07:00
8 changed files with 320 additions and 24 deletions

No files matched your search

+1
View File
@@ -6486,6 +6486,7 @@ dependencies = [
"clap",
"futures",
"lance",
"lance-arrow",
"lance-linalg",
"prost",
"prost-types",
+1
View File
@@ -16,6 +16,7 @@ path = "src/main.rs"
weed-vector-core = { path = "../core" }
weed-lance-worker = { path = "../../../seaweed-worker/crates/lance" }
lance = { version = "10", default-features = false, features = ["aws"] }
lance-arrow = "10"
lance-linalg = "10"
arrow-array = "58"
arrow-cast = "58"
+268 -21
View File
@@ -1,4 +1,4 @@
use anyhow::{Result, bail};
use anyhow::{Context, Result, bail};
use arrow_array::{Array, ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use futures::TryStreamExt;
@@ -10,7 +10,7 @@ use lance::io::ObjectStoreParams;
use lance::io::StorageOptionsAccessor;
use lance_linalg::distance::DistanceType;
use prost_types::{ListValue, Struct, Value, value::Kind};
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use tonic::{Request, Response, Status};
use weed_lance_worker::catalog::NamespaceClient;
@@ -74,17 +74,19 @@ fn schema_for(
.into_iter()
.collect(),
);
let mut metadata_field = Field::new(METADATA_COLUMN, DataType::Utf8, true);
// The arrow.json extension marks the Utf8 column as JSON: lance stores it
// as jsonb, which is what the json_get_* filter functions take.
let mut metadata_meta = HashMap::from_iter([(
"ARROW:extension:name".to_string(),
"arrow.json".to_string(),
)]);
if !non_filterable.is_empty() {
metadata_field = metadata_field.with_metadata(
[(
"non_filterable_metadata_keys".to_string(),
serde_json::to_string(non_filterable).unwrap_or_default(),
)]
.into_iter()
.collect(),
metadata_meta.insert(
"non_filterable_metadata_keys".to_string(),
serde_json::to_string(non_filterable).unwrap_or_default(),
);
}
let metadata_field = Field::new(METADATA_COLUMN, DataType::Utf8, true).with_metadata(metadata_meta);
Arc::new(Schema::new(vec![
Field::new(KEY_COLUMN, DataType::Utf8, false),
vector_field,
@@ -110,8 +112,18 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
.flat_map(|v| v.data.iter().copied())
.collect::<Vec<_>>();
let values: ArrayRef = Arc::new(Float32Array::from(flat));
// Lance stores the list item as nullable even when the write schema
// declared it non-null, so the child field must come from the batch's
// schema rather than a fixed declaration.
let DataType::FixedSizeList(item_field, _) = schema
.field_with_name(VECTOR_COLUMN)
.map_err(anyhow::Error::from)?
.data_type()
else {
bail!("vector column is not a fixed-size list");
};
let vectors_array = FixedSizeListArray::try_new(
Field::new("item", DataType::Float32, false).into(),
item_field.clone(),
dimension as i32,
values,
None,
@@ -125,13 +137,20 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
.transpose()
})
.collect::<Result<Vec<_>, _>>()?;
// The stored column is lance's jsonb (LargeBinary) once the field carries
// the arrow.json extension; encode the strings, else keep the Utf8 batch.
let metadata_array: ArrayRef = match schema
.field_with_name(METADATA_COLUMN)
.map(|f| f.data_type())
{
Ok(DataType::LargeBinary) => {
Arc::new(lance_arrow::json::JsonArray::try_from_iter(metas)?.into_inner())
}
_ => Arc::new(StringArray::from(metas)),
};
RecordBatch::try_new(
schema,
vec![
Arc::new(keys),
Arc::new(vectors_array),
Arc::new(StringArray::from(metas)),
],
vec![Arc::new(keys), Arc::new(vectors_array), metadata_array],
)
.map_err(Into::into)
}
@@ -199,6 +218,124 @@ fn key_list(keys: &[String]) -> String {
)
}
// The json_get_* functions lance registers only take a LargeBinary jsonb
// column; on an index written before metadata became jsonb the stored column
// is plain Utf8 and the SQL filter fails to plan. There the filter document
// is evaluated per row and the query is constrained to the matching keys.
fn metadata_is_jsonb(dataset: &Dataset) -> bool {
let schema: arrow_schema::Schema = dataset.schema().into();
matches!(
schema
.field_with_name(METADATA_COLUMN)
.map(|f| f.data_type()),
Ok(DataType::LargeBinary)
)
}
async fn matching_keys(dataset: &Dataset, filter_json: &str) -> Result<Vec<String>> {
let filter: serde_json::Value =
serde_json::from_str(filter_json).context("filter_json is not a JSON document")?;
let mut scanner = dataset.scan();
scanner.project(&[KEY_COLUMN, METADATA_COLUMN])?;
let mut stream = scanner.try_into_stream().await?;
let mut keys = Vec::new();
while let Some(batch) = stream.try_next().await? {
let keys_col = batch
.column_by_name(KEY_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>());
let metas = batch
.column_by_name(METADATA_COLUMN)
.and_then(|c| c.as_any().downcast_ref::<StringArray>());
let (Some(keys_col), Some(metas)) = (keys_col, metas) else {
continue;
};
for i in 0..batch.num_rows() {
if metas.is_null(i) {
continue;
}
let Ok(meta) = serde_json::from_str::<serde_json::Value>(metas.value(i)) else {
continue;
};
if filter_matches(&filter, &meta) {
keys.push(keys_col.value(i).to_string());
}
}
}
Ok(keys)
}
fn filter_matches(filter: &serde_json::Value, meta: &serde_json::Value) -> bool {
let Some(clauses) = filter.as_object() else {
return false;
};
clauses.iter().all(|(key, cond)| match key.as_str() {
"$and" => cond
.as_array()
.is_some_and(|subs| subs.iter().all(|s| filter_matches(s, meta))),
"$or" => cond
.as_array()
.is_some_and(|subs| subs.iter().any(|s| filter_matches(s, meta))),
_ if key.starts_with('$') => false,
_ => field_matches(meta.get(key), cond),
})
}
fn field_matches(value: Option<&serde_json::Value>, cond: &serde_json::Value) -> bool {
let Some(ops) = cond.as_object() else {
return json_eq(value, cond);
};
ops.iter().all(|(op, operand)| match op.as_str() {
"$exists" => value.is_some() == operand.as_bool().unwrap_or_default(),
"$eq" => json_eq(value, operand),
"$ne" => value.is_some() && !json_eq(value, operand),
"$in" => operand
.as_array()
.is_some_and(|list| list.iter().any(|item| json_eq(value, item))),
"$nin" => {
value.is_some()
&& operand
.as_array()
.is_some_and(|list| !list.iter().any(|item| json_eq(value, item)))
}
"$lt" | "$lte" | "$gt" | "$gte" => json_cmp(value, operand, op.as_str()),
_ => false,
})
}
// json_get_string semantics: strings read back as-is, scalars take their text
// form, documents serialize; a JSON null reads as NULL and never compares.
fn json_text(v: &serde_json::Value) -> Option<String> {
match v {
serde_json::Value::Null => None,
serde_json::Value::String(s) => Some(s.clone()),
_ => Some(v.to_string()),
}
}
fn json_eq(value: Option<&serde_json::Value>, operand: &serde_json::Value) -> bool {
match (value.and_then(json_text), json_text(operand)) {
(Some(a), Some(b)) => a == b,
_ => false,
}
}
fn json_cmp(value: Option<&serde_json::Value>, operand: &serde_json::Value, op: &str) -> bool {
let numeric = |v: &serde_json::Value| {
v.as_f64()
.or_else(|| v.as_str().and_then(|s| s.parse().ok()))
};
let (Some(v), Some(o)) = (value.and_then(numeric), numeric(operand)) else {
return false;
};
match op {
"$lt" => v < o,
"$lte" => v <= o,
"$gt" => v > o,
"$gte" => v >= o,
_ => false,
}
}
fn rows_as_vectors(
batches: &[RecordBatch],
return_data: bool,
@@ -483,14 +620,26 @@ impl VectorService for VectorServer {
Some("DOT_PRODUCT") => DistanceType::Dot,
_ => DistanceType::L2,
};
let mut filter = if req.filter.is_empty() {
None
} else {
Some(req.filter)
};
if filter.is_some() && !req.filter_json.is_empty() && !metadata_is_jsonb(&dataset) {
let keys = matching_keys(&dataset, &req.filter_json)
.await
.map_err(internal)?;
if keys.is_empty() {
return Ok(Response::new(pb::QueryVectorsResponse {
vectors: Vec::new(),
}));
}
filter = Some(key_list(&keys));
}
let query = Query {
vector: req.query_vector,
k: req.top_k as usize,
filter: if req.filter.is_empty() {
None
} else {
Some(req.filter)
},
filter,
postfilter: req.postfilter,
distance,
nprobes: None,
@@ -612,4 +761,102 @@ mod tests {
];
assert!(batch_of(&vectors, 4, schema).is_err());
}
#[test]
fn filter_matches_the_gateway_operators() {
let meta = meta_of(r#"{"color":"red","n":3,"flag":true}"#);
assert!(filter_matches(&meta_of(r#"{"color":"red"}"#), &meta));
assert!(filter_matches(
&meta_of(r#"{"color":{"$eq":"red"}}"#),
&meta
));
assert!(!filter_matches(
&meta_of(r#"{"color":{"$ne":"red"}}"#),
&meta
));
assert!(filter_matches(
&meta_of(r#"{"color":{"$in":["red","blue"]}}"#),
&meta
));
assert!(!filter_matches(
&meta_of(r#"{"color":{"$nin":["red"]}}"#),
&meta
));
assert!(filter_matches(
&meta_of(r#"{"missing":{"$exists":false}}"#),
&meta
));
assert!(!filter_matches(
&meta_of(r#"{"missing":{"$exists":true}}"#),
&meta
));
assert!(filter_matches(
&meta_of(r#"{"n":{"$gte":3,"$lt":4}}"#),
&meta
));
assert!(!filter_matches(&meta_of(r#"{"n":{"$gt":3}}"#), &meta));
// Comparisons on a missing field read as NULL: nothing matches,
// not even $ne/$nin.
assert!(!filter_matches(
&meta_of(r#"{"missing":{"$ne":"x"}}"#),
&meta
));
assert!(!filter_matches(
&meta_of(r#"{"missing":{"$nin":["x"]}}"#),
&meta
));
let or = meta_of(r#"{"$or":[{"color":"blue"},{"n":{"$lt":4}}]}"#);
assert!(filter_matches(&or, &meta));
let and = meta_of(r#"{"$and":[{"color":"red"},{"flag":true}]}"#);
assert!(filter_matches(&and, &meta));
}
fn meta_of(json: &str) -> serde_json::Value {
serde_json::from_str(json).unwrap()
}
async fn legacy_dataset() -> Dataset {
let schema = Arc::new(Schema::new(vec![
Field::new(KEY_COLUMN, DataType::Utf8, false),
Field::new(METADATA_COLUMN, DataType::Utf8, true),
]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(vec!["a", "b", "c"])),
Arc::new(StringArray::from(vec![
Some(r#"{"color":"red","n":3}"#),
Some(r#"{"color":"blue","n":7}"#),
None,
])),
],
)
.unwrap();
let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch)].into_iter(), schema);
Dataset::write(reader, "memory://legacy-meta-index", None)
.await
.unwrap()
}
#[tokio::test]
async fn matching_keys_scans_utf8_metadata_rows() {
let dataset = legacy_dataset().await;
assert!(!metadata_is_jsonb(&dataset));
assert_eq!(
matching_keys(&dataset, r#"{"color":"red"}"#).await.unwrap(),
vec!["a".to_string()]
);
assert_eq!(
matching_keys(&dataset, r#"{"n":{"$gte":3}}"#)
.await
.unwrap(),
vec!["a".to_string(), "b".to_string()]
);
assert!(
matching_keys(&dataset, r#"{"color":"green"}"#)
.await
.unwrap()
.is_empty()
);
}
}
+3
View File
@@ -19,6 +19,7 @@ PIDS+=($!)
./weed s3 \
-filer 127.0.0.1:8888 \
-config s3.json \
-ip 127.0.0.1 \
-ip.bind 127.0.0.1 \
-port 8334 \
@@ -29,6 +30,8 @@ PIDS+=($!)
./weed-vector-server \
--namespace http://127.0.0.1:9102 \
--storage-option aws_access_key_id=test \
--storage-option aws_secret_access_key=test \
--listen 127.0.0.1:9301 &
PIDS+=($!)
+20
View File
@@ -0,0 +1,20 @@
{
"identities": [
{
"name": "admin",
"credentials": [
{
"accessKey": "test",
"secretKey": "test"
}
],
"actions": [
"Admin",
"Read",
"List",
"Tagging",
"Write"
]
}
]
}
+5
View File
@@ -108,6 +108,11 @@ message QueryVectorsRequest {
// `metadata` column, so the gateway translates S3 Vectors filter
// expressions onto it before they land here.
string filter = 4;
// The raw S3 Vectors filter document. Indexes whose metadata column
// predates lance's jsonb storage cannot plan json_get_* calls; the engine
// evaluates this row-wise instead and constrains the scan by key. Gateways
// still send `filter` for engines that only know the SQL form.
string filter_json = 9;
// Lance's post-filter escape hatch; off prefilters, matching S3 Vectors.
bool postfilter = 5;
bool return_metadata = 6;
+16 -2
View File
@@ -823,6 +823,11 @@ type QueryVectorsRequest struct {
// `metadata` column, so the gateway translates S3 Vectors filter
// expressions onto it before they land here.
Filter string `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"`
// The raw S3 Vectors filter document. Indexes whose metadata column
// predates lance's jsonb storage cannot plan json_get_* calls; the engine
// evaluates this row-wise instead and constrains the scan by key. Gateways
// still send `filter` for engines that only know the SQL form.
FilterJson string `protobuf:"bytes,9,opt,name=filter_json,json=filterJson,proto3" json:"filter_json,omitempty"`
// Lance's post-filter escape hatch; off prefilters, matching S3 Vectors.
Postfilter bool `protobuf:"varint,5,opt,name=postfilter,proto3" json:"postfilter,omitempty"`
ReturnMetadata bool `protobuf:"varint,6,opt,name=return_metadata,json=returnMetadata,proto3" json:"return_metadata,omitempty"`
@@ -890,6 +895,13 @@ func (x *QueryVectorsRequest) GetFilter() string {
return ""
}
func (x *QueryVectorsRequest) GetFilterJson() string {
if x != nil {
return x.FilterJson
}
return ""
}
func (x *QueryVectorsRequest) GetPostfilter() bool {
if x != nil {
return x.Postfilter
@@ -1082,12 +1094,14 @@ const file_vector_proto_rawDesc = "" +
"\x13ListVectorsResponse\x12+\n" +
"\avectors\x18\x01 \x03(\v2\x11.vector_pb.VectorR\avectors\x12\x1d\n" +
"\n" +
"next_token\x18\x02 \x01(\tR\tnextToken\"\xa0\x02\n" +
"next_token\x18\x02 \x01(\tR\tnextToken\"\xc1\x02\n" +
"\x13QueryVectorsRequest\x12&\n" +
"\x05table\x18\x01 \x01(\v2\x10.vector_pb.TableR\x05table\x12!\n" +
"\fquery_vector\x18\x02 \x03(\x02R\vqueryVector\x12\x13\n" +
"\x05top_k\x18\x03 \x01(\rR\x04topK\x12\x16\n" +
"\x06filter\x18\x04 \x01(\tR\x06filter\x12\x1e\n" +
"\x06filter\x18\x04 \x01(\tR\x06filter\x12\x1f\n" +
"\vfilter_json\x18\t \x01(\tR\n" +
"filterJson\x12\x1e\n" +
"\n" +
"postfilter\x18\x05 \x01(\bR\n" +
"postfilter\x12'\n" +
+6 -1
View File
@@ -788,7 +788,7 @@ func filterExpr(filter map[string]interface{}) (string, error) {
}
func fieldClause(field string, cond interface{}) (string, error) {
col := fmt.Sprintf("json_get_str(`metadata`, '%s')", strings.ReplaceAll(field, "'", "''"))
col := fmt.Sprintf("json_get_string(`metadata`, '%s')", strings.ReplaceAll(field, "'", "''"))
switch c := cond.(type) {
case map[string]interface{}:
parts := []string{}
@@ -899,11 +899,16 @@ func (s *Server) handleQueryVectors(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "ValidationException", "topK must be non-negative")
return
}
var filterJSON []byte
if len(req.Filter) > 0 {
filterJSON, _ = json.Marshal(req.Filter)
}
resp, err := s.vectors.QueryVectors(r.Context(), &vector_pb.QueryVectorsRequest{
Table: tableID(arns.bucket, arns.index),
QueryVector: queryVector,
TopK: uint32(req.TopK),
Filter: filter,
FilterJson: string(filterJSON),
ReturnMetadata: req.ReturnMetadata,
ReturnDistance: req.ReturnDistance,
})