From bc86f44a22e50f91efbe793bf9a7d72c78496ef2 Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Thu, 19 Nov 2026 19:55:22 -0800 Subject: [PATCH] vector: count filtered queries by metadata key For each index, the engine counts its QueryVectors calls by the metadata keys of the parsed filter, with their total latency and the operand types each key was compared with, over the last hour in 5-minute buckets. At most 512 indexes and 32 keys per index are kept (an idle key makes room; otherwise the index is marked truncated), and the stats are not exported as metrics labels. The new FilterStats RPC returns an index's stats; the gateway's discovery client forwards it like the other calls. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011UpvafvK8JpagF94MHWqwK --- .../crates/core/src/indexed_filter.rs | 122 +++++++- .../crates/server/src/filter_stats.rs | 236 +++++++++++++++ .../crates/server/src/indexed_keys_tests.rs | 32 +++ seaweed-vector/crates/server/src/lib.rs | 1 + seaweed-vector/crates/server/src/observed.rs | 9 + seaweed-vector/crates/server/src/service.rs | 24 ++ weed/pb/vector.proto | 28 ++ weed/pb/vector_pb/vector.pb.go | 269 ++++++++++++++++-- weed/pb/vector_pb/vector_grpc.pb.go | 42 +++ weed/s3api/s3vectors/discovery.go | 21 ++ 10 files changed, 756 insertions(+), 28 deletions(-) create mode 100644 seaweed-vector/crates/server/src/filter_stats.rs diff --git a/seaweed-vector/crates/core/src/indexed_filter.rs b/seaweed-vector/crates/core/src/indexed_filter.rs index 2a60dffe85..acfef2d4d0 100644 --- a/seaweed-vector/crates/core/src/indexed_filter.rs +++ b/seaweed-vector/crates/core/src/indexed_filter.rs @@ -8,8 +8,9 @@ //! index answers. Everything else, including `$ne` and `$nin`, stays on the //! JSON path. -use std::collections::{BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use anyhow::Result; use jsonb::OwnedJsonb; use lance::Dataset; use lance::deps::datafusion::common::{Column, ScalarValue}; @@ -220,6 +221,105 @@ fn jsonb_text(s: &str) -> Option { Some(value.to_string()) } +/// How a filter compares a key. +pub mod operand { + pub const STRING: u8 = 1; + pub const NUMBER: u8 = 2; + pub const BOOL: u8 = 4; + pub const EXISTS: u8 = 8; +} + +/// The metadata keys `filter` reads, each with the [`operand`] kinds it is +/// compared with. +pub fn filter_keys(dataset: &Dataset, filter: &str) -> Result> { + let mut scanner = dataset.scan(); + scanner.filter(filter)?; + let mut keys = BTreeMap::new(); + if let Some(expr) = scanner.get_expr_filter()? { + collect_keys(&expr, &mut keys); + } + Ok(keys) +} + +fn literal_kind(text: &str) -> u8 { + match serde_json::from_str::(text) { + Ok(serde_json::Value::String(_)) => operand::STRING, + Ok(serde_json::Value::Number(_)) => operand::NUMBER, + Ok(serde_json::Value::Bool(_)) => operand::BOOL, + // json_extract's text of a string with control characters is not + // JSON, but it is quoted. + _ if text.starts_with('"') => operand::STRING, + _ => 0, + } +} + +fn collect_keys(expr: &Expr, keys: &mut BTreeMap) { + let mut note = |path: &str, kind: u8| { + if let Some(key) = json_path_key(path) { + *keys.entry(key).or_default() |= kind; + } + }; + match expr { + Expr::TryCast(cast) if extract(&cast.expr).is_some() => { + note(extract(&cast.expr).unwrap_or_default(), operand::NUMBER); + return; + } + Expr::BinaryExpr(BinaryExpr { left, right, .. }) => { + if let (Some(path), Some(value)) = (extract(left), utf8(right)) { + note(path, literal_kind(value)); + return; + } + } + Expr::InList(list) => { + if let Some(path) = extract(&list.expr) { + let kind = list + .list + .iter() + .filter_map(utf8) + .fold(0, |k, v| k | literal_kind(v)); + note(path, kind); + return; + } + } + Expr::ScalarFunction(f) if is_json_function(f.func.name()) => { + if let [data, path, rest @ ..] = f.args.as_slice() + && is_metadata(data) + && let Some(path) = utf8(path) + { + let kind = match (f.func.name(), rest) { + ("json_exists", _) => operand::EXISTS, + (_, [value]) => utf8(value).map_or(0, literal_kind), + _ => 0, + }; + note(path, kind); + return; + } + } + _ => {} + } + for child in children(expr) { + collect_keys(child, keys); + } +} + +fn extract(expr: &Expr) -> Option<&str> { + json_function(expr, "json_extract") +} + +fn is_json_function(name: &str) -> bool { + matches!(name, "json_extract" | "json_exists" | "json_array_contains") +} + +fn children(expr: &Expr) -> Vec<&Expr> { + use lance::deps::datafusion::common::tree_node::TreeNode; + let mut out = Vec::new(); + let _ = expr.apply_children(|child| { + out.push(child); + Ok(lance::deps::datafusion::common::tree_node::TreeNodeRecursion::Continue) + }); + out +} + #[cfg(test)] mod tests { use super::*; @@ -476,4 +576,24 @@ mod tests { assert!(plan.contains("LabelList"), "{plan}"); assert!(!plan.contains("json_"), "{plan}"); } + + #[tokio::test] + async fn filter_keys_note_how_each_key_is_compared() { + let dir = TempDir::new().unwrap(); + let dataset = dataset(&dir, 100).await; + let filter = format!( + "{} AND TRY_CAST(json_extract(`metadata`, '$[\"n\"]') AS DOUBLE) > 3 AND NOT json_exists(`metadata`, '$[\"a.b\\\"c\"]') AND COALESCE(json_extract(`metadata`, '$[\"f\"]') = 'true', false)", + eq("author", "\"rare\"") + ); + let keys = filter_keys(&dataset, &filter).unwrap(); + assert_eq!( + keys, + BTreeMap::from([ + ("a.b\"c".to_string(), operand::EXISTS), + ("author".to_string(), operand::STRING), + ("f".to_string(), operand::BOOL), + ("n".to_string(), operand::NUMBER), + ]) + ); + } } diff --git a/seaweed-vector/crates/server/src/filter_stats.rs b/seaweed-vector/crates/server/src/filter_stats.rs new file mode 100644 index 0000000000..b886a4ab2b --- /dev/null +++ b/seaweed-vector/crates/server/src/filter_stats.rs @@ -0,0 +1,236 @@ +//! How often, and how slowly, each index's queries filter on each metadata +//! key over the last hour. Keys come from the parsed filter; the number of +//! indexes and of keys per index is bounded, so arbitrary keys cannot grow +//! memory without limit. Not exported as metrics: a key is no label. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use weed_vector_core::indexed_filter::operand; + +use crate::pb::vector as pb; + +const BUCKETS: usize = 12; +const BUCKET: Duration = Duration::from_secs(300); +pub const WINDOW: Duration = Duration::from_secs(BUCKET.as_secs() * BUCKETS as u64); +pub const MAX_INDEXES: usize = 512; +pub const MAX_KEYS_PER_INDEX: usize = 32; + +#[derive(Default, Clone, Copy)] +struct Bucket { + /// The bucket's number since the stats started. + at: u64, + queries: u64, + seconds: f64, +} + +#[derive(Default)] +struct KeyStats { + kinds: u8, + buckets: [Bucket; BUCKETS], +} + +#[derive(Default)] +struct IndexStats { + keys: HashMap, + truncated: bool, + last: u64, +} + +pub struct FilterStats { + start: Instant, + indexes: Mutex>, +} + +impl Default for FilterStats { + fn default() -> Self { + Self::new() + } +} + +impl FilterStats { + pub fn new() -> Self { + Self { + start: Instant::now(), + indexes: Mutex::new(HashMap::new()), + } + } + + fn bucket(&self, now: Instant) -> u64 { + (now.duration_since(self.start).as_secs() / BUCKET.as_secs()) + 1 + } + + /// One query of `index` that took `elapsed` and filtered on `keys`. + pub fn record(&self, index: &str, keys: &BTreeMap, elapsed: Duration) { + self.record_at(index, keys, elapsed, Instant::now()); + } + + fn record_at(&self, index: &str, keys: &BTreeMap, elapsed: Duration, now: Instant) { + if keys.is_empty() { + return; + } + let at = self.bucket(now); + let mut indexes = self.indexes.lock().unwrap(); + if !indexes.contains_key(index) && indexes.len() >= MAX_INDEXES { + let Some(oldest) = indexes + .iter() + .min_by_key(|(_, stats)| stats.last) + .map(|(name, _)| name.clone()) + else { + return; + }; + indexes.remove(&oldest); + } + let stats = indexes.entry(index.to_string()).or_default(); + stats.last = at; + for (key, kinds) in keys { + if !stats.keys.contains_key(key) && stats.keys.len() >= MAX_KEYS_PER_INDEX { + // Make room only by dropping a key no query used in the window. + let idle = stats + .keys + .iter() + .find(|(_, k)| k.buckets.iter().all(|b| b.at + BUCKETS as u64 <= at)) + .map(|(name, _)| name.clone()); + match idle { + Some(idle) => { + stats.keys.remove(&idle); + } + None => { + stats.truncated = true; + continue; + } + } + } + let entry = stats.keys.entry(key.clone()).or_default(); + entry.kinds |= kinds; + let bucket = &mut entry.buckets[(at % BUCKETS as u64) as usize]; + if bucket.at != at { + *bucket = Bucket { + at, + ..Default::default() + }; + } + bucket.queries += 1; + bucket.seconds += elapsed.as_secs_f64(); + } + } + + /// The stats of `index` over the window. + pub fn snapshot(&self, index: &str) -> pb::FilterStatsResponse { + self.snapshot_at(index, Instant::now()) + } + + fn snapshot_at(&self, index: &str, now: Instant) -> pb::FilterStatsResponse { + let at = self.bucket(now); + let window_seconds = now.duration_since(self.start).min(WINDOW).as_secs() as u32; + let indexes = self.indexes.lock().unwrap(); + let Some(stats) = indexes.get(index) else { + return pb::FilterStatsResponse { + window_seconds, + ..Default::default() + }; + }; + let mut keys: Vec = stats + .keys + .iter() + .filter_map(|(key, s)| { + let live = s.buckets.iter().filter(|b| b.at + (BUCKETS as u64) > at); + let (queries, seconds) = + live.fold((0, 0.0), |(q, t), b| (q + b.queries, t + b.seconds)); + (queries > 0).then(|| pb::FilterKeyStats { + key: key.clone(), + queries, + seconds, + string_operand: s.kinds & operand::STRING != 0, + number_operand: s.kinds & operand::NUMBER != 0, + bool_operand: s.kinds & operand::BOOL != 0, + }) + }) + .collect(); + keys.sort_by(|a, b| b.queries.cmp(&a.queries).then(a.key.cmp(&b.key))); + pb::FilterStatsResponse { + keys, + window_seconds, + truncated: stats.truncated, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn keys(pairs: &[(&str, u8)]) -> BTreeMap { + pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect() + } + + #[test] + fn counts_queries_and_latency_per_key_within_the_window() { + let stats = FilterStats::new(); + let t0 = stats.start; + let ms = Duration::from_millis; + stats.record_at("b/i", &keys(&[("author", operand::STRING)]), ms(10), t0); + stats.record_at( + "b/i", + &keys(&[("author", operand::STRING), ("year", operand::NUMBER)]), + ms(30), + t0 + Duration::from_secs(600), + ); + stats.record_at("b/j", &keys(&[("x", operand::BOOL)]), ms(5), t0); + let got = stats.snapshot_at("b/i", t0 + Duration::from_secs(900)); + assert_eq!(got.window_seconds, 900); + assert_eq!(got.keys.len(), 2); + assert_eq!(got.keys[0].key, "author"); + assert_eq!(got.keys[0].queries, 2); + assert!((got.keys[0].seconds - 0.04).abs() < 1e-9); + assert!(got.keys[0].string_operand && !got.keys[0].number_operand); + assert_eq!(got.keys[1].key, "year"); + assert!(got.keys[1].number_operand); + // The first query leaves the window an hour after its bucket. + let later = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(1)); + assert_eq!(later.window_seconds, WINDOW.as_secs() as u32); + assert_eq!(later.keys[0].queries, 1); + let gone = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(900)); + assert!(gone.keys.is_empty()); + assert!(stats.snapshot_at("other", t0).keys.is_empty()); + } + + #[test] + fn indexes_and_keys_are_bounded() { + let stats = FilterStats::new(); + let t0 = stats.start; + for i in 0..MAX_KEYS_PER_INDEX + 5 { + stats.record_at( + "b/i", + &keys(&[(&format!("k{i}"), operand::STRING)]), + Duration::ZERO, + t0, + ); + } + let got = stats.snapshot_at("b/i", t0); + assert_eq!(got.keys.len(), MAX_KEYS_PER_INDEX); + assert!(got.truncated); + // A key idle for the whole window makes room for a new one. + let later = t0 + WINDOW + BUCKET; + stats.record_at( + "b/i", + &keys(&[("new", operand::STRING)]), + Duration::ZERO, + later, + ); + let got = stats.snapshot_at("b/i", later); + assert_eq!(got.keys.len(), 1); + assert_eq!(got.keys[0].key, "new"); + + for i in 0..MAX_INDEXES + 3 { + stats.record_at( + &format!("b/{i}"), + &keys(&[("k", operand::STRING)]), + Duration::ZERO, + later, + ); + } + assert_eq!(stats.indexes.lock().unwrap().len(), MAX_INDEXES); + } +} diff --git a/seaweed-vector/crates/server/src/indexed_keys_tests.rs b/seaweed-vector/crates/server/src/indexed_keys_tests.rs index a77ba197cd..e414ba2ff5 100644 --- a/seaweed-vector/crates/server/src/indexed_keys_tests.rs +++ b/seaweed-vector/crates/server/src/indexed_keys_tests.rs @@ -490,3 +490,35 @@ async fn a_scoped_query_is_exact_within_its_fragments() { }; assert_same(&pairs(got), &pairs(want), "scoped bob"); } + +/// The engine counts each index's filtered queries by key. +#[tokio::test] +async fn queries_are_counted_by_filter_key() { + let fixture = Fixture::new().await; + fixture + .put((0..50).map(|i| row(i, author(i))).collect()) + .await; + for (_, filter, _) in &FILTERS[..3] { + fixture + .query(&fixture.server, 0, filter, 5, &vector_of(1)) + .await; + } + let year = FILTERS[13].1; + fixture + .query(&fixture.server, 0, year, 5, &vector_of(1)) + .await; + let stats = fixture + .server + .filter_stats(Request::new(pb::FilterStatsRequest { + table: Some(fixture.table.clone()), + })) + .await + .unwrap() + .into_inner(); + let author = stats.keys.iter().find(|k| k.key == "author").unwrap(); + assert_eq!(author.queries, 4); + assert!(author.string_operand && !author.number_operand); + let year = stats.keys.iter().find(|k| k.key == "year").unwrap(); + assert_eq!(year.queries, 1); + assert!(year.number_operand && !year.string_operand); +} diff --git a/seaweed-vector/crates/server/src/lib.rs b/seaweed-vector/crates/server/src/lib.rs index b9a42b6ddd..95b5bc78b2 100644 --- a/seaweed-vector/crates/server/src/lib.rs +++ b/seaweed-vector/crates/server/src/lib.rs @@ -1,5 +1,6 @@ //! The VectorService gRPC server the S3 gateway talks to. +pub mod filter_stats; #[cfg(test)] mod indexed_keys_tests; pub mod metrics; diff --git a/seaweed-vector/crates/server/src/observed.rs b/seaweed-vector/crates/server/src/observed.rs index 55aa563efd..4dfc85829c 100644 --- a/seaweed-vector/crates/server/src/observed.rs +++ b/seaweed-vector/crates/server/src/observed.rs @@ -78,6 +78,15 @@ impl VectorService for ObservedService { } result } + async fn filter_stats( + &self, + request: Request, + ) -> Result, Status> { + let mut in_flight = self.metrics.start("FilterStats"); + let result = self.inner.filter_stats(request).await; + in_flight.complete(result.as_ref().err().map(|e| e.code())); + result + } } #[cfg(test)] diff --git a/seaweed-vector/crates/server/src/service.rs b/seaweed-vector/crates/server/src/service.rs index ceaf5ce5e2..7f7756748c 100644 --- a/seaweed-vector/crates/server/src/service.rs +++ b/seaweed-vector/crates/server/src/service.rs @@ -21,6 +21,7 @@ use weed_lance_worker::direct_read::{DirectReads, Wrappers}; use weed_lance_worker::jobs::vector_index::is_vector_table; use weed_lance_worker::metadata_index; use weed_vector_core::index; +use weed_vector_core::indexed_filter; use weed_vector_core::maintenance::SharedLeases; use weed_vector_core::query::{self, Query}; use weed_vector_core::table::VectorTable; @@ -544,6 +545,7 @@ pub struct VectorServer { leases: SharedLeases, nprobes: Option, exact_match_limit: Option, + filter_stats: crate::filter_stats::FilterStats, /// URI schemes a table's location may have. schemes: &'static [&'static str], } @@ -568,6 +570,7 @@ impl VectorServer { leases: SharedLeases::default(), nprobes: None, exact_match_limit: None, + filter_stats: Default::default(), schemes: &["s3"], } } @@ -972,6 +975,7 @@ impl VectorService for VectorServer { &self, request: Request, ) -> Result, Status> { + let started = std::time::Instant::now(); let req = request.into_inner(); let table = req .table @@ -981,6 +985,11 @@ impl VectorService for VectorServer { // while this query runs against it. let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?; let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?; + let filter_keys = if req.filter.is_empty() { + Default::default() + } else { + indexed_filter::filter_keys(&dataset, &req.filter).unwrap_or_default() + }; if req.query_vector.len() != resolved.dimension { return Err(Status::invalid_argument(format!( "query vector carries {} floats, the index dimension is {}", @@ -1081,8 +1090,23 @@ impl VectorService for VectorServer { data: data_map.remove(&hit.key).unwrap_or_default(), }); } + self.filter_stats + .record(&table.id.join("/"), &filter_keys, started.elapsed()); Ok(Response::new(pb::QueryVectorsResponse { vectors })) } + + async fn filter_stats( + &self, + request: Request, + ) -> Result, Status> { + let table = request + .into_inner() + .table + .ok_or_else(|| Status::invalid_argument("missing table"))?; + Ok(Response::new( + self.filter_stats.snapshot(&table.id.join("/")), + )) + } } #[cfg(test)] diff --git a/weed/pb/vector.proto b/weed/pb/vector.proto index 466993f010..64db42d847 100644 --- a/weed/pb/vector.proto +++ b/weed/pb/vector.proto @@ -17,6 +17,9 @@ service VectorService { rpc DeleteVectors(DeleteVectorsRequest) returns (DeleteVectorsResponse); rpc ListVectors(ListVectorsRequest) returns (ListVectorsResponse); rpc QueryVectors(QueryVectorsRequest) returns (QueryVectorsResponse); + // How this engine's queries of an index filtered on each metadata key + // over the last hour. + rpc FilterStats(FilterStatsRequest) returns (FilterStatsResponse); } enum DistanceMetric { @@ -139,3 +142,28 @@ message QueryResult { message QueryVectorsResponse { repeated QueryResult vectors = 1; } + +message FilterStatsRequest { + // Only the id is read. + Table table = 1; +} + +message FilterKeyStats { + string key = 1; + uint64 queries = 2; + // Their total latency. + double seconds = 3; + // The operand types the key was compared with. + bool string_operand = 4; + bool number_operand = 5; + bool bool_operand = 6; +} + +message FilterStatsResponse { + repeated FilterKeyStats keys = 1; + // The stats cover at most this long, less when the engine started later. + uint32 window_seconds = 2; + // Keys of this index not counted because the engine tracks a bounded + // number of them. + bool truncated = 3; +} diff --git a/weed/pb/vector_pb/vector.pb.go b/weed/pb/vector_pb/vector.pb.go index b67556cd4c..4aa43e52be 100644 --- a/weed/pb/vector_pb/vector.pb.go +++ b/weed/pb/vector_pb/vector.pb.go @@ -1077,6 +1077,200 @@ func (x *QueryVectorsResponse) GetVectors() []*QueryResult { return nil } +type FilterStatsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Only the id is read. + Table *Table `protobuf:"bytes,1,opt,name=table,proto3" json:"table,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FilterStatsRequest) Reset() { + *x = FilterStatsRequest{} + mi := &file_vector_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FilterStatsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FilterStatsRequest) ProtoMessage() {} + +func (x *FilterStatsRequest) ProtoReflect() protoreflect.Message { + mi := &file_vector_proto_msgTypes[17] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FilterStatsRequest.ProtoReflect.Descriptor instead. +func (*FilterStatsRequest) Descriptor() ([]byte, []int) { + return file_vector_proto_rawDescGZIP(), []int{17} +} + +func (x *FilterStatsRequest) GetTable() *Table { + if x != nil { + return x.Table + } + return nil +} + +type FilterKeyStats struct { + state protoimpl.MessageState `protogen:"open.v1"` + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Queries uint64 `protobuf:"varint,2,opt,name=queries,proto3" json:"queries,omitempty"` + // Their total latency. + Seconds float64 `protobuf:"fixed64,3,opt,name=seconds,proto3" json:"seconds,omitempty"` + // The operand types the key was compared with. + StringOperand bool `protobuf:"varint,4,opt,name=string_operand,json=stringOperand,proto3" json:"string_operand,omitempty"` + NumberOperand bool `protobuf:"varint,5,opt,name=number_operand,json=numberOperand,proto3" json:"number_operand,omitempty"` + BoolOperand bool `protobuf:"varint,6,opt,name=bool_operand,json=boolOperand,proto3" json:"bool_operand,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FilterKeyStats) Reset() { + *x = FilterKeyStats{} + mi := &file_vector_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FilterKeyStats) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FilterKeyStats) ProtoMessage() {} + +func (x *FilterKeyStats) ProtoReflect() protoreflect.Message { + mi := &file_vector_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FilterKeyStats.ProtoReflect.Descriptor instead. +func (*FilterKeyStats) Descriptor() ([]byte, []int) { + return file_vector_proto_rawDescGZIP(), []int{18} +} + +func (x *FilterKeyStats) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +func (x *FilterKeyStats) GetQueries() uint64 { + if x != nil { + return x.Queries + } + return 0 +} + +func (x *FilterKeyStats) GetSeconds() float64 { + if x != nil { + return x.Seconds + } + return 0 +} + +func (x *FilterKeyStats) GetStringOperand() bool { + if x != nil { + return x.StringOperand + } + return false +} + +func (x *FilterKeyStats) GetNumberOperand() bool { + if x != nil { + return x.NumberOperand + } + return false +} + +func (x *FilterKeyStats) GetBoolOperand() bool { + if x != nil { + return x.BoolOperand + } + return false +} + +type FilterStatsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Keys []*FilterKeyStats `protobuf:"bytes,1,rep,name=keys,proto3" json:"keys,omitempty"` + // The stats cover at most this long, less when the engine started later. + WindowSeconds uint32 `protobuf:"varint,2,opt,name=window_seconds,json=windowSeconds,proto3" json:"window_seconds,omitempty"` + // Keys of this index not counted because the engine tracks a bounded + // number of them. + Truncated bool `protobuf:"varint,3,opt,name=truncated,proto3" json:"truncated,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FilterStatsResponse) Reset() { + *x = FilterStatsResponse{} + mi := &file_vector_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FilterStatsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FilterStatsResponse) ProtoMessage() {} + +func (x *FilterStatsResponse) ProtoReflect() protoreflect.Message { + mi := &file_vector_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FilterStatsResponse.ProtoReflect.Descriptor instead. +func (*FilterStatsResponse) Descriptor() ([]byte, []int) { + return file_vector_proto_rawDescGZIP(), []int{19} +} + +func (x *FilterStatsResponse) GetKeys() []*FilterKeyStats { + if x != nil { + return x.Keys + } + return nil +} + +func (x *FilterStatsResponse) GetWindowSeconds() uint32 { + if x != nil { + return x.WindowSeconds + } + return 0 +} + +func (x *FilterStatsResponse) GetTruncated() bool { + if x != nil { + return x.Truncated + } + return false +} + var File_vector_proto protoreflect.FileDescriptor const file_vector_proto_rawDesc = "" + @@ -1153,13 +1347,26 @@ const file_vector_proto_rawDesc = "" + "\bmetadata\x18\x03 \x01(\v2\x17.google.protobuf.StructR\bmetadata\x12\x12\n" + "\x04data\x18\x04 \x03(\x02R\x04data\"H\n" + "\x14QueryVectorsResponse\x120\n" + - "\avectors\x18\x01 \x03(\v2\x16.vector_pb.QueryResultR\avectors*V\n" + + "\avectors\x18\x01 \x03(\v2\x16.vector_pb.QueryResultR\avectors\"<\n" + + "\x12FilterStatsRequest\x12&\n" + + "\x05table\x18\x01 \x01(\v2\x10.vector_pb.TableR\x05table\"\xc7\x01\n" + + "\x0eFilterKeyStats\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x18\n" + + "\aqueries\x18\x02 \x01(\x04R\aqueries\x12\x18\n" + + "\aseconds\x18\x03 \x01(\x01R\aseconds\x12%\n" + + "\x0estring_operand\x18\x04 \x01(\bR\rstringOperand\x12%\n" + + "\x0enumber_operand\x18\x05 \x01(\bR\rnumberOperand\x12!\n" + + "\fbool_operand\x18\x06 \x01(\bR\vboolOperand\"\x89\x01\n" + + "\x13FilterStatsResponse\x12-\n" + + "\x04keys\x18\x01 \x03(\v2\x19.vector_pb.FilterKeyStatsR\x04keys\x12%\n" + + "\x0ewindow_seconds\x18\x02 \x01(\rR\rwindowSeconds\x12\x1c\n" + + "\ttruncated\x18\x03 \x01(\bR\ttruncated*V\n" + "\x0eDistanceMetric\x12\x1f\n" + "\x1bDISTANCE_METRIC_UNSPECIFIED\x10\x00\x12\x06\n" + "\x02L2\x10\x01\x12\n" + "\n" + "\x06COSINE\x10\x02\x12\x0f\n" + - "\vDOT_PRODUCT\x10\x032\xae\x04\n" + + "\vDOT_PRODUCT\x10\x032\xfc\x04\n" + "\rVectorService\x12L\n" + "\vCreateIndex\x12\x1d.vector_pb.CreateIndexRequest\x1a\x1e.vector_pb.CreateIndexResponse\x12F\n" + "\tDropIndex\x12\x1b.vector_pb.DropIndexRequest\x1a\x1c.vector_pb.DropIndexResponse\x12I\n" + @@ -1169,7 +1376,8 @@ const file_vector_proto_rawDesc = "" + "GetVectors\x12\x1c.vector_pb.GetVectorsRequest\x1a\x1d.vector_pb.GetVectorsResponse\x12R\n" + "\rDeleteVectors\x12\x1f.vector_pb.DeleteVectorsRequest\x1a .vector_pb.DeleteVectorsResponse\x12L\n" + "\vListVectors\x12\x1d.vector_pb.ListVectorsRequest\x1a\x1e.vector_pb.ListVectorsResponse\x12O\n" + - "\fQueryVectors\x12\x1e.vector_pb.QueryVectorsRequest\x1a\x1f.vector_pb.QueryVectorsResponseB2Z0github.com/seaweedfs/seaweedfs/weed/pb/vector_pbb\x06proto3" + "\fQueryVectors\x12\x1e.vector_pb.QueryVectorsRequest\x1a\x1f.vector_pb.QueryVectorsResponse\x12L\n" + + "\vFilterStats\x12\x1d.vector_pb.FilterStatsRequest\x1a\x1e.vector_pb.FilterStatsResponseB2Z0github.com/seaweedfs/seaweedfs/weed/pb/vector_pbb\x06proto3" var ( file_vector_proto_rawDescOnce sync.Once @@ -1184,7 +1392,7 @@ func file_vector_proto_rawDescGZIP() []byte { } var file_vector_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_vector_proto_msgTypes = make([]protoimpl.MessageInfo, 17) +var file_vector_proto_msgTypes = make([]protoimpl.MessageInfo, 20) var file_vector_proto_goTypes = []any{ (DistanceMetric)(0), // 0: vector_pb.DistanceMetric (*Table)(nil), // 1: vector_pb.Table @@ -1204,13 +1412,16 @@ var file_vector_proto_goTypes = []any{ (*QueryVectorsRequest)(nil), // 15: vector_pb.QueryVectorsRequest (*QueryResult)(nil), // 16: vector_pb.QueryResult (*QueryVectorsResponse)(nil), // 17: vector_pb.QueryVectorsResponse - (*structpb.Struct)(nil), // 18: google.protobuf.Struct + (*FilterStatsRequest)(nil), // 18: vector_pb.FilterStatsRequest + (*FilterKeyStats)(nil), // 19: vector_pb.FilterKeyStats + (*FilterStatsResponse)(nil), // 20: vector_pb.FilterStatsResponse + (*structpb.Struct)(nil), // 21: google.protobuf.Struct } var file_vector_proto_depIdxs = []int32{ 1, // 0: vector_pb.CreateIndexRequest.table:type_name -> vector_pb.Table 0, // 1: vector_pb.CreateIndexRequest.distance_metric:type_name -> vector_pb.DistanceMetric 1, // 2: vector_pb.DropIndexRequest.table:type_name -> vector_pb.Table - 18, // 3: vector_pb.Vector.metadata:type_name -> google.protobuf.Struct + 21, // 3: vector_pb.Vector.metadata:type_name -> google.protobuf.Struct 1, // 4: vector_pb.PutVectorsRequest.table:type_name -> vector_pb.Table 6, // 5: vector_pb.PutVectorsRequest.vectors:type_name -> vector_pb.Vector 1, // 6: vector_pb.GetVectorsRequest.table:type_name -> vector_pb.Table @@ -1219,27 +1430,31 @@ var file_vector_proto_depIdxs = []int32{ 1, // 9: vector_pb.ListVectorsRequest.table:type_name -> vector_pb.Table 6, // 10: vector_pb.ListVectorsResponse.vectors:type_name -> vector_pb.Vector 1, // 11: vector_pb.QueryVectorsRequest.table:type_name -> vector_pb.Table - 18, // 12: vector_pb.QueryResult.metadata:type_name -> google.protobuf.Struct + 21, // 12: vector_pb.QueryResult.metadata:type_name -> google.protobuf.Struct 16, // 13: vector_pb.QueryVectorsResponse.vectors:type_name -> vector_pb.QueryResult - 2, // 14: vector_pb.VectorService.CreateIndex:input_type -> vector_pb.CreateIndexRequest - 4, // 15: vector_pb.VectorService.DropIndex:input_type -> vector_pb.DropIndexRequest - 7, // 16: vector_pb.VectorService.PutVectors:input_type -> vector_pb.PutVectorsRequest - 9, // 17: vector_pb.VectorService.GetVectors:input_type -> vector_pb.GetVectorsRequest - 11, // 18: vector_pb.VectorService.DeleteVectors:input_type -> vector_pb.DeleteVectorsRequest - 13, // 19: vector_pb.VectorService.ListVectors:input_type -> vector_pb.ListVectorsRequest - 15, // 20: vector_pb.VectorService.QueryVectors:input_type -> vector_pb.QueryVectorsRequest - 3, // 21: vector_pb.VectorService.CreateIndex:output_type -> vector_pb.CreateIndexResponse - 5, // 22: vector_pb.VectorService.DropIndex:output_type -> vector_pb.DropIndexResponse - 8, // 23: vector_pb.VectorService.PutVectors:output_type -> vector_pb.PutVectorsResponse - 10, // 24: vector_pb.VectorService.GetVectors:output_type -> vector_pb.GetVectorsResponse - 12, // 25: vector_pb.VectorService.DeleteVectors:output_type -> vector_pb.DeleteVectorsResponse - 14, // 26: vector_pb.VectorService.ListVectors:output_type -> vector_pb.ListVectorsResponse - 17, // 27: vector_pb.VectorService.QueryVectors:output_type -> vector_pb.QueryVectorsResponse - 21, // [21:28] is the sub-list for method output_type - 14, // [14:21] is the sub-list for method input_type - 14, // [14:14] is the sub-list for extension type_name - 14, // [14:14] is the sub-list for extension extendee - 0, // [0:14] is the sub-list for field type_name + 1, // 14: vector_pb.FilterStatsRequest.table:type_name -> vector_pb.Table + 19, // 15: vector_pb.FilterStatsResponse.keys:type_name -> vector_pb.FilterKeyStats + 2, // 16: vector_pb.VectorService.CreateIndex:input_type -> vector_pb.CreateIndexRequest + 4, // 17: vector_pb.VectorService.DropIndex:input_type -> vector_pb.DropIndexRequest + 7, // 18: vector_pb.VectorService.PutVectors:input_type -> vector_pb.PutVectorsRequest + 9, // 19: vector_pb.VectorService.GetVectors:input_type -> vector_pb.GetVectorsRequest + 11, // 20: vector_pb.VectorService.DeleteVectors:input_type -> vector_pb.DeleteVectorsRequest + 13, // 21: vector_pb.VectorService.ListVectors:input_type -> vector_pb.ListVectorsRequest + 15, // 22: vector_pb.VectorService.QueryVectors:input_type -> vector_pb.QueryVectorsRequest + 18, // 23: vector_pb.VectorService.FilterStats:input_type -> vector_pb.FilterStatsRequest + 3, // 24: vector_pb.VectorService.CreateIndex:output_type -> vector_pb.CreateIndexResponse + 5, // 25: vector_pb.VectorService.DropIndex:output_type -> vector_pb.DropIndexResponse + 8, // 26: vector_pb.VectorService.PutVectors:output_type -> vector_pb.PutVectorsResponse + 10, // 27: vector_pb.VectorService.GetVectors:output_type -> vector_pb.GetVectorsResponse + 12, // 28: vector_pb.VectorService.DeleteVectors:output_type -> vector_pb.DeleteVectorsResponse + 14, // 29: vector_pb.VectorService.ListVectors:output_type -> vector_pb.ListVectorsResponse + 17, // 30: vector_pb.VectorService.QueryVectors:output_type -> vector_pb.QueryVectorsResponse + 20, // 31: vector_pb.VectorService.FilterStats:output_type -> vector_pb.FilterStatsResponse + 24, // [24:32] is the sub-list for method output_type + 16, // [16:24] is the sub-list for method input_type + 16, // [16:16] is the sub-list for extension type_name + 16, // [16:16] is the sub-list for extension extendee + 0, // [0:16] is the sub-list for field type_name } func init() { file_vector_proto_init() } @@ -1253,7 +1468,7 @@ func file_vector_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_vector_proto_rawDesc), len(file_vector_proto_rawDesc)), NumEnums: 1, - NumMessages: 17, + NumMessages: 20, NumExtensions: 0, NumServices: 1, }, diff --git a/weed/pb/vector_pb/vector_grpc.pb.go b/weed/pb/vector_pb/vector_grpc.pb.go index 1eaf64fe5f..0cc68b3e1f 100644 --- a/weed/pb/vector_pb/vector_grpc.pb.go +++ b/weed/pb/vector_pb/vector_grpc.pb.go @@ -26,6 +26,7 @@ const ( VectorService_DeleteVectors_FullMethodName = "/vector_pb.VectorService/DeleteVectors" VectorService_ListVectors_FullMethodName = "/vector_pb.VectorService/ListVectors" VectorService_QueryVectors_FullMethodName = "/vector_pb.VectorService/QueryVectors" + VectorService_FilterStats_FullMethodName = "/vector_pb.VectorService/FilterStats" ) // VectorServiceClient is the client API for VectorService service. @@ -43,6 +44,9 @@ type VectorServiceClient interface { DeleteVectors(ctx context.Context, in *DeleteVectorsRequest, opts ...grpc.CallOption) (*DeleteVectorsResponse, error) ListVectors(ctx context.Context, in *ListVectorsRequest, opts ...grpc.CallOption) (*ListVectorsResponse, error) QueryVectors(ctx context.Context, in *QueryVectorsRequest, opts ...grpc.CallOption) (*QueryVectorsResponse, error) + // How this engine's queries of an index filtered on each metadata key + // over the last hour. + FilterStats(ctx context.Context, in *FilterStatsRequest, opts ...grpc.CallOption) (*FilterStatsResponse, error) } type vectorServiceClient struct { @@ -123,6 +127,16 @@ func (c *vectorServiceClient) QueryVectors(ctx context.Context, in *QueryVectors return out, nil } +func (c *vectorServiceClient) FilterStats(ctx context.Context, in *FilterStatsRequest, opts ...grpc.CallOption) (*FilterStatsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(FilterStatsResponse) + err := c.cc.Invoke(ctx, VectorService_FilterStats_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // VectorServiceServer is the server API for VectorService service. // All implementations must embed UnimplementedVectorServiceServer // for forward compatibility. @@ -138,6 +152,9 @@ type VectorServiceServer interface { DeleteVectors(context.Context, *DeleteVectorsRequest) (*DeleteVectorsResponse, error) ListVectors(context.Context, *ListVectorsRequest) (*ListVectorsResponse, error) QueryVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error) + // How this engine's queries of an index filtered on each metadata key + // over the last hour. + FilterStats(context.Context, *FilterStatsRequest) (*FilterStatsResponse, error) mustEmbedUnimplementedVectorServiceServer() } @@ -169,6 +186,9 @@ func (UnimplementedVectorServiceServer) ListVectors(context.Context, *ListVector func (UnimplementedVectorServiceServer) QueryVectors(context.Context, *QueryVectorsRequest) (*QueryVectorsResponse, error) { return nil, status.Error(codes.Unimplemented, "method QueryVectors not implemented") } +func (UnimplementedVectorServiceServer) FilterStats(context.Context, *FilterStatsRequest) (*FilterStatsResponse, error) { + return nil, status.Error(codes.Unimplemented, "method FilterStats not implemented") +} func (UnimplementedVectorServiceServer) mustEmbedUnimplementedVectorServiceServer() {} func (UnimplementedVectorServiceServer) testEmbeddedByValue() {} @@ -316,6 +336,24 @@ func _VectorService_QueryVectors_Handler(srv interface{}, ctx context.Context, d return interceptor(ctx, in, info, handler) } +func _VectorService_FilterStats_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(FilterStatsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(VectorServiceServer).FilterStats(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: VectorService_FilterStats_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(VectorServiceServer).FilterStats(ctx, req.(*FilterStatsRequest)) + } + return interceptor(ctx, in, info, handler) +} + // VectorService_ServiceDesc is the grpc.ServiceDesc for VectorService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -351,6 +389,10 @@ var VectorService_ServiceDesc = grpc.ServiceDesc{ MethodName: "QueryVectors", Handler: _VectorService_QueryVectors_Handler, }, + { + MethodName: "FilterStats", + Handler: _VectorService_FilterStats_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "vector.proto", diff --git a/weed/s3api/s3vectors/discovery.go b/weed/s3api/s3vectors/discovery.go index 70963ba9f7..a243141503 100644 --- a/weed/s3api/s3vectors/discovery.go +++ b/weed/s3api/s3vectors/discovery.go @@ -326,6 +326,27 @@ func (d *vectorDiscovery) QueryVectors(ctx context.Context, in *vector_pb.QueryV return nil, err } +func (d *vectorDiscovery) FilterStats(ctx context.Context, in *vector_pb.FilterStatsRequest, opts ...grpc.CallOption) (resp *vector_pb.FilterStatsResponse, err error) { + for attempt := 0; attempt < 2; attempt++ { + var c vector_pb.VectorServiceClient + if c, err = d.cli(ctx); err != nil { + return nil, err + } + resp, err = c.FilterStats(ctx, in, opts...) + if isTransportError(err) { + d.reset(c) + } + d.release(c) + if err == nil { + return resp, nil + } + if !isTransportError(err) { + return nil, err + } + } + return nil, err +} + func discoverVectorServers(masters []pb.ServerAddress, grpcDialOption grpc.DialOption, filerGroup string) []string { for _, master := range masters { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)