use std::collections::BTreeMap;
use std::ops::Bound;
use bytes::{Bytes, BytesMut};
use object_store::path::Path;
use object_store::{GetOptions, GetRange, ObjectStore, ObjectStoreExt};
use crate::attrs::AttrType;
use crate::budget::ReadBudget;
use crate::error::{ItzmaError, Result};
const MAGIC: [u8; 4] = *b"ITZT";
pub(crate) const FORMAT_VERSION: u32 = 1;
const HEADER_LEN: usize = 4 + 4 + 4 + 4;
const OBJECT_PREFIX: &str = "attr-idx-";
const OBJECT_SUFFIX: &str = ".bin";
fn corrupt(path: &str, reason: impl Into<String>) -> ItzmaError {
ItzmaError::CorruptAttrIndex {
path: path.to_string(),
reason: reason.into(),
}
}
const MISSING: &str = "missing from the store";
pub(crate) fn missing(path: &Path) -> ItzmaError {
corrupt(path.as_ref(), MISSING)
}
pub(crate) fn is_missing(err: &ItzmaError) -> bool {
matches!(err, ItzmaError::CorruptAttrIndex { reason, .. } if reason == MISSING)
}
pub(crate) fn attr_index_path(namespace: &str, id: &str, generation: u32) -> Path {
Path::from(format!(
"{namespace}/segments/{id}/{OBJECT_PREFIX}{generation}{OBJECT_SUFFIX}"
))
}
pub(crate) fn generation_of(file_name: &str) -> Option<u32> {
let digits = file_name
.strip_prefix(OBJECT_PREFIX)?
.strip_suffix(OBJECT_SUFFIX)?;
let generation: u32 = digits.parse().ok()?;
(generation >= 1 && generation.to_string() == digits).then_some(generation)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Bool,
Number,
Text,
}
impl Kind {
pub(crate) fn of(ty: AttrType) -> Kind {
match ty {
AttrType::Bool => Kind::Bool,
AttrType::Number | AttrType::NumberSet => Kind::Number,
AttrType::Text | AttrType::TextSet => Kind::Text,
}
}
fn to_u8(self) -> u8 {
match self {
Kind::Bool => 0,
Kind::Number => 1,
Kind::Text => 2,
}
}
fn from_u8(byte: u8) -> Option<Kind> {
match byte {
0 => Some(Kind::Bool),
1 => Some(Kind::Number),
2 => Some(Kind::Text),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Value {
Bool(bool),
Number(f64),
Text(String),
}
impl Value {
fn number(n: f64) -> Value {
Value::Number(if n == 0.0 { 0.0 } else { n })
}
fn cmp(&self, other: &Value) -> std::cmp::Ordering {
match (self, other) {
(Value::Bool(a), Value::Bool(b)) => a.cmp(b),
(Value::Number(a), Value::Number(b)) => a.total_cmp(b),
(Value::Text(a), Value::Text(b)) => a.cmp(b),
_ => std::cmp::Ordering::Equal,
}
}
}
fn write_value(out: &mut BytesMut, value: &Value) {
match value {
Value::Bool(v) => out.extend_from_slice(&[u8::from(*v)]),
Value::Number(v) => out.extend_from_slice(&v.to_bits().to_le_bytes()),
Value::Text(v) => {
let bytes = v.as_bytes();
out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
out.extend_from_slice(bytes);
}
}
}
pub(crate) struct FieldBuild {
pub(crate) kind: Kind,
pub(crate) entries: Vec<(Value, Vec<u32>)>,
}
pub(crate) fn group_sorted(mut pairs: Vec<(Value, u32)>) -> Vec<(Value, Vec<u32>)> {
pairs.sort_by(|(a, ra), (b, rb)| a.cmp(b).then(ra.cmp(rb)));
let mut out: Vec<(Value, Vec<u32>)> = Vec::new();
for (value, row) in pairs {
match out.last_mut() {
Some((last, rows)) if last.cmp(&value) == std::cmp::Ordering::Equal => {
if rows.last() != Some(&row) {
rows.push(row);
}
}
_ => out.push((value, vec![row])),
}
}
out
}
pub(crate) fn build(rows: u32, fields: &BTreeMap<String, FieldBuild>) -> Bytes {
let mut dir = BytesMut::new();
let mut body = BytesMut::new();
for (name, field) in fields {
let name_bytes = name.as_bytes();
dir.extend_from_slice(&(name_bytes.len() as u16).to_le_bytes());
dir.extend_from_slice(name_bytes);
dir.extend_from_slice(&[field.kind.to_u8()]);
dir.extend_from_slice(&(field.entries.len() as u32).to_le_bytes());
for (value, rows_for_value) in &field.entries {
write_value(&mut body, value);
body.extend_from_slice(&(rows_for_value.len() as u32).to_le_bytes());
for row in rows_for_value {
body.extend_from_slice(&row.to_le_bytes());
}
}
}
let mut out = BytesMut::with_capacity(HEADER_LEN + dir.len() + body.len());
out.extend_from_slice(&MAGIC);
out.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
out.extend_from_slice(&rows.to_le_bytes());
out.extend_from_slice(&(fields.len() as u32).to_le_bytes());
out.extend_from_slice(&dir);
out.extend_from_slice(&body);
out.freeze()
}
struct Reader<'a> {
path: &'a str,
buf: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
fn new(path: &'a str, buf: &'a [u8]) -> Self {
Self { path, buf, pos: 0 }
}
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
let out = self
.buf
.get(self.pos..)
.and_then(|rest| rest.get(..n))
.ok_or_else(|| corrupt(self.path, "object is truncated"))?;
self.pos += n;
Ok(out)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<u16> {
let b = self.take(2)?;
Ok(u16::from_le_bytes([b[0], b[1]]))
}
fn u32(&mut self) -> Result<u32> {
let b = self.take(4)?;
Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
fn f64(&mut self) -> Result<f64> {
let b = self.take(8)?;
let mut a = [0u8; 8];
a.copy_from_slice(b);
Ok(f64::from_le_bytes(a))
}
fn text(&mut self, len: usize) -> Result<String> {
let bytes = self.take(len)?;
String::from_utf8(bytes.to_vec())
.map_err(|_| corrupt(self.path, "a text value is not valid UTF-8"))
}
}
#[derive(Debug)]
pub(crate) struct FieldIndex {
entries: Vec<(Value, Vec<u32>)>,
}
impl FieldIndex {
pub(crate) fn rows_eq(&self, value: &Value) -> Vec<u32> {
self.entries
.binary_search_by(|(v, _)| v.cmp(value))
.map(|at| self.entries[at].1.clone())
.unwrap_or_default()
}
pub(crate) fn rows_range(&self, low: Bound<&Value>, high: Bound<&Value>) -> Vec<u32> {
use std::cmp::Ordering;
let start = match low {
Bound::Unbounded => 0,
Bound::Included(v) => self
.entries
.partition_point(|(e, _)| e.cmp(v) == Ordering::Less),
Bound::Excluded(v) => self
.entries
.partition_point(|(e, _)| e.cmp(v) != Ordering::Greater),
};
let end = match high {
Bound::Unbounded => self.entries.len(),
Bound::Included(v) => self
.entries
.partition_point(|(e, _)| e.cmp(v) != Ordering::Greater),
Bound::Excluded(v) => self
.entries
.partition_point(|(e, _)| e.cmp(v) == Ordering::Less),
};
let mut out: Vec<u32> = self.entries[start..end.max(start)]
.iter()
.flat_map(|(_, rows)| rows.iter().copied())
.collect();
out.sort_unstable();
out
}
}
#[derive(Debug)]
pub(crate) struct AttrIndex {
fields: BTreeMap<String, FieldIndex>,
}
impl AttrIndex {
pub(crate) fn field(&self, name: &str) -> Option<&FieldIndex> {
self.fields.get(name)
}
}
fn decode(path: &str, bytes: &[u8], rows: u64) -> Result<AttrIndex> {
let mut r = Reader::new(path, bytes);
if r.take(4)? != MAGIC {
return Err(corrupt(path, "bad magic"));
}
match r.u32()? {
FORMAT_VERSION => {}
version => return Err(ItzmaError::UnsupportedFormat { version }),
}
let got_rows = u64::from(r.u32()?);
if got_rows != rows {
return Err(corrupt(
path,
format!("{got_rows} rows, the segment has {rows}"),
));
}
let field_count = r.u32()?;
struct DirEntry {
name: String,
kind: Kind,
entry_count: u32,
}
let mut dir = Vec::new();
let mut last_name: Option<String> = None;
for _ in 0..field_count {
let name_len = r.u16()? as usize;
let name = r.text(name_len)?;
if last_name.as_ref().is_some_and(|last| &name <= last) {
return Err(corrupt(
path,
"field directory is not sorted by ascending name",
));
}
last_name = Some(name.clone());
let kind = Kind::from_u8(r.u8()?).ok_or_else(|| corrupt(path, "unknown field kind"))?;
let entry_count = r.u32()?;
dir.push(DirEntry {
name,
kind,
entry_count,
});
}
let mut fields = BTreeMap::new();
for entry in dir {
let mut values: Vec<(Value, Vec<u32>)> = Vec::new();
let mut last_value: Option<Value> = None;
for _ in 0..entry.entry_count {
let value = match entry.kind {
Kind::Bool => Value::Bool(r.u8()? != 0),
Kind::Number => Value::Number(r.f64()?),
Kind::Text => {
let len = r.u32()? as usize;
Value::Text(r.text(len)?)
}
};
if last_value
.as_ref()
.is_some_and(|last| last.cmp(&value) != std::cmp::Ordering::Less)
{
return Err(corrupt(
path,
format!("{}'s entries are not sorted by ascending value", entry.name),
));
}
last_value = Some(value.clone());
let row_count = r.u32()?;
let mut row_list = Vec::new();
let mut last_row: Option<u32> = None;
for _ in 0..row_count {
let row = r.u32()?;
if u64::from(row) >= rows {
return Err(corrupt(
path,
format!(
"{}'s entry names row {row}, the segment has {rows} rows",
entry.name
),
));
}
if last_row.is_some_and(|last| row <= last) {
return Err(corrupt(
path,
format!("{}'s rows are not sorted by ascending row", entry.name),
));
}
last_row = Some(row);
row_list.push(row);
}
values.push((value, row_list));
}
fields.insert(entry.name, FieldIndex { entries: values });
}
Ok(AttrIndex { fields })
}
pub(crate) fn open_bytes_for_check(path: &str, bytes: &[u8], rows: u64) -> Result<()> {
decode(path, bytes, rows).map(|_| ())
}
const HEAD_GUESS: u64 = 64 * 1024;
async fn get_range(
store: &dyn ObjectStore,
budget: &ReadBudget,
path: &Path,
range: std::ops::Range<u64>,
) -> Result<Bytes> {
if range.end <= range.start {
return Ok(Bytes::new());
}
budget.charge(path.as_ref(), range.end - range.start)?;
match store.get_range(path, range).await {
Ok(bytes) => Ok(bytes),
Err(object_store::Error::NotFound { .. }) => Err(missing(path)),
Err(e) => Err(e.into()),
}
}
pub(crate) async fn open(
store: &dyn ObjectStore,
budget: &ReadBudget,
path: &Path,
rows: u64,
) -> Result<AttrIndex> {
let name = path.as_ref();
budget.charge(name, HEAD_GUESS)?;
let options = GetOptions {
range: Some(GetRange::Bounded(0..HEAD_GUESS)),
..GetOptions::default()
};
let got = match store.get_opts(path, options).await {
Ok(got) => got,
Err(object_store::Error::NotFound { .. }) => return Err(missing(path)),
Err(e) => return Err(e.into()),
};
let size = got.meta.size;
let first = got.bytes().await?;
if size <= first.len() as u64 {
return decode(name, &first, rows);
}
let rest = get_range(store, budget, path, first.len() as u64..size).await?;
let whole: Vec<u8> = first.iter().copied().chain(rest.iter().copied()).collect();
decode(name, &whole, rows)
}
use std::collections::BTreeSet;
use crate::predicate::{AttrValue, Compare, Predicate, TextCompare};
fn intersect(a: &[u32], b: &[u32]) -> Vec<u32> {
let a: BTreeSet<u32> = a.iter().copied().collect();
b.iter().copied().filter(|r| a.contains(r)).collect()
}
fn union(a: &[u32], b: &[u32]) -> Vec<u32> {
let mut out: BTreeSet<u32> = a.iter().copied().collect();
out.extend(b.iter().copied());
out.into_iter().collect()
}
fn attr_value_to_value(v: &AttrValue) -> Value {
match v {
AttrValue::Number(n) => Value::number(*n),
AttrValue::Text(s) => Value::Text(s.clone()),
}
}
pub(crate) fn could_resolve(predicate: &Predicate, indexed: &BTreeSet<&str>) -> bool {
match predicate {
Predicate::And(items) => items.iter().any(|item| could_resolve(item, indexed)),
Predicate::Or(items) => items.iter().all(|item| could_resolve(item, indexed)),
Predicate::Not(_)
| Predicate::IsNull(_)
| Predicate::IsNotNull(_)
| Predicate::IsEmpty(_) => false,
Predicate::IsTrue(field)
| Predicate::IsFalse(field)
| Predicate::NumberIn { field, .. }
| Predicate::Between { field, .. }
| Predicate::TextIn { field, .. }
| Predicate::Contains { field, .. }
| Predicate::ContainsAny { field, .. }
| Predicate::ContainsAll { field, .. } => indexed.contains(field.as_str()),
Predicate::Number { field, op, .. } => {
*op != Compare::Ne && indexed.contains(field.as_str())
}
Predicate::Text { field, op, .. } => {
*op == TextCompare::Eq && indexed.contains(field.as_str())
}
}
}
pub(crate) fn index_candidates(predicate: &Predicate, index: &AttrIndex) -> Option<Vec<u32>> {
match predicate {
Predicate::And(items) => {
let mut acc: Option<Vec<u32>> = None;
for item in items {
if let Some(rows) = index_candidates(item, index) {
acc = Some(match acc {
Some(existing) => intersect(&existing, &rows),
None => rows,
});
}
}
acc
}
Predicate::Or(items) => {
let mut acc: Option<Vec<u32>> = Some(Vec::new());
for item in items {
let rows = index_candidates(item, index)?;
acc = acc.map(|existing| union(&existing, &rows));
}
acc
}
Predicate::Not(_)
| Predicate::IsNull(_)
| Predicate::IsNotNull(_)
| Predicate::IsEmpty(_) => None,
Predicate::IsTrue(field) => index.field(field).map(|f| f.rows_eq(&Value::Bool(true))),
Predicate::IsFalse(field) => index.field(field).map(|f| f.rows_eq(&Value::Bool(false))),
Predicate::Number { field, op, value } => {
let f = index.field(field)?;
let v = Value::number(*value);
Some(match op {
Compare::Eq => f.rows_eq(&v),
Compare::Ne => return None,
Compare::Lt => {
f.rows_range(std::ops::Bound::Unbounded, std::ops::Bound::Excluded(&v))
}
Compare::Le => {
f.rows_range(std::ops::Bound::Unbounded, std::ops::Bound::Included(&v))
}
Compare::Gt => {
f.rows_range(std::ops::Bound::Excluded(&v), std::ops::Bound::Unbounded)
}
Compare::Ge => {
f.rows_range(std::ops::Bound::Included(&v), std::ops::Bound::Unbounded)
}
})
}
Predicate::NumberIn { field, values } => {
let f = index.field(field)?;
Some(
values
.iter()
.map(|v| f.rows_eq(&Value::number(*v)))
.fold(Vec::new(), |acc, rows| union(&acc, &rows)),
)
}
Predicate::Between { field, low, high } => {
let f = index.field(field)?;
Some(f.rows_range(
std::ops::Bound::Included(&Value::number(*low)),
std::ops::Bound::Included(&Value::number(*high)),
))
}
Predicate::Text { field, op, value } => {
let f = index.field(field)?;
match op {
TextCompare::Eq => Some(f.rows_eq(&Value::Text(value.clone()))),
TextCompare::Ne | TextCompare::StartsWith => None,
}
}
Predicate::TextIn { field, values } => {
let f = index.field(field)?;
Some(
values
.iter()
.map(|v| f.rows_eq(&Value::Text(v.clone())))
.fold(Vec::new(), |acc, rows| union(&acc, &rows)),
)
}
Predicate::Contains { field, value } => {
let f = index.field(field)?;
Some(f.rows_eq(&attr_value_to_value(value)))
}
Predicate::ContainsAny { field, values } => {
let f = index.field(field)?;
Some(
values
.iter()
.map(|v| f.rows_eq(&attr_value_to_value(v)))
.fold(Vec::new(), |acc, rows| union(&acc, &rows)),
)
}
Predicate::ContainsAll { field, values } => {
let f = index.field(field)?;
let mut iter = values.iter().map(|v| f.rows_eq(&attr_value_to_value(v)));
let first = iter.next()?;
Some(iter.fold(first, |acc, rows| intersect(&acc, &rows)))
}
}
}
pub(crate) fn field_value(
attrs: Option<&serde_json::Value>,
field: &str,
ty: AttrType,
) -> Option<Value> {
let value = attrs?.get(field)?;
if value.is_null() {
return None;
}
match ty {
AttrType::Bool => value.as_bool().map(Value::Bool),
AttrType::Number => value.as_f64().map(Value::number),
AttrType::Text => value.as_str().map(|s| Value::Text(s.to_string())),
AttrType::TextSet | AttrType::NumberSet => None,
}
}
pub(crate) fn field_elements(
attrs: Option<&serde_json::Value>,
field: &str,
ty: AttrType,
) -> Vec<Value> {
let Some(items) = attrs
.and_then(|a| a.get(field))
.and_then(serde_json::Value::as_array)
else {
return Vec::new();
};
items
.iter()
.filter_map(|item| match ty {
AttrType::TextSet => item.as_str().map(|s| Value::Text(s.to_string())),
AttrType::NumberSet => item.as_f64().map(Value::number),
AttrType::Bool | AttrType::Number | AttrType::Text => None,
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn b(v: bool) -> Value {
Value::Bool(v)
}
fn n(v: f64) -> Value {
Value::Number(v)
}
fn t(v: &str) -> Value {
Value::Text(v.into())
}
fn sample_fields() -> BTreeMap<String, FieldBuild> {
let mut fields = BTreeMap::new();
fields.insert(
"active".to_string(),
FieldBuild {
kind: Kind::Bool,
entries: vec![(b(false), vec![1]), (b(true), vec![0, 2])],
},
);
fields.insert(
"price".to_string(),
FieldBuild {
kind: Kind::Number,
entries: vec![(n(1.5), vec![0]), (n(9.0), vec![1, 2])],
},
);
fields.insert(
"tags".to_string(),
FieldBuild {
kind: Kind::Text,
entries: vec![(t("a"), vec![0, 1]), (t("b"), vec![1])],
},
);
fields
}
#[test]
fn build_open_and_lookups_round_trip() {
let bytes = build(3, &sample_fields());
let index = decode("p", &bytes, 3).expect("decode");
let active = index.field("active").expect("active present");
assert_eq!(active.rows_eq(&b(true)), vec![0, 2]);
assert_eq!(active.rows_eq(&b(false)), vec![1]);
let price = index.field("price").expect("price present");
assert_eq!(price.rows_eq(&n(9.0)), vec![1, 2]);
assert_eq!(price.rows_eq(&n(2.0)), Vec::<u32>::new());
assert_eq!(
price.rows_range(Bound::Included(&n(1.5)), Bound::Included(&n(9.0))),
vec![0, 1, 2]
);
assert_eq!(
price.rows_range(Bound::Excluded(&n(1.5)), Bound::Unbounded),
vec![1, 2]
);
assert_eq!(
price.rows_range(Bound::Unbounded, Bound::Excluded(&n(9.0))),
vec![0]
);
let tags = index.field("tags").expect("tags present");
assert_eq!(tags.rows_eq(&t("a")), vec![0, 1]);
assert_eq!(tags.rows_eq(&t("z")), Vec::<u32>::new());
assert!(index.field("nope").is_none());
}
#[test]
fn group_sorted_groups_equal_values_and_sorts_rows_within_a_group() {
let grouped = group_sorted(vec![(n(2.0), 5), (n(1.0), 1), (n(2.0), 0)]);
assert_eq!(grouped, vec![(n(1.0), vec![1]), (n(2.0), vec![0, 5])]);
}
#[test]
fn group_sorted_dedups_the_same_row_appearing_twice_for_one_value() {
let grouped = group_sorted(vec![(t("a"), 3), (t("a"), 3), (t("a"), 1)]);
assert_eq!(grouped, vec![(t("a"), vec![1, 3])]);
}
#[test]
fn decode_rejects_a_row_count_mismatch() {
let bytes = build(3, &sample_fields());
let err = decode("p", &bytes, 4).unwrap_err();
assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
}
#[test]
fn decode_rejects_a_row_past_the_segment() {
let mut fields = BTreeMap::new();
fields.insert(
"active".to_string(),
FieldBuild {
kind: Kind::Bool,
entries: vec![(b(true), vec![5])],
},
);
let bytes = build(3, &fields);
let err = decode("p", &bytes, 3).unwrap_err();
assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
}
#[test]
fn every_truncation_and_bit_flip_is_refused_never_panics() {
let bytes = build(3, &sample_fields());
for len in 0..bytes.len() {
let _ = decode("p", &bytes.slice(..len), 3); }
for i in 0..bytes.len() {
let mut bad = bytes.to_vec();
bad[i] ^= 0xFF;
let _ = decode("p", &bad, 3); }
}
#[test]
fn a_huge_field_count_is_refused_not_preallocated() {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(&MAGIC);
bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(&u32::MAX.to_le_bytes()); let err = decode("p", &bytes, 3).unwrap_err();
assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
}
#[test]
fn a_huge_entry_count_is_refused_not_preallocated() {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(&MAGIC);
bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&1u16.to_le_bytes()); bytes.extend_from_slice(b"x"); bytes.extend_from_slice(&[0u8]); bytes.extend_from_slice(&u32::MAX.to_le_bytes()); let err = decode("p", &bytes, 3).unwrap_err();
assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
}
#[test]
fn a_huge_row_count_is_refused_not_preallocated() {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(&MAGIC);
bytes.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
bytes.extend_from_slice(&3u32.to_le_bytes()); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&1u16.to_le_bytes()); bytes.extend_from_slice(b"x"); bytes.extend_from_slice(&[0u8]); bytes.extend_from_slice(&1u32.to_le_bytes()); bytes.extend_from_slice(&[1u8]); bytes.extend_from_slice(&u32::MAX.to_le_bytes()); let err = decode("p", &bytes, 3).unwrap_err();
assert!(matches!(err, ItzmaError::CorruptAttrIndex { .. }));
}
#[tokio::test]
async fn open_fetches_and_decodes_from_a_store() {
let bytes = build(3, &sample_fields());
let store = object_store::memory::InMemory::new();
let path = Path::from("p");
store.put(&path, bytes.into()).await.expect("put");
let budget = ReadBudget::unlimited();
let index = open(&store, &budget, &path, 3).await.expect("open");
assert_eq!(index.field("price").unwrap().rows_eq(&n(9.0)), vec![1, 2]);
}
#[tokio::test]
async fn open_of_a_missing_object_is_missing() {
let store = object_store::memory::InMemory::new();
let path = Path::from("p");
let budget = ReadBudget::unlimited();
let err = open(&store, &budget, &path, 3).await.unwrap_err();
assert!(is_missing(&err));
}
#[test]
fn only_the_exact_object_name_has_a_generation() {
assert_eq!(generation_of("attr-idx-1.bin"), Some(1));
assert_eq!(generation_of("attr-idx-42.bin"), Some(42));
for name in [
"data.bin",
"sparse.bin",
"index-1.bin",
"attr-idx-0.bin",
"attr-idx-.bin",
"attr-idx-1",
] {
assert_eq!(generation_of(name), None, "{name}");
}
}
#[test]
fn an_attr_index_lives_beside_its_segment() {
assert_eq!(
attr_index_path("docs", "0001-0002", 3).as_ref(),
"docs/segments/0001-0002/attr-idx-3.bin"
);
}
use crate::predicate::{AttrValue, Compare, Predicate, TextCompare};
fn index_with(fields: BTreeMap<String, FieldBuild>) -> AttrIndex {
let bytes = build(10, &fields);
decode("p", &bytes, 10).unwrap()
}
fn two_field_index() -> AttrIndex {
let mut fields = BTreeMap::new();
fields.insert(
"price".to_string(),
FieldBuild {
kind: Kind::Number,
entries: vec![(n(1.0), vec![0]), (n(5.0), vec![1, 2]), (n(9.0), vec![3])],
},
);
fields.insert(
"tags".to_string(),
FieldBuild {
kind: Kind::Text,
entries: vec![
(t("a"), vec![0, 1, 4]),
(t("b"), vec![1, 2]),
(t("c"), vec![2]),
],
},
);
index_with(fields)
}
#[test]
fn a_leaf_on_an_indexed_number_field_resolves_exactly() {
let index = two_field_index();
let p = Predicate::number("price", Compare::Eq, 5.0);
assert_eq!(index_candidates(&p, &index), Some(vec![1, 2]));
}
#[test]
fn compare_lt_le_gt_ge_all_resolve_via_range() {
let index = two_field_index();
let cases = [
(Compare::Lt, 5.0, vec![0]),
(Compare::Le, 5.0, vec![0, 1, 2]),
(Compare::Gt, 5.0, vec![3]),
(Compare::Ge, 5.0, vec![1, 2, 3]),
];
for (op, at, want) in cases {
let p = Predicate::number("price", op, at);
assert_eq!(index_candidates(&p, &index), Some(want), "{op:?}");
}
}
#[test]
fn compare_ne_does_not_resolve() {
let index = two_field_index();
let p = Predicate::number("price", Compare::Ne, 5.0);
assert_eq!(index_candidates(&p, &index), None);
}
#[test]
fn between_and_number_in_resolve() {
let index = two_field_index();
let between = Predicate::Between {
field: "price".into(),
low: 1.0,
high: 5.0,
};
assert_eq!(index_candidates(&between, &index), Some(vec![0, 1, 2]));
let inn = Predicate::NumberIn {
field: "price".into(),
values: vec![1.0, 9.0],
};
assert_eq!(index_candidates(&inn, &index), Some(vec![0, 3]));
}
#[test]
fn text_eq_resolves_but_ne_and_starts_with_do_not() {
let index = two_field_index();
let eq = Predicate::text("tags", TextCompare::Eq, "b");
assert_eq!(index_candidates(&eq, &index), Some(vec![1, 2]));
let ne = Predicate::text("tags", TextCompare::Ne, "b");
assert_eq!(index_candidates(&ne, &index), None);
let starts = Predicate::text("tags", TextCompare::StartsWith, "b");
assert_eq!(index_candidates(&starts, &index), None);
}
#[test]
fn text_in_resolves_as_a_union() {
let index = two_field_index();
let p = Predicate::TextIn {
field: "tags".into(),
values: vec!["a".into(), "c".into()],
};
assert_eq!(index_candidates(&p, &index), Some(vec![0, 1, 2, 4]));
}
#[test]
fn contains_any_all_resolve_as_union_and_intersection() {
let index = two_field_index();
let any = Predicate::ContainsAny {
field: "tags".into(),
values: vec![AttrValue::Text("a".into()), AttrValue::Text("c".into())],
};
assert_eq!(index_candidates(&any, &index), Some(vec![0, 1, 2, 4]));
let all = Predicate::ContainsAll {
field: "tags".into(),
values: vec![AttrValue::Text("a".into()), AttrValue::Text("b".into())],
};
assert_eq!(index_candidates(&all, &index), Some(vec![1]));
}
#[test]
fn a_field_that_is_not_indexed_does_not_resolve() {
let index = two_field_index();
let p = Predicate::is_true("active"); assert_eq!(index_candidates(&p, &index), None);
let unresolvable = [
Predicate::IsNull("price".into()),
Predicate::IsNotNull("price".into()),
Predicate::IsEmpty("tags".into()),
];
for p in unresolvable {
assert_eq!(index_candidates(&p, &index), None, "{p:?}");
}
}
#[test]
fn not_never_resolves() {
let index = two_field_index();
let p = Predicate::negate(Predicate::number("price", Compare::Eq, 5.0));
assert_eq!(index_candidates(&p, &index), None);
}
#[test]
fn could_resolve_agrees_with_index_candidates_but_needs_no_index() {
let index = two_field_index();
let indexed: BTreeSet<&str> = BTreeSet::from(["price", "tags"]);
let cases = [
Predicate::number("price", Compare::Eq, 5.0),
Predicate::number("price", Compare::Lt, 5.0),
Predicate::number("price", Compare::Ne, 5.0), Predicate::text("tags", TextCompare::Eq, "b"),
Predicate::text("tags", TextCompare::StartsWith, "b"), Predicate::is_true("active"), Predicate::IsNull("price".into()), Predicate::negate(Predicate::number("price", Compare::Eq, 5.0)),
Predicate::and(vec![
Predicate::number("price", Compare::Ge, 5.0),
Predicate::is_true("active"),
]),
Predicate::or(vec![
Predicate::number("price", Compare::Eq, 1.0),
Predicate::is_true("active"),
]),
Predicate::or(vec![
Predicate::number("price", Compare::Eq, 1.0),
Predicate::text("tags", TextCompare::Eq, "c"),
]),
];
for p in cases {
assert_eq!(
could_resolve(&p, &indexed),
index_candidates(&p, &index).is_some(),
"{p:?}"
);
}
}
#[test]
fn could_resolve_is_false_with_no_indexed_fields_at_all() {
let indexed: BTreeSet<&str> = BTreeSet::new();
assert!(!could_resolve(&Predicate::is_true("active"), &indexed));
assert!(!could_resolve(
&Predicate::number("bucket", Compare::Eq, 7.0),
&indexed
));
}
#[test]
fn and_intersects_and_narrows_even_with_one_unresolved_side() {
let index = two_field_index();
let both = Predicate::and(vec![
Predicate::number("price", Compare::Ge, 5.0), Predicate::text("tags", TextCompare::Eq, "b"), ]);
assert_eq!(index_candidates(&both, &index), Some(vec![1, 2]));
let one_side_indexed = Predicate::and(vec![
Predicate::number("price", Compare::Ge, 5.0), Predicate::is_true("active"), ]);
assert_eq!(
index_candidates(&one_side_indexed, &index),
Some(vec![1, 2, 3])
);
}
#[test]
fn or_resolves_only_when_both_sides_do() {
let index = two_field_index();
let both = Predicate::or(vec![
Predicate::number("price", Compare::Eq, 1.0), Predicate::text("tags", TextCompare::Eq, "c"), ]);
assert_eq!(index_candidates(&both, &index), Some(vec![0, 2]));
let one_side_unresolved = Predicate::or(vec![
Predicate::number("price", Compare::Eq, 1.0),
Predicate::is_true("active"),
]);
assert_eq!(index_candidates(&one_side_unresolved, &index), None);
}
#[test]
fn a_predicate_that_survives_check_but_resolves_to_no_rows_is_a_valid_empty_result() {
let index = two_field_index();
let p = Predicate::number("price", Compare::Eq, 404.0);
assert_eq!(index_candidates(&p, &index), Some(Vec::new()));
}
#[test]
fn negative_zero_and_positive_zero_are_the_same_row() {
let mut fields = BTreeMap::new();
let stored = field_value(
Some(&serde_json::json!({"price": -0.0})),
"price",
AttrType::Number,
)
.expect("a number field with a value");
fields.insert(
"price".to_string(),
FieldBuild {
kind: Kind::Number,
entries: group_sorted(vec![(stored, 0), (n(1.0), 1)]),
},
);
let index = index_with(fields);
let eq_pos = Predicate::number("price", Compare::Eq, 0.0);
assert_eq!(index_candidates(&eq_pos, &index), Some(vec![0]));
let ge_pos = Predicate::number("price", Compare::Ge, 0.0);
assert_eq!(index_candidates(&ge_pos, &index), Some(vec![0, 1]));
let eq_neg = Predicate::number("price", Compare::Eq, -0.0);
assert_eq!(index_candidates(&eq_neg, &index), Some(vec![0]));
}
}