diff --git a/k8s/charts/seaweedfs/README.md b/k8s/charts/seaweedfs/README.md index 92c8d869c6..af39b51ffa 100644 --- a/k8s/charts/seaweedfs/README.md +++ b/k8s/charts/seaweedfs/README.md @@ -729,7 +729,7 @@ global: The engine registers its pod address with the masters and stores indexes through the filers and volume servers. Both Go and Rust volume servers use the same setup. The maintenance worker builds and updates ANN indexes; queries can scan data before indexing completes. Enabling filer write signing also requires clients writing directly to the filer HTTP API to supply a signed JWT. -The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The cache defaults to 512 MiB and is configured with `vector.readCacheMB`. +The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The engine sizes its caches to a quarter of its memory limit. `global.seaweedfs.enableSecurity` provisions and mounts the vector certificate and shared security configuration. With external certificates, provide the `-vector-cert` secret (`my-seaweedfs-vector-cert` for release `my`). `fullname` follows `seaweedfs.fullname`, including `fullnameOverride`, `nameOverride`, and DNS-name truncation. Provide this secret alongside the existing CA and client secrets. diff --git a/k8s/charts/seaweedfs/templates/vector/vector-deployment.yaml b/k8s/charts/seaweedfs/templates/vector/vector-deployment.yaml index 31007c40db..7f09bd207b 100644 --- a/k8s/charts/seaweedfs/templates/vector/vector-deployment.yaml +++ b/k8s/charts/seaweedfs/templates/vector/vector-deployment.yaml @@ -56,13 +56,9 @@ spec: - 'case "$POD_IP" in *:*) POD_IP="[$POD_IP]";; esac; exec /usr/bin/weed-vector --listen="$POD_IP:{{ .Values.vector.port }}" "$@"' - vector - {{ printf "--masters=%s" (.Values.vector.masters | default $masters) | quote }} - - {{ printf "--read-cache-mb=%d" (int .Values.vector.readCacheMB) | quote }} {{- if .Values.filer.filerGroup }} - {{ printf "--filer-group=%s" .Values.filer.filerGroup | quote }} {{- end }} - {{- if .Values.vector.nprobes }} - - {{ printf "--nprobes=%d" (int .Values.vector.nprobes) | quote }} - {{- end }} {{- if include "seaweedfs.securityConfigEnabled" . }} - --security-toml=/etc/seaweedfs/security.toml {{- end }} diff --git a/k8s/charts/seaweedfs/values.yaml b/k8s/charts/seaweedfs/values.yaml index 009a1982f5..09d41d3b17 100644 --- a/k8s/charts/seaweedfs/values.yaml +++ b/k8s/charts/seaweedfs/values.yaml @@ -1774,8 +1774,6 @@ vector: port: 8090 metricsPort: 0 masters: "" - readCacheMB: 512 - nprobes: null extraArgs: [] extraEnvironmentVars: {} podLabels: {} diff --git a/seaweed-vector/README.md b/seaweed-vector/README.md index 7c0bec281c..2bc2207aba 100644 --- a/seaweed-vector/README.md +++ b/seaweed-vector/README.md @@ -15,12 +15,12 @@ Point an AWS S3 Vectors client at the S3 endpoint, normally `http://localhost:83 | `--masters` | Required | Comma-separated master addresses | | `--listen` | `127.0.0.1:8090` | gRPC listener and registered address | | `--filer-group` | Empty | Filer group used for table storage | -| `--read-cache-mb` | `512` | Immutable data/index read cache; zero disables it | -| `--nprobes` | Automatic | ANN partitions searched per query | | `--metrics-port` | `0` | HTTP metrics and health listener; zero disables it | | `--metrics-ip` | `127.0.0.1` | HTTP listener address | | `--security-toml` | Discovered | Cluster certificates, signing keys and encryption keys | +The engine caches a quarter of the memory it may use (its cgroup limit, else the machine's), split 2:4:1 between file reads, loaded indexes and table metadata, and logs the sizes at startup. Each query probes a tenth of the index's partitions, at least 8, and more under a filter. + The HTTP listener provides `/health`, `/ready`, and `/metrics`. Readiness requires an active registration with the master. The gRPC listener also implements the standard health service for `vector_pb.VectorService` and the whole server. These health statuses follow master registration. Metrics use the `SeaweedFS_vector_` prefix: @@ -35,6 +35,6 @@ The S3 gateway separately publishes `SeaweedFS_s3_` request metrics with `type=" For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `[grpc.client]` for its master/filer connections, and the cluster CA. HTTPS volume reads also use `[https.client]`. The engine follows the same signing and encryption configuration as the other cluster clients. -Run the Lance maintenance worker against the same masters and Lance namespace to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings. +Run the Lance maintenance worker against the cluster's admin to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings. The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data. diff --git a/seaweed-vector/crates/core/src/main.rs b/seaweed-vector/crates/core/src/main.rs index ae4918faab..50141272e7 100644 --- a/seaweed-vector/crates/core/src/main.rs +++ b/seaweed-vector/crates/core/src/main.rs @@ -2,35 +2,27 @@ use anyhow::{Context, Result, bail}; use clap::{Parser, Subcommand}; use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id}; +use weed_lance_worker::cluster::Cluster; use weed_lance_worker::dataset::{self, Storage}; use weed_vector_core::coverage; use weed_vector_core::index; use weed_vector_core::query::{self, Query}; use weed_vector_core::table::VectorTable; -/// Mirrors `weed-worker`'s flags where the two touch the same thing: the -/// namespace that says where a table is, and the masters whose filers hold -/// it. +/// Finds everything through the masters: the S3 gateway whose Lance Namespace +/// says where a table is, and the filers that hold it. #[derive(Parser, Debug)] #[command( name = "weed-vector", about = "Describe, query and index S3 Vectors tables" )] struct Args { - /// Lance namespace the tables live in. - #[arg( - long, - default_value = "http://localhost:9101", - env = "WEED_LANCE_NAMESPACE" - )] - namespace: String, - - /// Comma-separated master addresses, whose filers the tables are kept - /// through. A table named by a local URI needs none. + /// Comma-separated master addresses. A table named by a local path needs + /// none. #[arg(long, alias = "master", env = "WEED_MASTERS")] masters: Option, - /// The filer group whose filers hold the tables. + /// The filer group whose gateways and filers hold the tables. #[arg( long, alias = "filer.group", @@ -45,7 +37,7 @@ struct Args { filer_signing_key: Option, /// The cluster's security.toml; by default the file weed processes find - /// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs. + /// in ., ~/.seaweedfs and /etc/seaweedfs. #[arg(long, env = "WEED_VECTOR_SECURITY_TOML")] security_toml: Option, @@ -146,34 +138,44 @@ enum IndexAction { }, } -/// `id` is a delimiter-joined table id; when it looks like a URI the dataset -/// is opened directly, skipping the namespace: an `s3://` URI on the -/// cluster's storage, a local path (`/path/...`, `file://...`) as it is. -async fn open_dataset( - client: &NamespaceClient, - id: &str, - storage: &Storage, -) -> Result { - let on_cluster = id.starts_with("s3://"); - if !on_cluster && (id.contains("://") || id.starts_with('/')) { - return lance::dataset::builder::DatasetBuilder::from_uri(id) - .load() - .await - .with_context(|| format!("open {id}")); - } - if storage.0.is_none() { - bail!("{id} is kept on the cluster and needs --masters"); - } - if on_cluster { - let description = TableDescription { - location: id.to_string(), - storage_options: Default::default(), - managed_versioning: false, +/// Where tables are found: through the cluster the masters name, or, for a +/// local path, nowhere in particular. +struct Tables { + cluster: Option, + storage: Storage, + signing_key: Option, +} + +impl Tables { + /// `id` is a delimiter-joined table id, looked up in the namespace of a + /// gateway the masters name; when it looks like a URI the dataset is + /// opened directly: an `s3://` URI on the cluster's storage, a local path + /// (`/path/...`, `file://...`) as it is. + async fn open(&self, id: &str) -> Result { + let on_cluster = id.starts_with("s3://"); + if !on_cluster && (id.contains("://") || id.starts_with('/')) { + return lance::dataset::builder::DatasetBuilder::from_uri(id) + .load() + .await + .with_context(|| format!("open {id}")); + } + let Some(cluster) = &self.cluster else { + bail!("{id} is kept on the cluster and needs --masters"); }; - return dataset::open_at(&description, storage.wrapper(id).await?, None).await; + if on_cluster { + let description = TableDescription { + location: id.to_string(), + storage_options: Default::default(), + managed_versioning: false, + }; + return dataset::open_at(&description, self.storage.wrapper(id).await?, None).await; + } + let client = NamespaceClient::new(cluster.lance_namespace().await?) + .with_signing_key(self.signing_key.as_ref()); + Ok(dataset::open(&client, &parse_id(id), &self.storage) + .await? + .dataset) } - let table = dataset::open(client, &parse_id(id), storage).await?; - Ok(table.dataset) } #[tokio::main] @@ -188,20 +190,26 @@ async fn main() -> Result<()> { .init(); let args = Args::parse(); - let security = - weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?; + let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?; let signing_key = SigningKey::new( args.filer_signing_key .or_else(|| security.get("jwt.filer_signing.key")), ); - let client = NamespaceClient::new(args.namespace).with_signing_key(signing_key.as_ref()); - let storage = match &args.masters { + let tables = match &args.masters { Some(masters) => { - let cluster = - weed_lance_worker::cluster::Cluster::new(masters, &args.filer_group, &security)?; - Storage(Some(cluster.storage(&security).await?)) + let cluster = Cluster::new(masters, &args.filer_group, &security)?; + let storage = Storage(Some(cluster.storage(&security).await?)); + Tables { + cluster: Some(cluster), + storage, + signing_key, + } } - None => Storage::default(), + None => Tables { + cluster: None, + storage: Storage::default(), + signing_key, + }, }; match args.command { @@ -210,7 +218,7 @@ async fn main() -> Result<()> { vector_column, key_column, } => { - let dataset = open_dataset(&client, &id, &storage).await?; + let dataset = tables.open(&id).await?; let schema: arrow_schema::Schema = dataset.schema().into(); let resolved = VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref()); @@ -250,7 +258,7 @@ async fn main() -> Result<()> { vector_column, key_column, } => { - let dataset = open_dataset(&client, &id, &storage).await?; + let dataset = tables.open(&id).await?; let vector = VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?; let coverages = coverage::coverage(&dataset, &vector.vector_column).await?; @@ -262,7 +270,7 @@ async fn main() -> Result<()> { vector_column, key_column, } => { - let dataset = open_dataset(&client, &id, &storage).await?; + let dataset = tables.open(&id).await?; let vector = VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?; for batch in query::get(&dataset, &vector, &keys, None).await? { @@ -282,7 +290,7 @@ async fn main() -> Result<()> { key_column, nprobes, } => { - let opened = open_dataset(&client, &id, &storage).await?; + let opened = tables.open(&id).await?; let dataset = match version { Some(v) => opened.checkout_version(v).await?, None => opened, @@ -327,7 +335,7 @@ async fn main() -> Result<()> { id, vector_column, .. } => (id.clone(), vector_column.clone()), }; - let mut dataset = open_dataset(&client, &id, &storage).await?; + let mut dataset = tables.open(&id).await?; let table = VectorTable::resolve(&dataset, vector_column.as_deref(), None)?; let started = std::time::Instant::now(); match action { @@ -404,6 +412,17 @@ mod tests { .unwrap(); assert_eq!(args.masters.as_deref(), Some("m:9333")); assert_eq!(args.filer_group, "eu"); + assert!( + Args::try_parse_from([ + "weed-vector", + "--namespace", + "http://s3:9101", + "describe", + "t" + ]) + .is_err(), + "the namespace comes from the masters" + ); assert!( Args::try_parse_from(["weed-vector", "--encryptVolumeData", "describe", "t"]).is_err(), "volume encryption follows the filer" diff --git a/seaweed-vector/crates/server/src/lib.rs b/seaweed-vector/crates/server/src/lib.rs index 03d1f05f9d..8732e33f58 100644 --- a/seaweed-vector/crates/server/src/lib.rs +++ b/seaweed-vector/crates/server/src/lib.rs @@ -22,6 +22,7 @@ pub mod master_pb { tonic::include_proto!("master_pb"); } pub mod master_client; +pub mod memory; pub mod security { pub use weed_lance_worker::security::*; } diff --git a/seaweed-vector/crates/server/src/main.rs b/seaweed-vector/crates/server/src/main.rs index cd0b3106e1..9b595ad99c 100644 --- a/seaweed-vector/crates/server/src/main.rs +++ b/seaweed-vector/crates/server/src/main.rs @@ -5,6 +5,7 @@ use clap::Parser; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::Server; use weed_lance_worker::cluster::Cluster; +use weed_vector_server::memory::CacheSizes; use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer; use weed_vector_server::read_cache::ReadCache; use weed_vector_server::security::Security; @@ -38,30 +39,11 @@ struct Args { default_value = "" )] filer_group: String, - /// Memory for caching reads of write-once table files, in MiB; 0 disables. - #[arg(long, env = "WEED_VECTOR_READ_CACHE_MB", default_value_t = 512)] - read_cache_mb: u64, - /// Memory for indexes loaded by queries, kept for the next query, in MiB. - #[arg(long, env = "WEED_VECTOR_INDEX_CACHE_MB", default_value_t = 1024)] - index_cache_mb: usize, - /// Memory for table metadata (manifests, file footers) kept across - /// queries, in MiB. - #[arg(long, env = "WEED_VECTOR_METADATA_CACHE_MB", default_value_t = 256)] - metadata_cache_mb: usize, - /// Partitions each query probes in a table's vector index. Default: a - /// tenth of the index's partitions, at least 8; more under a filter. - #[arg(long, env = "WEED_VECTOR_NPROBES")] - nprobes: Option, - /// A filtered query whose indexed metadata keys match at most this many - /// rows scores them exactly instead of searching the vector index; 0 - /// never does. - #[arg(long, env = "WEED_VECTOR_EXACT_MATCH_LIMIT", default_value_t = weed_vector_core::query::DEFAULT_EXACT_MATCH_LIMIT)] - exact_match_limit: usize, /// The cluster's security.toml: [grpc.vector] for this server, /// [grpc.client] for the masters and filers, https.client for volume /// servers under HTTPS, jwt.signing.read.key for signed volume reads, /// s3.sse.kek or s3.sse.key for SSE-S3 buckets. By default the file weed - /// processes find in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs. + /// processes find in ., ~/.seaweedfs and /etc/seaweedfs. #[arg(long, env = "WEED_VECTOR_SECURITY_TOML")] security_toml: Option, #[arg( @@ -78,11 +60,6 @@ struct Args { default_value = "127.0.0.1" )] metrics_ip: String, - - /// The directory weed's -config_dir names, searched for security.toml - /// first. - #[arg(long, alias = "config_dir", env = "WEED_VECTOR_CONFIG_DIR")] - config_dir: Option, } // weed tools take Go-style single-dash long flags; normalize_args converts @@ -153,7 +130,7 @@ async fn main() -> Result<()> { tracing_subscriber::fmt::init(); let args = Args::parse_from(normalize_args(std::env::args().collect())); weed_lance_worker::tls::install_default_crypto_provider(); - let security = Security::load(args.security_toml.as_deref(), args.config_dir.as_deref())?; + let security = Security::load(args.security_toml.as_deref())?; if let Some(path) = security.path() { tracing::info!("security settings from {}", path.display()); } @@ -171,16 +148,18 @@ async fn main() -> Result<()> { let (health, health_service) = tonic_health::server::health_reporter(); let metrics = Metrics::new()?.with_health(health); metrics.set_connected(false).await; - let cache = (args.read_cache_mb > 0) - .then(|| ReadCache::new(args.read_cache_mb << 20).with_metrics(metrics.clone())); - let mut service = VectorServer::new() - .with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get)) - .with_exact_match_limit(Some(args.exact_match_limit)) - .with_lance_caches(args.index_cache_mb << 20, args.metadata_cache_mb << 20) - .with_storage(reads); - if let Some(cache) = &cache { - service = service.with_read_cache(cache.clone()); - } + let sizes = CacheSizes::detect(); + tracing::info!( + "caching {} MiB of file reads, {} MiB of indexes, {} MiB of table metadata", + sizes.read >> 20, + sizes.index >> 20, + sizes.metadata >> 20 + ); + let cache = ReadCache::new(sizes.read).with_metrics(metrics.clone()); + let service = VectorServer::new() + .with_lance_caches(sizes.index as usize, sizes.metadata as usize) + .with_storage(reads) + .with_read_cache(cache.clone()); if args.metrics_port > 0 { let ip = args .metrics_ip @@ -191,7 +170,7 @@ async fn main() -> Result<()> { tokio::net::TcpListener::bind(std::net::SocketAddr::new(ip, args.metrics_port)).await?; let metrics = metrics.clone(); tokio::spawn(async move { - if let Err(error) = metrics::serve_listener(metrics, listener, cache).await { + if let Err(error) = metrics::serve_listener(metrics, listener, Some(cache)).await { tracing::error!(%error, "vector metrics server stopped"); } }); @@ -263,16 +242,6 @@ mod tests { ); } - #[test] - fn nprobes_must_be_positive() { - let parse = |nprobes: &str| { - Args::try_parse_from(["weed-vector", "--masters", "m:9333", "--nprobes", nprobes]) - }; - assert!(parse("0").is_err()); - let args = parse("12").unwrap(); - assert_eq!(args.nprobes.map(std::num::NonZeroUsize::get), Some(12)); - } - #[test] fn the_catalog_flags_are_gone() { let parse = |extra: &[&str]| { diff --git a/seaweed-vector/crates/server/src/memory.rs b/seaweed-vector/crates/server/src/memory.rs new file mode 100644 index 0000000000..7c05a85935 --- /dev/null +++ b/seaweed-vector/crates/server/src/memory.rs @@ -0,0 +1,155 @@ +//! How much the engine caches: a share of the memory this process may use, +//! so a small pod is not overcommitted and a large host is not left idle. + +use std::path::{Path, PathBuf}; + +/// The read, index and metadata caches, in bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CacheSizes { + pub read: u64, + pub index: u64, + pub metadata: u64, +} + +/// Where no limit can be read, the sizes the flags used to default to. +const UNKNOWN_LIMIT_BUDGET: u64 = 1792 << 20; + +impl CacheSizes { + /// A quarter of the memory limit, split 2:4:1 between file reads, loaded + /// indexes and table metadata. + pub fn for_limit(limit: Option) -> Self { + let budget = limit.map_or(UNKNOWN_LIMIT_BUDGET, |limit| limit / 4); + let seventh = budget / 7; + Self { + read: seventh * 2, + index: seventh * 4, + metadata: seventh, + } + } + + pub fn detect() -> Self { + Self::for_limit(memory_limit()) + } +} + +/// The smallest of the machine's memory and the limits of this process's +/// memory cgroup and its ancestors: a systemd service is limited in its own +/// group, a container usually at the root it sees. +fn memory_limit() -> Option { + let read = |path: &Path| std::fs::read_to_string(path).ok(); + let total = read(Path::new("/proc/meminfo")).and_then(|info| mem_total(&info)); + let groups = read(Path::new("/proc/self/cgroup")) + .map(|groups| limit_files(&groups)) + .unwrap_or_default(); + groups + .iter() + .filter_map(|file| read(file).and_then(|limit| cgroup_limit(&limit))) + .chain(total) + .min() +} + +/// The limit files of the memory cgroup `/proc/self/cgroup` names and of its +/// ancestors: v1's memory controller where it has one, else v2's unified group. +fn limit_files(self_cgroup: &str) -> Vec { + let entries: Vec<(&str, &str)> = self_cgroup + .lines() + .filter_map(|line| { + let mut fields = line.splitn(3, ':'); + fields.next()?; + Some((fields.next()?, fields.next()?)) + }) + .collect(); + let v1 = entries + .iter() + .find(|(controllers, _)| controllers.split(',').any(|c| c == "memory")) + .map(|(_, group)| ("/sys/fs/cgroup/memory", *group, "memory.limit_in_bytes")); + let v2 = entries + .iter() + .find(|(controllers, _)| controllers.is_empty()) + .map(|(_, group)| ("/sys/fs/cgroup", *group, "memory.max")); + let Some((root, group, file)) = v1.or(v2) else { + return Vec::new(); + }; + Path::new(group) + .ancestors() + .map(|dir| { + Path::new(root) + .join(dir.strip_prefix("/").unwrap_or(dir)) + .join(file) + }) + .collect() +} + +fn mem_total(meminfo: &str) -> Option { + let line = meminfo.lines().find(|line| line.starts_with("MemTotal:"))?; + let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; + Some(kib << 10) +} + +/// cgroup v2 writes "max" for no limit; v1 writes a number near u64::MAX. +fn cgroup_limit(limit: &str) -> Option { + let bytes: u64 = limit.trim().parse().ok()?; + (bytes < 1 << 60).then_some(bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_quarter_of_the_limit_split_two_four_one() { + let sizes = CacheSizes::for_limit(Some(28 << 30)); + assert_eq!(sizes.read, 2 << 30); + assert_eq!(sizes.index, 4 << 30); + assert_eq!(sizes.metadata, 1 << 30); + } + + #[test] + fn no_limit_keeps_the_former_defaults() { + let sizes = CacheSizes::for_limit(None); + assert_eq!( + (sizes.read, sizes.index, sizes.metadata), + (512 << 20, 1024 << 20, 256 << 20) + ); + } + + #[test] + fn looks_up_the_process_group_and_its_ancestors() { + let paths = |groups: &str| -> Vec { + limit_files(groups) + .iter() + .map(|p| p.display().to_string()) + .collect() + }; + assert_eq!( + paths("0::/system.slice/weed-vector.service\n"), + [ + "/sys/fs/cgroup/system.slice/weed-vector.service/memory.max", + "/sys/fs/cgroup/system.slice/memory.max", + "/sys/fs/cgroup/memory.max", + ] + ); + // A container's namespace shows its own group as the root. + assert_eq!(paths("0::/\n"), ["/sys/fs/cgroup/memory.max"]); + // On a hybrid host the memory controller is v1's. + assert_eq!( + paths("12:cpu,cpuacct:/a\n4:memory:/user.slice\n0::/user.slice\n"), + [ + "/sys/fs/cgroup/memory/user.slice/memory.limit_in_bytes", + "/sys/fs/cgroup/memory/memory.limit_in_bytes", + ] + ); + assert!(paths("").is_empty()); + } + + #[test] + fn reads_the_limits_the_kernel_writes() { + assert_eq!( + mem_total("MemTotal: 16384000 kB\nMemFree: 1 kB\n"), + Some(16_384_000 << 10) + ); + assert_eq!(cgroup_limit("4294967296\n"), Some(4 << 30)); + assert_eq!(cgroup_limit("max\n"), None); + assert_eq!(cgroup_limit("9223372036854771712\n"), None); + } +} diff --git a/seaweed-vector/crates/server/src/service.rs b/seaweed-vector/crates/server/src/service.rs index cb7eb06114..12d4cf4e69 100644 --- a/seaweed-vector/crates/server/src/service.rs +++ b/seaweed-vector/crates/server/src/service.rs @@ -705,7 +705,6 @@ pub struct VectorServer { pub(crate) handles: moka::sync::Cache<(String, bool), (u64, Dataset)>, lance_cache_bytes: (usize, usize), leases: SharedLeases, - nprobes: Option, exact_match_limit: Option, filter_stats: crate::filter_stats::FilterStats, /// URI schemes a table's location may have. @@ -730,7 +729,6 @@ impl VectorServer { lance_cache_bytes: (DEFAULT_INDEX_CACHE_BYTES, DEFAULT_METADATA_CACHE_BYTES), handles: moka::sync::Cache::new(MAX_HANDLES), leases: SharedLeases::default(), - nprobes: None, exact_match_limit: None, filter_stats: Default::default(), schemes: &["s3"], @@ -744,15 +742,10 @@ impl VectorServer { self } - /// Partitions every query probes, instead of the index's own default. - pub fn with_nprobes(mut self, nprobes: Option) -> Self { - self.nprobes = nprobes; - self - } - /// Matches of a filter's indexed metadata keys scored exactly instead of /// searched through the vector index, at most; None keeps the default. - pub fn with_exact_match_limit(mut self, limit: Option) -> Self { + #[cfg(test)] + pub(crate) fn with_exact_match_limit(mut self, limit: Option) -> Self { self.exact_match_limit = limit; self } @@ -1180,7 +1173,7 @@ impl VectorService for VectorServer { }, postfilter: req.postfilter, distance, - nprobes: self.nprobes, + nprobes: None, index_segments: None, fragments: None, exact_match_limit: self.exact_match_limit, diff --git a/seaweed-worker/crates/lance/src/cluster.rs b/seaweed-worker/crates/lance/src/cluster.rs index 58f668af20..8ac14540a3 100644 --- a/seaweed-worker/crates/lance/src/cluster.rs +++ b/seaweed-worker/crates/lance/src/cluster.rs @@ -10,6 +10,7 @@ use tonic::transport::{Channel, Endpoint}; use crate::direct_read::{Connection, DirectReads, FilerDialer}; use crate::grpc_tls; +use crate::master_pb::list_cluster_nodes_response::ClusterNode; use crate::master_pb::{ListClusterNodesRequest, seaweed_client::SeaweedClient}; use crate::security::{GrpcTls, Security}; @@ -102,22 +103,32 @@ pub async fn list_filers( } } -async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Result> { +/// The nodes of `client_type` in `filer_group` that `master` lists. +async fn cluster_nodes( + master: &str, + client_type: &str, + filer_group: &str, + tls: Option<&GrpcTls>, +) -> Result> { let channel = connect(master, tls).await?; let request = ListClusterNodesRequest { - client_type: "filer".into(), + client_type: client_type.into(), filer_group: filer_group.into(), ..Default::default() }; - let nodes = tokio::time::timeout( + Ok(tokio::time::timeout( CONNECT_TIMEOUT, SeaweedClient::new(channel).list_cluster_nodes(request), ) .await .context("master did not answer")?? .into_inner() - .cluster_nodes; - Ok(nodes + .cluster_nodes) +} + +async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Result> { + Ok(cluster_nodes(master, "filer", filer_group, tls) + .await? .iter() .filter_map(|node| match filer_grpc_addr(&node.address) { Ok(addr) => Some(addr), @@ -129,6 +140,13 @@ async fn filers_of(master: &str, filer_group: &str, tls: Option<&GrpcTls>) -> Re .collect()) } +/// Where an S3 gateway registered as `host:grpc` serves its Lance +/// Namespace, or None when it serves none. +fn lance_namespace_url(node: &ClusterNode) -> Option { + let (host, _) = node.address.rsplit_once(':')?; + (node.lance_port > 0).then(|| format!("http://{host}:{}", node.lance_port)) +} + /// A filer registers as `host:port.grpc`, or `host:port` with its gRPC at /// port + 10000. pub fn filer_grpc_addr(address: &str) -> Result { @@ -220,6 +238,25 @@ impl Cluster { }) } + /// The Lance Namespace of an S3 gateway in the filer group, from the first + /// master that names one. + pub async fn lance_namespace(&self) -> Result { + let mut last = None; + for master in &self.masters { + match cluster_nodes(master, "s3", &self.filer_group, self.master_tls.as_ref()).await { + Ok(nodes) => { + if let Some(url) = nodes.iter().find_map(lance_namespace_url) { + return Ok(url); + } + } + Err(err) => last = Some(err), + } + } + Err(last.unwrap_or_else(|| { + anyhow::anyhow!("the masters list no S3 gateway that serves a Lance Namespace") + })) + } + /// Connects to the cluster's storage and follows the masters' filer list. /// Chunks are encrypted for the volume servers when the filer is /// configured to (`weed filer -encryptVolumeData`), as `weed s3` does. @@ -291,6 +328,24 @@ pub async fn open_storage(conn: &Connection) -> Result { mod tests { use super::*; + #[test] + fn a_gateway_serves_its_namespace_on_its_registered_host() { + let node = |address: &str, lance_port| ClusterNode { + address: address.into(), + lance_port, + ..Default::default() + }; + assert_eq!( + lance_namespace_url(&node("10.0.0.5:18333", 9101)).as_deref(), + Some("http://10.0.0.5:9101") + ); + assert_eq!( + lance_namespace_url(&node("[fd00::5]:18333", 9101)).as_deref(), + Some("http://[fd00::5]:9101") + ); + assert_eq!(lance_namespace_url(&node("10.0.0.5:18333", 0)), None); + } + #[test] fn an_empty_master_list_is_refused() { assert!(master_addresses("").is_err()); diff --git a/seaweed-worker/crates/lance/src/main.rs b/seaweed-worker/crates/lance/src/main.rs index f245b5e921..66f67fc47e 100644 --- a/seaweed-worker/crates/lance/src/main.rs +++ b/seaweed-worker/crates/lance/src/main.rs @@ -30,7 +30,7 @@ struct Args { max_concurrency: i32, /// The cluster's security.toml; by default the file weed processes find - /// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs. + /// in ., ~/.seaweedfs and /etc/seaweedfs. #[arg(long, env = "WEED_WORKER_SECURITY_TOML")] security_toml: Option, @@ -131,8 +131,7 @@ async fn main() -> Result<()> { let tls = args.tls()?; // One security.toml for everything: the admin stream's and the catalog's // signing key, and the cluster connection. - let security = - weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?; + let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?; let filer_signing = match args.filer_signing_key.filter(|key| !key.is_empty()) { Some(key) => Some((key, 0)), None => security diff --git a/seaweed-worker/crates/lance/src/security.rs b/seaweed-worker/crates/lance/src/security.rs index 557dd28bd6..116d3a792c 100644 --- a/seaweed-worker/crates/lance/src/security.rs +++ b/seaweed-worker/crates/lance/src/security.rs @@ -1,5 +1,5 @@ //! The cluster's `security.toml`, found and read the way weed processes do: -//! the file in `-config_dir`, `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs` +//! the file in `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs` //! or `/etc/seaweedfs`, with `WEED_*` environment variables over it. use std::path::{Path, PathBuf}; @@ -77,23 +77,8 @@ impl std::fmt::Debug for Security { } } -// weed's util.ResolvePath for "~" and "~/..." -fn resolve_path(path: &Path, home: Option<&Path>) -> PathBuf { - match (path.strip_prefix("~"), home) { - (Ok(rest), Some(home)) => home.join(rest), - _ => path.to_path_buf(), - } -} - -fn candidates( - config_dir: Option<&Path>, - current_dir: Option<&Path>, - home: Option<&Path>, -) -> Vec { +fn candidates(current_dir: Option<&Path>, home: Option<&Path>) -> Vec { let mut found = Vec::new(); - if let Some(dir) = config_dir { - found.push(resolve_path(dir, home).join(FILE_NAME)); - } if let Some(dir) = current_dir { found.push(dir.join(FILE_NAME)); } @@ -130,21 +115,17 @@ fn entry<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> { } impl Security { - /// Reads `path`, or the first `security.toml` where weed looks: the - /// `-config_dir`, then `.`, `~/.seaweedfs`, `/usr/local/etc/seaweedfs` - /// and `/etc/seaweedfs`. Without one, only the environment applies. - pub fn load(path: Option<&Path>, config_dir: Option<&Path>) -> Result { + /// Reads `path`, or the first `security.toml` where weed looks: `.`, + /// `~/.seaweedfs`, `/usr/local/etc/seaweedfs` and `/etc/seaweedfs`. + /// Without one, only the environment applies. + pub fn load(path: Option<&Path>) -> Result { let path = match path { Some(path) => Some(path.to_path_buf()), None => { let home = std::env::var_os("HOME").map(PathBuf::from); - candidates( - config_dir, - std::env::current_dir().ok().as_deref(), - home.as_deref(), - ) - .into_iter() - .find(|p| p.is_file()) + candidates(std::env::current_dir().ok().as_deref(), home.as_deref()) + .into_iter() + .find(|p| p.is_file()) } }; Self::from_file(path, Box::new(|name| std::env::var(name).ok())) @@ -559,15 +540,10 @@ mod tests { #[test] fn the_file_is_searched_where_weed_looks() { - let found = candidates( - Some(Path::new("/etc/weed")), - Some(Path::new("/cwd")), - Some(Path::new("/home/u")), - ); + let found = candidates(Some(Path::new("/cwd")), Some(Path::new("/home/u"))); assert_eq!( found, [ - "/etc/weed/security.toml", "/cwd/security.toml", "/home/u/.seaweedfs/security.toml", "/usr/local/etc/seaweedfs/security.toml", @@ -575,32 +551,14 @@ mod tests { ] .map(PathBuf::from) ); - let home = Some(Path::new("/home/u")); - for (dir, want) in [ - ("~", "/home/u/security.toml"), - ("~/cluster", "/home/u/cluster/security.toml"), - ("~other/cluster", "~other/cluster/security.toml"), - ("/srv/~/cluster", "/srv/~/cluster/security.toml"), - ] { - assert_eq!( - candidates(Some(Path::new(dir)), None, home)[0], - PathBuf::from(want), - "{dir}" - ); - } } #[test] - fn load_takes_the_config_dir_before_the_usual_places() { + fn an_explicit_file_wins() { let dir = tempfile::tempdir().unwrap(); - let in_config_dir = dir.path().join(FILE_NAME); - std::fs::write(&in_config_dir, "").unwrap(); - let loaded = Security::load(None, Some(dir.path())).unwrap(); - assert_eq!(loaded.path(), Some(in_config_dir.as_path())); - // An explicit file still wins. let explicit = dir.path().join("other.toml"); std::fs::write(&explicit, "").unwrap(); - let loaded = Security::load(Some(&explicit), Some(dir.path())).unwrap(); + let loaded = Security::load(Some(&explicit)).unwrap(); assert_eq!(loaded.path(), Some(explicit.as_path())); } } diff --git a/seaweed-worker/crates/lance/tests/common/mod.rs b/seaweed-worker/crates/lance/tests/common/mod.rs index b48c3ee852..e9ecd8d369 100644 --- a/seaweed-worker/crates/lance/tests/common/mod.rs +++ b/seaweed-worker/crates/lance/tests/common/mod.rs @@ -115,7 +115,7 @@ pub async fn storage() -> weed_lance_worker::dataset::Storage { } fn security() -> weed_lance_worker::security::Security { - weed_lance_worker::security::Security::load(None, None).expect("security.toml") + weed_lance_worker::security::Security::load(None).expect("security.toml") } /// The cluster token the namespace authenticates its processes by, from diff --git a/test/s3vectors/conftest.py b/test/s3vectors/conftest.py index 20c4f45557..9203f0a808 100644 --- a/test/s3vectors/conftest.py +++ b/test/s3vectors/conftest.py @@ -333,11 +333,11 @@ def run_cluster(param, tmp_path_factory, identities): return response.status == 200 wait_for(vector_ready, processes, "vector engine did not register with master") - def restart_engine(env=None): - """Restart the single engine with `env` added to its environment.""" + def restart_engine(): + """Restart the single engine, so a workload starts with empty caches.""" old = processes["vector"] stop(old) - start("vector", old.args, env=env) + start("vector", old.args) wait_for(vector_ready, processes, "vector engine did not come back") if os.environ.get("VECTOR_TLS"): diff --git a/test/s3vectors/perf_test.py b/test/s3vectors/perf_test.py index 6dce3e9a62..01872d2695 100644 --- a/test/s3vectors/perf_test.py +++ b/test/s3vectors/perf_test.py @@ -33,10 +33,6 @@ one more index per locality, each row with an `author` key, and queries (seed 5) over the whole index; "clustered": they are consecutive keys, written together, so they land in few fragments ("scattered"; both: "scattered,clustered") - PERF_FILTER_MODES "warm": engine restarted with default caches; - "cold": engine restarted with its read, index and - metadata caches at 0 MB, so every query reads again - ("warm") PERF_FILTER_ROUNDS rounds; each round runs every author and locality in turn (1) @@ -48,8 +44,7 @@ distance, responses without a `vectors` field (counted, and the test fails after every scenario ran; results and recall then come from the same query repeated, untimed, without returnDistance), and the reads per query: the engine's cache_requests_total misses, storage_read_seconds count and storage_read_bytes_total (immutable files -only, and none when cold: they come from the read cache, which a 0 MB -setting removes) and the volume server's request_total (every request, +only) and the volume server's request_total (every request, manifests included). The engine does not expose the partitions a query probed. @@ -93,10 +88,8 @@ NOISE = float(os.environ.get("PERF_NOISE", "0.3")) INDEX = "perf" FILTER_AUTHORS = os.environ.get("PERF_FILTER_AUTHORS", "alice=0.1,bob=0.01,carol=0.0001,dave=#5,nobody=#0") FILTER_LOCALITY = os.environ.get("PERF_FILTER_LOCALITY", "scattered").split(",") -FILTER_MODES = os.environ.get("PERF_FILTER_MODES", "warm").split(",") FILTER_ROUNDS = int(os.environ.get("PERF_FILTER_ROUNDS", "1")) FILTER_SEED = 5 -COLD = {"WEED_VECTOR_READ_CACHE_MB": "0", "WEED_VECTOR_INDEX_CACHE_MB": "0", "WEED_VECTOR_METADATA_CACHE_MB": "0"} REPORT = {} @@ -346,7 +339,6 @@ def test_query_filter_workload(perf): s3v, data, queries, cluster = perf["client"], perf["data"], perf["queries"], perf["cluster"] if cluster["mode"] != "single": pytest.skip("restart_engine restarts one engine") - assert set(FILTER_MODES) <= {"warm", "cold"}, FILTER_MODES unit = np.array([v for v, _ in data], dtype=np.float64) unit /= np.linalg.norm(unit, axis=1, keepdims=True) indexes, eligible, setup = {}, {}, {} @@ -372,56 +364,52 @@ def test_query_filter_workload(perf): assert {name: len(eligible[locality, name]) for name in planted} == planted eligible.update({(locality, None): np.arange(VECTORS) for locality in FILTER_LOCALITY}) perf["report"]["filter_workload"] = report = { - "seed": FILTER_SEED, "authors": FILTER_AUTHORS, "eligible": planted, "modes": FILTER_MODES, + "seed": FILTER_SEED, "authors": FILTER_AUTHORS, "eligible": planted, "rounds": FILTER_ROUNDS, "setup": setup, "partitions_probed": "not exposed by the engine", "runs": []} - for mode in FILTER_MODES: - cluster["restart_engine"](COLD if mode == "cold" else {}) - for round_ in range(FILTER_ROUNDS): - for author in [None, *planted]: - for locality in FILTER_LOCALITY: - args = indexes[locality] - rows = eligible[locality, author] - keep = set(rows.tolist()) - extra = {"filter": {"author": author}} if author else {} - s3v.query_vectors(**args, queryVector={"float32": queries[0]}, topK=TOPK, **extra) - latencies, recalls, results, nonfinite, without_vectors = [], [], [], 0, 0 - reads = dict.fromkeys(engine_reads(cluster), 0.0) - for query in queries: - before = engine_reads(cluster) - seconds, response = timed(lambda: s3v.query_vectors( - **args, queryVector={"float32": query}, topK=TOPK, returnDistance=True, **extra)) - after = engine_reads(cluster) - for name in reads: - reads[name] += after[name] - before[name] - latencies.append(seconds) - if "vectors" in response: - nonfinite += sum(1 for h in response["vectors"] - if not math.isfinite(h.get("distance", math.nan))) - else: - without_vectors += 1 - response = s3v.query_vectors(**args, queryVector={"float32": query}, topK=TOPK, **extra) - hits = response["vectors"] - assert all(int(h["key"][1:]) in keep for h in hits), hits - assert len(hits) <= min(TOPK, len(rows)), hits - results.append(len(hits)) - recalls.append(filtered_recall(unit, rows, query, TOPK, hits)) - recalls = [r for r in recalls if r is not None] - row = {"mode": mode, "round": round_, "locality": locality, "author": author, - "eligible": len(rows), **summarize(latencies), - "recall_at_k": statistics.fmean(recalls) if recalls else None, - "min_recall_at_k": min(recalls) if recalls else None, - "results_mean": statistics.fmean(results), "results_min": min(results), - "nonfinite_distances": nonfinite, "responses_without_vectors": without_vectors, - **{f"{name}_per_query": value / len(queries) for name, value in reads.items()}, - # Without a read cache the engine has no storage counters. - **({f"{name}_per_query": None for name in ("cache_misses", "storage_reads", "storage_bytes")} - if mode == "cold" else {}), - "load_1m": os.getloadavg()[0]} - report["runs"].append(row) - print(json.dumps(row)) - assert INDEXED or not recalls or statistics.fmean(recalls) >= 0.9 - if without_vectors: - empty.append(f"{mode} {locality} {author}: {without_vectors}") + cluster["restart_engine"]() + for round_ in range(FILTER_ROUNDS): + for author in [None, *planted]: + for locality in FILTER_LOCALITY: + args = indexes[locality] + rows = eligible[locality, author] + keep = set(rows.tolist()) + extra = {"filter": {"author": author}} if author else {} + s3v.query_vectors(**args, queryVector={"float32": queries[0]}, topK=TOPK, **extra) + latencies, recalls, results, nonfinite, without_vectors = [], [], [], 0, 0 + reads = dict.fromkeys(engine_reads(cluster), 0.0) + for query in queries: + before = engine_reads(cluster) + seconds, response = timed(lambda: s3v.query_vectors( + **args, queryVector={"float32": query}, topK=TOPK, returnDistance=True, **extra)) + after = engine_reads(cluster) + for name in reads: + reads[name] += after[name] - before[name] + latencies.append(seconds) + if "vectors" in response: + nonfinite += sum(1 for h in response["vectors"] + if not math.isfinite(h.get("distance", math.nan))) + else: + without_vectors += 1 + response = s3v.query_vectors(**args, queryVector={"float32": query}, topK=TOPK, **extra) + hits = response["vectors"] + assert all(int(h["key"][1:]) in keep for h in hits), hits + assert len(hits) <= min(TOPK, len(rows)), hits + results.append(len(hits)) + recalls.append(filtered_recall(unit, rows, query, TOPK, hits)) + recalls = [r for r in recalls if r is not None] + row = {"round": round_, "locality": locality, "author": author, + "eligible": len(rows), **summarize(latencies), + "recall_at_k": statistics.fmean(recalls) if recalls else None, + "min_recall_at_k": min(recalls) if recalls else None, + "results_mean": statistics.fmean(results), "results_min": min(results), + "nonfinite_distances": nonfinite, "responses_without_vectors": without_vectors, + **{f"{name}_per_query": value / len(queries) for name, value in reads.items()}, + "load_1m": os.getloadavg()[0]} + report["runs"].append(row) + print(json.dumps(row)) + assert INDEXED or not recalls or statistics.fmean(recalls) >= 0.9 + if without_vectors: + empty.append(f"{locality} {author}: {without_vectors}") finally: cluster["restart_engine"]() for args in indexes.values(): @@ -521,7 +509,7 @@ def print_report(combo, report, path): f"p95 {r['p95_ms']:7.1f} ms") for r in report.get("filter_workload", {}).get("runs", []): recall_text = "n/a" if r["recall_at_k"] is None else f"{r['recall_at_k']:.3f}" - lines.append(f"filter {r['mode']} r{r['round']} {r['locality']:<9} {str(r['author']):<8} " + lines.append(f"filter r{r['round']} {r['locality']:<9} {str(r['author']):<8} " f"{r['eligible']:>7} rows p50 {r['p50_ms']:7.1f} ms p95 {r['p95_ms']:7.1f} ms " f"recall@k {recall_text} results {r['results_mean']:.1f} (min {r['results_min']}) " f"empty {r['responses_without_vectors']} " diff --git a/weed/command/mini_vector.go b/weed/command/mini_vector.go index c2420d82f0..93d9c4bc81 100644 --- a/weed/command/mini_vector.go +++ b/weed/command/mini_vector.go @@ -55,7 +55,10 @@ func startMiniVector() error { args = append(args, fmt.Sprintf("--metrics-port=%d", *miniVectorMetricsPort), "--metrics-ip="+bindIP) } if directory := util.ConfigurationFileDirectory.String(); directory != "" { - args = append(args, "--config-dir="+util.ResolvePath(directory)) + path := filepath.Join(util.ResolvePath(directory), "security.toml") + if _, explicit := os.LookupEnv("WEED_VECTOR_SECURITY_TOML"); !explicit && util.FileExists(path) { + args = append(args, "--security-toml="+path) + } } command := exec.CommandContext(miniClientsCtx(), binary, args...) command.Stdout, command.Stderr = os.Stdout, os.Stderr