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
14 changed files with 359 additions and 224 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"
]
}
]
}
+16 -41
View File
@@ -45,12 +45,6 @@ type LockClient struct {
// snapshot) but short enough that a write fails instead of hanging
// forever.
noLockServerRetryPeriod time.Duration
// lockRpcTimeout bounds a single DistributedLock attempt: a ring member
// reachable from the masters but not from this filer would otherwise
// block an attempt on the TCP connect timeout, far past
// noLockServerRetryPeriod.
lockRpcTimeout time.Duration
}
func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *LockClient {
@@ -61,7 +55,6 @@ func NewLockClient(grpcDialOption grpc.DialOption, seedFiler pb.ServerAddress) *
seedFiler: seedFiler,
priorWindow: 5 * time.Second,
noLockServerRetryPeriod: 15 * time.Second,
lockRpcTimeout: 10 * time.Second,
}
}
@@ -311,34 +304,26 @@ func (lc *LockClient) StartLongLivedLock(key string, owner string, onLockOwnerCh
// waiter must pick it up promptly, otherwise cross-mount write handoff stalls
// long enough to time out clients.
func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
// The retry window bounds acquisition as a whole: the clock starts
// before the first attempt and each attempt gets what is left of it, so
// a bounded attempt cannot burn the window inside one call.
unavailableSince := time.Now()
var unavailableSince time.Time
for lock.renewToken == "" {
attemptTimeout := lock.lc.lockRpcTimeout
if remaining := lock.lc.noLockServerRetryPeriod - time.Since(unavailableSince); remaining < attemptTimeout {
if remaining <= 0 {
return fmt.Errorf("no lock server within %s", lock.lc.noLockServerRetryPeriod)
}
attemptTimeout = remaining
}
err := lock.attemptToLockWithin(lockDuration, attemptTimeout)
err := lock.AttemptToLock(lockDuration)
if err == nil {
unavailableSince = time.Now()
unavailableSince = time.Time{}
continue
}
glog.V(1).Infof("create lock %s: %v", lock.key, err)
if strings.Contains(err.Error(), "lock already owned") {
// Ordinary contention: a reachable server holds the lock, so
// waiting is the point and has no bound.
unavailableSince = time.Now()
unavailableSince = time.Time{}
continue
}
// Anything else — "no lock server found", a dead ring member refusing
// connections — is a systemic fault waiting cannot fix; give up once
// it persists past the retry period.
if time.Since(unavailableSince) > lock.lc.noLockServerRetryPeriod {
if unavailableSince.IsZero() {
unavailableSince = time.Now()
} else if time.Since(unavailableSince) > lock.lc.noLockServerRetryPeriod {
return err
}
}
@@ -346,12 +331,8 @@ func (lock *LiveLock) retryUntilLocked(lockDuration time.Duration) error {
}
func (lock *LiveLock) AttemptToLock(lockDuration time.Duration) error {
return lock.attemptToLockWithin(lockDuration, lock.lc.lockRpcTimeout)
}
func (lock *LiveLock) attemptToLockWithin(lockDuration, attemptTimeout time.Duration) error {
glog.V(4).Infof("LOCK: AttemptToLock key=%s owner=%s", lock.key, lock.self)
errorMessage, err := lock.doLock(lockDuration, attemptTimeout)
errorMessage, err := lock.doLock(lockDuration)
if err != nil {
glog.V(1).Infof("LOCK: doLock failed for key=%s: %v", lock.key, err)
time.Sleep(time.Second)
@@ -428,20 +409,15 @@ func (lock *LiveLock) Stop() error {
return lock.StopShortLivedLock()
}
func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorMessage string, err error) {
func (lock *LiveLock) doLock(lockDuration time.Duration) (errorMessage string, err error) {
glog.V(4).Infof("LOCK: doLock calling DistributedLock - key=%s filer=%s owner=%s",
lock.key, lock.hostFiler, lock.self)
previousHostFiler := lock.hostFiler
previousOwner := lock.owner
// Bound the whole attempt — connection acquisition included — so an
// unreachable owner fails within the retry window.
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
defer cancel()
err = pb.WithGrpcClient(ctx, false, 0, func(grpcConnection *grpc.ClientConn) error {
client := filer_pb.NewSeaweedFilerClient(grpcConnection)
resp, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
err = pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.DistributedLock(context.Background(), &filer_pb.LockRequest{
Name: lock.key,
SecondsToLock: int64(lockDuration.Seconds()),
RenewToken: lock.renewToken,
@@ -457,11 +433,9 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
lock.consecutiveFailures = 0 // Reset failure counter on success
glog.V(4).Infof("LOCK: Got renewToken for key=%s", lock.key)
} else {
// the request may have renewed the lease server-side before its
// response was lost: the last token can still be valid, so the
// next attempt retries with it. A definitive rejection clears it
// through the response's empty RenewToken.
glog.V(1).Infof("LOCK: no response for key=%s (err=%v)", lock.key, err)
//this can be retried. Need to remember the last valid renewToken
lock.renewToken = ""
glog.V(1).Infof("LOCK: Cleared renewToken for key=%s (err=%v)", lock.key, err)
}
if resp != nil {
errorMessage = resp.Error
@@ -485,7 +459,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
}
}
return err
}, lock.hostFiler.ToGrpcAddress(), false, lock.grpcDialOption)
})
if err != nil && !lock.hostFiler.Equals(lock.lc.seedFiler) {
lock.consecutiveFailures++
@@ -495,6 +469,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
lock.consecutiveFailures, lock.key, lock.hostFiler, lock.lc.seedFiler)
lock.hostFiler = lock.lc.seedFiler
lock.consecutiveFailures = 0
lock.renewToken = ""
}
}
-79
View File
@@ -286,85 +286,6 @@ func TestNewShortLivedLockFailsFastOnUnreachableFiler(t *testing.T) {
}
}
type hangingLockFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
}
func (s *hangingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(30 * time.Second):
return nil, fmt.Errorf("test: server never answered")
}
}
// A failed attempt keeps the token it sent: the request may have renewed the
// lease server-side before its response was lost, and a retry with the last
// token can still succeed. Only a definitive rejection may clear it.
func TestDoLockKeepsRenewTokenOnError(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
addr := listener.Addr().String()
listener.Close()
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
host, port, err := net.SplitHostPort(addr)
if err != nil {
t.Fatalf("split host port: %v", err)
}
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
lock := &LiveLock{
key: "test-key",
renewToken: "tok",
hostFiler: pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)),
grpcDialOption: dialOption,
lc: lc,
}
if _, err := lock.doLock(time.Second, 50*time.Millisecond); err == nil {
t.Fatal("expected the attempt to fail against a dead member")
}
if lock.renewToken != "tok" {
t.Errorf("renewToken = %q, want it kept for the next attempt", lock.renewToken)
}
}
// A ring member that accepts connections but never answers stalls the caller
// the same way a partially partitioned peer does: each attempt must fail
// within the per-attempt bound so the retry window can give up.
func TestNewShortLivedLockBoundsHangingAttempt(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, &hangingLockFiler{})
go grpcServer.Serve(listener)
defer grpcServer.Stop()
dialOption := grpc.WithTransportCredentials(insecure.NewCredentials())
host, port, err := net.SplitHostPort(listener.Addr().String())
if err != nil {
t.Fatalf("split host port: %v", err)
}
lc := NewLockClient(dialOption, pb.ServerAddress(fmt.Sprintf("%s:0.%s", host, port)))
lc.noLockServerRetryPeriod = 200 * time.Millisecond
lc.lockRpcTimeout = 50 * time.Millisecond
start := time.Now()
lock := lc.NewShortLivedLock("test-key", "test-owner")
elapsed := time.Since(start)
if lock != nil {
t.Fatal("expected nil lock when the ring member never answers")
}
if elapsed > 5*time.Second {
t.Fatalf("lock acquisition took %v, expected it bounded by the per-attempt timeout", elapsed)
}
}
// LiveLock.generation is a fencing token written and read with 64-bit atomic
// operations. On 32-bit platforms (GOARCH=386 and GOARCH=arm) a 64-bit atomic
// op requires an 8-byte-aligned address, which Go only guarantees for the
@@ -46,7 +46,7 @@ func (dlm *DistributedLockManager) LockWithTimeout(key string, expiredAtNs int64
// ring update and lock transfer completion — the old primary remains
// authoritative for locks it still holds.
if token != "" {
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && (lock.Token == token || lock.PrevToken == token) {
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && lock.Token == token {
var seq int64
lockOwner, renewToken, generation, seq, err = dlm.lockManager.Lock(key, expiredAtNs, token, owner)
if err == nil && renewToken != "" {
@@ -95,7 +95,7 @@ func (dlm *DistributedLockManager) Unlock(key string, token string) (movedTo pb.
}
if primary != dlm.Host {
// If we still hold this lock locally, serve the unlock here
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && token != "" && (lock.Token == token || lock.PrevToken == token) {
if lock, found := dlm.lockManager.GetLock(key); found && !lock.IsBackup && lock.Token == token {
var isUnlocked bool
var generation int64
var seq int64
+12 -23
View File
@@ -24,7 +24,6 @@ type LockManager struct {
}
type Lock struct {
Token string
PrevToken string // token superseded by the latest renewal; a holder whose renewal response was lost still presents it
ExpiredAtNs int64
Key string // only used for moving locks
Owner string
@@ -103,29 +102,19 @@ func (lm *LockManager) Lock(path string, expiredAtNs int64, token string, owner
generation = oldValue.Generation // keep same generation on renewal
seq = oldValue.Seq + 1
glog.V(4).Infof("key %s old token %v owner %v => %v owner %v", path, oldValue.Token, oldValue.Owner, renewToken, owner)
lm.locks[path] = &Lock{Token: renewToken, PrevToken: oldValue.Token, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
lm.locks[path] = &Lock{Token: renewToken, ExpiredAtNs: expiredAtNs, Owner: owner, Generation: generation, Seq: seq}
return
} else {
if token == "" {
// new lock
glog.V(4).Infof("key %s locked by %v", path, oldValue.Owner)
err = fmt.Errorf("lock already owned by %v", oldValue.Owner)
return
}
glog.V(4).Infof("key %s expected token %v owner %v received %v from %v", path, oldValue.Token, oldValue.Owner, token, owner)
err = fmt.Errorf("lock: token mismatch")
return
}
if token != "" && token == oldValue.PrevToken && owner == oldValue.Owner {
// The latest renewal already rotated the token but its response
// was lost: replay the current token so the holder recovers it
// instead of conflicting with its own lease until it expires.
renewToken = oldValue.Token
generation = oldValue.Generation
seq = oldValue.Seq + 1
oldValue.ExpiredAtNs = expiredAtNs
oldValue.Seq = seq
return
}
if token == "" {
// new lock
glog.V(4).Infof("key %s locked by %v", path, oldValue.Owner)
err = fmt.Errorf("lock already owned by %v", oldValue.Owner)
return
}
glog.V(4).Infof("key %s expected token %v owner %v received %v from %v", path, oldValue.Token, oldValue.Owner, token, owner)
err = fmt.Errorf("lock: token mismatch")
return
} else {
glog.V(4).Infof("key %s no lock owner %v", path, owner)
if token == "" {
@@ -159,7 +148,7 @@ func (lm *LockManager) Unlock(path string, token string) (isUnlocked bool, gener
delete(lm.locks, path)
return
}
if oldValue.Token == token || (token != "" && token == oldValue.PrevToken) {
if oldValue.Token == token {
isUnlocked = true
generation = oldValue.Generation
seq = oldValue.Seq + 1
@@ -84,49 +84,3 @@ func TestLockManager_RemoveBackupLockRejectsOlderGeneration(t *testing.T) {
assert.Equal(t, int64(8), lock.Generation)
assert.Equal(t, int64(1), lock.Seq)
}
func TestLockManager_LostRenewalResponseReplaysToken(t *testing.T) {
lm := NewLockManager()
expires := time.Now().Add(30 * time.Second).UnixNano()
_, token1, _, _, err := lm.Lock("key1", expires, "", "owner1")
assert.NoError(t, err)
// The renewal rotated token1 to token2; the client never learned it.
_, token2, generation, seq2, err := lm.Lock("key1", expires, token1, "owner1")
assert.NoError(t, err)
assert.NotEqual(t, token1, token2)
// Retrying with the superseded token replays the current one instead of
// conflicting with its own lease until it expires. The replayed mutation
// still advances seq so backups accept the extended expiry as fresh.
later := time.Now().Add(60 * time.Second).UnixNano()
owner, replayed, _, seq3, err := lm.Lock("key1", later, token1, "owner1")
assert.NoError(t, err)
assert.Equal(t, "owner1", owner)
assert.Equal(t, token2, replayed)
assert.Greater(t, seq3, seq2)
backup := NewLockManager()
backup.InsertBackupLock("key1", expires, token2, "owner1", generation, seq2)
backup.InsertBackupLock("key1", later, token2, "owner1", generation, seq3)
backupLock, found := backup.GetLock("key1")
assert.True(t, found)
assert.Equal(t, later, backupLock.ExpiredAtNs)
// A replay from a different owner still mismatches.
_, _, _, _, err = lm.Lock("key1", expires, token1, "intruder")
assert.Error(t, err)
// The next rotation retires the superseded token for good.
_, token3, _, _, err := lm.Lock("key1", expires, token2, "owner1")
assert.NoError(t, err)
assert.NotEqual(t, token2, token3)
_, _, _, _, err = lm.Lock("key1", expires, token1, "owner1")
assert.Error(t, err)
// A superseded token still releases its own lock.
unlocked, _, _, err := lm.Unlock("key1", token2)
assert.NoError(t, err)
assert.True(t, unlocked)
}
+9 -9
View File
@@ -272,7 +272,7 @@ func GrpcDial(ctx context.Context, address string, waitForReady bool, opts ...gr
return grpc.DialContext(ctx, address, options...)
}
func getOrCreateConnection(ctx context.Context, address string, waitForReady bool, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
func getOrCreateConnection(address string, waitForReady bool, opts ...grpc.DialOption) (*versionedGrpcClient, error) {
grpcClientsLock.Lock()
defer grpcClientsLock.Unlock()
@@ -284,6 +284,7 @@ func getOrCreateConnection(ctx context.Context, address string, waitForReady boo
}
glog.V(2).Infof("Creating new gRPC connection to %s", address)
ctx := context.Background()
grpcConnection, err := GrpcDial(ctx, address, waitForReady, opts...)
if err != nil {
return nil, fmt.Errorf("fail to dial %s: %v", address, err)
@@ -467,16 +468,15 @@ func shouldInvalidateConnection(ctx context.Context, err error) bool {
}
// WithGrpcClient In streamingMode, always use a fresh connection. Otherwise, try to reuse an existing connection.
// ctx must be the context that bounds this call's connection acquisition and
// the RPC fn issues, so that a Canceled/DeadlineExceeded fired by ctx itself
// does not tear down the shared cached ClientConn out from under other
// concurrent callers. Pass context.Background() when fn picks its own
// context: a Canceled/DeadlineExceeded then never invalidates, since nothing
// here can attribute it to the channel.
// ctx must be the context that bounds the RPC fn issues, so that a
// Canceled/DeadlineExceeded fired by ctx itself does not tear down the shared
// cached ClientConn out from under other concurrent callers. Pass
// context.Background() when fn picks its own context: a Canceled/DeadlineExceeded
// then never invalidates, since nothing here can attribute it to the channel.
func WithGrpcClient(ctx context.Context, streamingMode bool, signature int32, fn func(*grpc.ClientConn) error, address string, waitForReady bool, opts ...grpc.DialOption) error {
if !streamingMode {
vgc, err := getOrCreateConnection(ctx, address, waitForReady, opts...)
vgc, err := getOrCreateConnection(address, waitForReady, opts...)
if err != nil {
return fmt.Errorf("getOrCreateConnection %s: %v", address, err)
}
@@ -498,7 +498,7 @@ func WithGrpcClient(ctx context.Context, streamingMode bool, signature int32, fn
}
// Streaming mode: dedicate a fresh ClientConn to this call.
dialCtx := ctx
dialCtx := context.Background()
if signature != 0 {
// Optimize: Use AppendToOutgoingContext instead of creating new map
dialCtx = metadata.AppendToOutgoingContext(dialCtx, "sw-client-id", fmt.Sprintf("%d", signature))
+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,
})