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";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum QuantizationType {
Scalar,
Binary,
None,
}
impl QuantizationType {
const ALL: [(&'static str, Self); 3] = [
("SCALAR", Self::Scalar),
("BINARY", Self::Binary),
("NONE", Self::None),
];
fn name(self) -> &'static str {
Self::ALL
.into_iter()
.find(|(_, member)| *member == self)
.map(|(spelling, _)| spelling)
.expect("every QuantizationType is listed in ALL")
}
fn from_spelling(name: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|(spelling, _)| spelling.eq_ignore_ascii_case(name))
.map(|(_, member)| member)
}
fn supported_values() -> String {
Self::ALL
.iter()
.map(|(spelling, _)| format!("'{spelling}'"))
.collect::<Vec<_>>()
.join(", ")
}
}
#[derive(Clone, Copy, PartialEq)]
enum KeyShape {
Int,
Number,
}
impl KeyShape {
fn admits(self, value: &Value) -> bool {
matches!(
(self, value),
(Self::Int, Value::Int(_)) | (Self::Number, Value::Int(_) | Value::Float(_))
)
}
}
#[derive(Clone, Copy)]
enum KeyRule {
Dimension,
Metric,
Quantization,
LegacyQuantization,
Shape(KeyShape),
}
const CONFIG_KEYS: [(&str, KeyRule); 7] = [
(KEY_DIMENSIONS, KeyRule::Dimension),
(KEY_SIMILARITY, KeyRule::Metric),
(KEY_QUANTIZATION, KeyRule::LegacyQuantization),
(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 =
*relate_model::VECTOR_DIMENSION_RANGE.start() as usize;
pub(crate) const VECTOR_DIMENSIONS_MAX: usize =
*relate_model::VECTOR_DIMENSION_RANGE.end() as usize;
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: Option<QuantizationType> = None;
let mut legacy: Option<QuantizationType> = None;
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 =
Some(QuantizationType::from_spelling(name).ok_or_else(|| {
Error::argument_error(format!(
"Invalid input for '{KEY_QUANTIZATION_TYPE}': '{name}'. \
Expected one of {}.",
QuantizationType::supported_values()
))
})?);
}
_ => return Err(Error::argument_error("InvalidInputValue")),
},
KeyRule::LegacyQuantization => match value {
Value::Bool(enabled) => {
legacy = Some(if *enabled {
QuantizationType::Scalar
} else {
QuantizationType::None
})
}
_ => return Err(Error::argument_error("InvalidInputValue")),
},
KeyRule::Shape(shape) => {
if !shape.admits(value) {
return Err(Error::argument_error("InvalidInputValue"));
}
}
}
}
let quantization = quantization.or(legacy).unwrap_or(QuantizationType::Binary);
Ok(StoredVectorConfig {
dimension,
metric,
quantization,
})
}
#[derive(Debug)]
pub(crate) struct StoredVectorConfig {
pub dimension: Option<usize>,
pub metric: StorableMetric,
pub quantization: QuantizationType,
}
pub(crate) fn parse_stored_config(config: &BTreeMap<String, Value>) -> Result<StoredVectorConfig> {
if matches!(
config.get(KEY_QUANTIZATION_TYPE),
Some(Value::String(stored)) if stored.eq_ignore_ascii_case("INT8")
) {
let mut folded = config.clone();
folded.insert(
KEY_QUANTIZATION_TYPE.into(),
Value::String(QuantizationType::Scalar.name().into()),
);
return parse_config(&folded);
}
parse_config(config)
}
pub(crate) fn apply_defaults(config: &mut BTreeMap<String, Value>, parsed: &StoredVectorConfig) {
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(parsed.quantization.name().into()),
);
let expansion_default = match parsed.quantization {
QuantizationType::None => 1.0,
QuantizationType::Scalar => 1.5,
QuantizationType::Binary => 3.0,
};
config
.entry(KEY_SEARCH_EXPANSION.into())
.or_insert(Value::Float(expansion_default));
config.insert(
KEY_SIMILARITY.into(),
Value::String(parsed.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));
}
let mut spellings: Vec<&str> = QuantizationType::ALL.iter().map(|(s, _)| *s).collect();
spellings.sort_unstable();
spellings.dedup();
assert_eq!(
spellings.len(),
QuantizationType::ALL.len(),
"spellings are unique"
);
for (spelling, member) in QuantizationType::ALL {
for form in [spelling, spelling.to_ascii_lowercase().as_str()] {
let parsed =
parse_config(&map(&[(KEY_QUANTIZATION_TYPE, Value::String(form.into()))]))
.expect("an in-vocabulary spelling parses");
assert_eq!(parsed.quantization, member, "{form:?}");
}
}
for rejected in ["int8", "INT8", "Bogus", ""] {
let error = parse_config(&map(&[(
KEY_QUANTIZATION_TYPE,
Value::String(rejected.into()),
)]))
.expect_err("an out-of-vocabulary spelling is rejected");
assert!(
format!("{error}").contains(&QuantizationType::supported_values()),
"{rejected:?} rejection lists the supported values: {error}"
);
}
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::*;
use crate::test_support::map;
#[test]
fn stored_int8_folds_onto_scalar() {
for stored in ["INT8", "int8"] {
let parsed = parse_stored_config(&map(&[(
KEY_QUANTIZATION_TYPE,
Value::String(stored.into()),
)]))
.expect("the stored legacy spelling folds onto SCALAR");
assert_eq!(parsed.quantization, QuantizationType::Scalar);
}
assert!(parse_stored_config(&map(&[(
KEY_QUANTIZATION_TYPE,
Value::String("Bogus".into()),
)]))
.is_err());
}
#[test]
fn defaults_match_live_neo4j_and_follow_the_quantization_type() {
let mut config = map(&[]);
let parsed = parse_config(&config).expect("an empty config parses");
assert_eq!(parsed.quantization, QuantizationType::Binary);
apply_defaults(&mut config, &parsed);
assert_eq!(config.get(KEY_SEARCH_EXPANSION), Some(&Value::Float(3.0)));
assert_eq!(
config.get(KEY_QUANTIZATION_TYPE),
Some(&Value::String(QuantizationType::Binary.name().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 = map(&[(KEY_QUANTIZATION_TYPE, Value::String("none".into()))]);
let parsed = parse_config(&none).expect("a string quantization type parses");
assert_eq!(parsed.quantization, QuantizationType::None);
apply_defaults(&mut none, &parsed);
assert_eq!(
none.get(KEY_QUANTIZATION_TYPE),
Some(&Value::String(QuantizationType::None.name().into()))
);
assert_eq!(none.get(KEY_SEARCH_EXPANSION), Some(&Value::Float(1.0)));
let mut scalar = map(&[(KEY_QUANTIZATION_TYPE, Value::String("Scalar".into()))]);
let parsed = parse_config(&scalar).expect("an in-vocabulary type parses");
assert_eq!(parsed.quantization, QuantizationType::Scalar);
apply_defaults(&mut scalar, &parsed);
assert_eq!(scalar.get(KEY_SEARCH_EXPANSION), Some(&Value::Float(1.5)));
for (enabled, canonical, expansion) in [
(true, QuantizationType::Scalar, 1.5),
(false, QuantizationType::None, 1.0),
] {
let mut legacy = map(&[(KEY_QUANTIZATION, Value::Bool(enabled))]);
let parsed = parse_config(&legacy).expect("the legacy spelling is admitted");
assert_eq!(parsed.quantization, canonical);
apply_defaults(&mut legacy, &parsed);
assert_eq!(
legacy.get(KEY_QUANTIZATION_TYPE),
Some(&Value::String(canonical.name().into()))
);
assert_eq!(
legacy.get(KEY_SEARCH_EXPANSION),
Some(&Value::Float(expansion))
);
}
let both = map(&[
(KEY_QUANTIZATION, Value::Bool(false)),
(KEY_QUANTIZATION_TYPE, Value::String("binary".into())),
]);
let parsed = parse_config(&both).expect("both keys are admitted together");
assert_eq!(parsed.quantization, QuantizationType::Binary);
}
}