use std::collections::BTreeMap;
use relate_core::{Error, Result, Value};
use relate_ir::VectorMetric;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StorableMetric {
Cosine,
Euclidean,
}
impl TryFrom<VectorMetric> for StorableMetric {
type Error = Error;
fn try_from(metric: VectorMetric) -> Result<Self> {
match metric {
VectorMetric::Cosine => Ok(Self::Cosine),
VectorMetric::Euclidean => Ok(Self::Euclidean),
VectorMetric::EuclideanSquared
| VectorMetric::Manhattan
| VectorMetric::Dot
| VectorMetric::Hamming => Err(Error::argument_error("InvalidInputValue")),
}
}
}
impl From<StorableMetric> for VectorMetric {
fn from(metric: StorableMetric) -> Self {
match metric {
StorableMetric::Cosine => Self::Cosine,
StorableMetric::Euclidean => Self::Euclidean,
}
}
}
impl StorableMetric {
fn name(self) -> &'static str {
VectorMetric::from(self).name()
}
}
const KEY_DIMENSIONS: &str = "vector.dimensions";
const KEY_SIMILARITY: &str = "vector.similarity_function";
const KEY_QUANTIZATION: &str = "vector.quantization.enabled";
const KEY_QUANTIZATION_TYPE: &str = "vector.quantization.type";
const KEY_HNSW_M: &str = "vector.hnsw.m";
const KEY_HNSW_EF: &str = "vector.hnsw.ef_construction";
const KEY_SEARCH_EXPANSION: &str = "vector.default_search_expansion_factor";
const QUANTIZATION_NONE: &str = "NONE";
const QUANTIZATION_BINARY: &str = "BINARY";
#[derive(Clone, Copy, PartialEq)]
enum KeyShape {
Bool,
Int,
Number,
}
impl KeyShape {
fn admits(self, value: &Value) -> bool {
matches!(
(self, value),
(Self::Bool, Value::Bool(_))
| (Self::Int, Value::Int(_))
| (Self::Number, Value::Int(_) | Value::Float(_))
)
}
}
#[derive(Clone, Copy)]
enum KeyRule {
Dimension,
Metric,
Quantization,
Shape(KeyShape),
}
const CONFIG_KEYS: [(&str, KeyRule); 7] = [
(KEY_DIMENSIONS, KeyRule::Dimension),
(KEY_SIMILARITY, KeyRule::Metric),
(KEY_QUANTIZATION, KeyRule::Shape(KeyShape::Bool)),
(KEY_QUANTIZATION_TYPE, KeyRule::Quantization),
(KEY_HNSW_M, KeyRule::Shape(KeyShape::Int)),
(KEY_HNSW_EF, KeyRule::Shape(KeyShape::Int)),
(KEY_SEARCH_EXPANSION, KeyRule::Shape(KeyShape::Number)),
];
pub(crate) const VECTOR_DIMENSIONS_MIN: usize = 1;
pub(crate) const VECTOR_DIMENSIONS_MAX: usize = 4096;
pub(crate) fn vector_dimension(value: i64) -> Option<usize> {
let dimension = usize::try_from(value).ok()?;
(VECTOR_DIMENSIONS_MIN..=VECTOR_DIMENSIONS_MAX)
.contains(&dimension)
.then_some(dimension)
}
pub(crate) fn parse_config(config: &BTreeMap<String, Value>) -> Result<StoredVectorConfig> {
if !config
.keys()
.all(|key| CONFIG_KEYS.iter().any(|(name, _)| *name == key.as_str()))
{
return Err(Error::argument_error("InvalidInputValue"));
}
let mut dimension = None;
let mut metric = StorableMetric::Cosine;
let mut quantization = QUANTIZATION_BINARY.to_string();
for (name, rule) in CONFIG_KEYS {
let Some(value) = config.get(name) else {
continue;
};
match rule {
KeyRule::Dimension => match value {
Value::Int(value) => {
dimension = Some(
vector_dimension(*value)
.ok_or_else(|| Error::argument_error("NumberOutOfRange"))?,
);
}
_ => return Err(Error::argument_error("InvalidInputValue")),
},
KeyRule::Metric => match value {
Value::String(metric_name) => {
metric = StorableMetric::try_from(
VectorMetric::from_name(metric_name)
.ok_or_else(|| Error::argument_error("InvalidInputValue"))?,
)?;
}
_ => return Err(Error::argument_error("InvalidInputValue")),
},
KeyRule::Quantization => match value {
Value::String(name) => quantization = name.to_ascii_uppercase(),
_ => return Err(Error::argument_error("InvalidInputValue")),
},
KeyRule::Shape(shape) => {
if !shape.admits(value) {
return Err(Error::argument_error("InvalidInputValue"));
}
}
}
}
Ok(StoredVectorConfig {
dimension,
metric,
quantization,
})
}
pub(crate) struct StoredVectorConfig {
pub dimension: Option<usize>,
pub metric: StorableMetric,
pub quantization: String,
}
pub(crate) fn apply_defaults(
config: &mut BTreeMap<String, Value>,
metric: StorableMetric,
quantization: &str,
) {
config.entry(KEY_HNSW_M.into()).or_insert(Value::Int(16));
config.entry(KEY_HNSW_EF.into()).or_insert(Value::Int(100));
config.insert(
KEY_QUANTIZATION_TYPE.into(),
Value::String(quantization.into()),
);
let expansion_default = match quantization {
QUANTIZATION_NONE => 1.0,
_ => 3.0,
};
config
.entry(KEY_SEARCH_EXPANSION.into())
.or_insert(Value::Float(expansion_default));
config.insert(KEY_SIMILARITY.into(), Value::String(metric.name().into()));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::map;
#[test]
fn config_admits_both_quantization_keys() {
for admitted in [
map(&[
(KEY_QUANTIZATION, Value::Bool(false)),
(KEY_QUANTIZATION_TYPE, Value::String("none".into())),
]),
map(&[(KEY_QUANTIZATION, Value::Bool(true))]),
map(&[(KEY_QUANTIZATION_TYPE, Value::String("scalar".into()))]),
] {
let parsed = parse_config(&admitted).expect("quantization keys are admitted");
assert!(matches!(parsed.metric, StorableMetric::Cosine));
}
for (key, rejected) in [
(KEY_QUANTIZATION, Value::String("yes".into())),
(KEY_HNSW_M, Value::String("16".into())),
(KEY_HNSW_EF, Value::Float(16.0)),
(KEY_QUANTIZATION_TYPE, Value::Bool(false)),
(KEY_QUANTIZATION_TYPE, Value::Int(0)),
(KEY_QUANTIZATION_TYPE, Value::Null),
] {
let rejected_config = map(&[(key, rejected.clone())]);
assert!(
parse_config(&rejected_config).is_err(),
"{key} rejects {rejected:?}"
);
}
let unknown = map(&[("vector.unknown", Value::Int(1))]);
assert!(parse_config(&unknown).is_err(), "unknown key is rejected");
}
#[test]
fn the_storable_subset_is_exactly_the_two_index_metrics() {
for (keyword, metric) in VectorMetric::ALL {
let config = map(&[(KEY_SIMILARITY, Value::String(keyword.into()))]);
let parsed = parse_config(&config);
let storable = StorableMetric::try_from(metric).is_ok();
assert_eq!(
parsed.is_ok(),
storable,
"{keyword} parses exactly when the narrowing admits it"
);
if storable {
assert_eq!(
VectorMetric::from(parsed.expect("is_ok was asserted above").metric),
metric,
"{keyword} round-trips as its own variant"
);
}
}
let absent = map(&[(KEY_DIMENSIONS, Value::Int(4))]);
assert_eq!(
parse_config(&absent)
.expect("an absent key defaults")
.metric,
StorableMetric::Cosine
);
}
}
#[cfg(test)]
mod default_tests {
use super::*;
#[test]
fn defaults_match_live_neo4j_and_follow_the_quantization_type() {
let mut config = BTreeMap::new();
let parsed = parse_config(&config).expect("an empty config parses");
assert_eq!(parsed.quantization, QUANTIZATION_BINARY);
apply_defaults(&mut config, parsed.metric, &parsed.quantization);
assert_eq!(config.get(KEY_SEARCH_EXPANSION), Some(&Value::Float(3.0)));
assert_eq!(
config.get(KEY_QUANTIZATION_TYPE),
Some(&Value::String(QUANTIZATION_BINARY.into()))
);
assert_eq!(config.get(KEY_HNSW_M), Some(&Value::Int(16)));
assert_eq!(config.get(KEY_HNSW_EF), Some(&Value::Int(100)));
let mut none = BTreeMap::new();
none.insert(KEY_QUANTIZATION_TYPE.into(), Value::String("none".into()));
let parsed = parse_config(&none).expect("a string quantization type parses");
assert_eq!(parsed.quantization, QUANTIZATION_NONE);
apply_defaults(&mut none, parsed.metric, &parsed.quantization);
assert_eq!(
none.get(KEY_QUANTIZATION_TYPE),
Some(&Value::String(QUANTIZATION_NONE.into()))
);
assert_eq!(none.get(KEY_SEARCH_EXPANSION), Some(&Value::Float(1.0)));
}
}