1use bytes::Bytes;
14use object_store::path::Path;
15use object_store::{ObjectStore, ObjectStoreExt, PutMode, PutOptions};
16use serde::{Deserialize, Serialize};
17
18use crate::budget::ReadBudget;
19use crate::cpu::{self, Cost, Lane};
20use crate::document::Metric;
21use crate::error::{ItzmaError, Result};
22use crate::fetch::FetchPolicy;
23use crate::index::{self, Kind, hnsw, sq8};
24use crate::manifest::{self, IndexEntry};
25use crate::segment;
26
27pub const DEFAULT_MIN_ROWS: usize = 4096;
29
30pub(crate) const MIN_SEGMENT_FORMAT: u32 = 2;
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(default)]
38#[non_exhaustive]
39pub struct IndexOptions {
40 pub min_rows: usize,
44 pub rebuild: bool,
48 pub kind: IndexKind,
52 pub nlist: Option<usize>,
58}
59
60impl Default for IndexOptions {
61 fn default() -> Self {
62 Self {
63 min_rows: DEFAULT_MIN_ROWS,
64 rebuild: false,
65 kind: IndexKind::default(),
66 nlist: None,
67 }
68 }
69}
70
71impl IndexOptions {
72 #[must_use]
74 pub fn min_rows(mut self, min_rows: usize) -> Self {
75 self.min_rows = min_rows;
76 self
77 }
78
79 #[must_use]
81 pub fn rebuild(mut self, rebuild: bool) -> Self {
82 self.rebuild = rebuild;
83 self
84 }
85
86 #[must_use]
88 pub fn nlist(mut self, nlist: Option<usize>) -> Self {
89 self.nlist = nlist;
90 self
91 }
92
93 pub(crate) fn validate(&self) -> Result<()> {
95 if self.nlist == Some(0) {
96 return Err(ItzmaError::InvalidQuery("nlist must be at least 1"));
97 }
98 Ok(())
99 }
100
101 #[must_use]
103 pub fn kind(mut self, kind: IndexKind) -> Self {
104 self.kind = kind;
105 self
106 }
107}
108
109#[must_use]
115pub fn default_nlist(rows: usize) -> usize {
116 sq8::default_nlist(rows)
117}
118
119#[must_use]
123pub fn default_nprobe(nlist: usize) -> usize {
124 sq8::default_nprobe(nlist)
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
130#[serde(rename_all = "snake_case")]
131#[non_exhaustive]
132pub enum IndexKind {
133 Sq8,
137 #[default]
140 Hnsw,
141}
142
143impl IndexKind {
144 fn as_kind(self) -> Kind {
145 match self {
146 IndexKind::Sq8 => Kind::Sq8,
147 IndexKind::Hnsw => Kind::Hnsw,
148 }
149 }
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
155#[serde(default)]
156#[non_exhaustive]
157pub struct IndexReport {
158 pub indexed: usize,
160 pub skipped_small: usize,
163 pub already_indexed: usize,
166 pub superseded: usize,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub(crate) enum Outcome {
174 Indexed,
175 SkippedSmall,
176 AlreadyIndexed,
177 Superseded,
178}
179
180impl IndexReport {
181 pub(crate) fn record(&mut self, outcome: Outcome) {
182 let count = match outcome {
183 Outcome::Indexed => &mut self.indexed,
184 Outcome::SkippedSmall => &mut self.skipped_small,
185 Outcome::AlreadyIndexed => &mut self.already_indexed,
186 Outcome::Superseded => &mut self.superseded,
187 };
188 *count += 1;
189 }
190}
191
192#[allow(clippy::too_many_arguments)] pub(crate) async fn index_segment(
207 store: &dyn ObjectStore,
208 namespace: &str,
209 dim: usize,
210 metric: Metric,
211 id: &str,
212 have: Option<&IndexEntry>,
213 options: &IndexOptions,
214 read_budget: u64,
215 policy: &FetchPolicy,
216) -> Result<Outcome> {
217 if have.is_some() && !options.rebuild {
218 return Ok(Outcome::AlreadyIndexed);
219 }
220 let budget = ReadBudget::new(read_budget);
221 let data_path = segment::segment_path(namespace, id);
222
223 let head = segment::peek(store, &data_path, &budget).await?;
224 if usize::try_from(head.doc_count).is_ok_and(|rows| rows < options.min_rows) {
225 return Ok(Outcome::SkippedSmall);
226 }
227
228 let bytes = segment::fetch_bytes(store, &data_path, &budget, policy).await?;
229 let data_size = bytes.len() as u64;
230 let layer = segment::decode_on(Lane::Maintenance, data_path.clone(), bytes, dim).await?;
231 let docs = layer.sorted_docs();
232 let matrix: Vec<f32> = docs.iter().flat_map(|d| d.vector.iter().copied()).collect();
233 let rows = docs.len();
234
235 let names = segment::object_names(store, namespace, id).await?;
236 let floor = segment::generation_floor(
237 have.map(|entry| entry.generation),
238 &names,
239 index::generation_of,
240 );
241 let generation = segment::claim_generation(store, namespace, id, floor).await?;
242 let path = index::index_path(namespace, id, generation);
243 let kind = options.kind.as_kind();
244 let nlist = options.nlist.unwrap_or_else(|| sq8::default_nlist(rows));
245 let cost = build_cost(kind, rows, nlist, dim);
246 let built = cpu::run(Lane::Maintenance, cost, move || match kind {
247 Kind::Sq8 => sq8::build(&matrix, dim, rows, data_size, nlist, metric),
248 Kind::Hnsw => hnsw::build(&matrix, dim, rows, data_size, metric),
249 })
250 .await?;
251 put_or_reuse(store, &path, built, kind, dim, rows as u64, data_size).await?;
252
253 publish(store, namespace, id, have, generation, kind).await
254}
255
256fn build_cost(kind: Kind, rows: usize, nlist: usize, dim: usize) -> Cost {
260 let per_row = match kind {
261 Kind::Sq8 => nlist.max(1),
262 Kind::Hnsw => hnsw::EF_CONSTRUCTION,
263 };
264 Cost::Distances {
265 rows: rows.saturating_mul(per_row),
266 dim,
267 }
268}
269
270async fn put_or_reuse(
274 store: &dyn ObjectStore,
275 path: &Path,
276 built: Bytes,
277 kind: Kind,
278 dim: usize,
279 rows: u64,
280 data_size: u64,
281) -> Result<()> {
282 match store
283 .put_opts(path, built.into(), PutOptions::from(PutMode::Create))
284 .await
285 {
286 Ok(_) => Ok(()),
287 Err(object_store::Error::AlreadyExists { .. }) => {
288 let existing = store.get(path).await?.bytes().await?;
289 let checked = match kind {
290 Kind::Sq8 => {
291 sq8::Index::decode(path.as_ref(), &existing, dim, rows, data_size).map(|_| ())
292 }
293 Kind::Hnsw => {
294 hnsw::Index::decode(path.as_ref(), &existing, dim, rows, data_size).map(|_| ())
295 }
296 };
297 checked.map_err(|err| match err {
298 ItzmaError::CorruptIndex { path, reason } => ItzmaError::CorruptIndex {
299 path,
300 reason: format!(
301 "{reason}; an object already at this key does not fit the segment, \
302 delete it and rerun"
303 ),
304 },
305 other => other,
306 })
307 }
308 Err(e) => Err(e.into()),
309 }
310}
311
312async fn publish(
315 store: &dyn ObjectStore,
316 namespace: &str,
317 id: &str,
318 have: Option<&IndexEntry>,
319 generation: u32,
320 kind: Kind,
321) -> Result<Outcome> {
322 let mut lost = Outcome::AlreadyIndexed;
323 let published = manifest::update_if(store, namespace, |m| {
324 if !m.live_segments.iter().any(|live| live == id) {
325 lost = Outcome::Superseded;
326 return false;
327 }
328 if m.indexes.get(id) != have {
329 lost = Outcome::AlreadyIndexed;
330 return false;
331 }
332 m.indexes.insert(
333 id.to_string(),
334 IndexEntry {
335 generation,
336 kind: kind.name().to_string(),
337 },
338 );
339 true
340 })
341 .await?;
342 Ok(published.map_or(lost, |_| Outcome::Indexed))
343}
344
345#[cfg(test)]
346mod tests {
347
348 #[test]
349 fn every_build_worth_indexing_leaves_the_tokio_worker() {
350 use crate::cpu::INLINE_BELOW;
351 for dim in [4, 25, 128] {
354 let cost = build_cost(Kind::Hnsw, DEFAULT_MIN_ROWS, 1, dim);
355 assert!(cost.units() >= INLINE_BELOW, "hnsw at dim {dim}");
356 }
357 let cost = build_cost(Kind::Sq8, 100_000, 316, 25);
359 assert!(cost.units() >= INLINE_BELOW);
360 }
361
362 use super::*;
363
364 #[test]
365 fn options_default_to_hnsw_and_the_setter_changes_it() {
366 assert_eq!(IndexOptions::default().kind, IndexKind::Hnsw);
367 let opts = IndexOptions::default().kind(IndexKind::Sq8);
368 assert_eq!(opts.kind, IndexKind::Sq8);
369 }
370}