zeppelin-embed 0.8.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Graph search runs on the document segments pinned by its statement lease.

use super::super::{LegState, ScorePrecision, SearchKind, SearchReport};
use crate::lifecycle::Store;
use crate::property_graph::query::eligibility::Eligibility;
use crate::property_graph::query::pattern::{
    SearchAdapter, SearchArguments, SearchHit, SearchInvocation,
};
use crate::property_graph::query::plan::{SearchMode, SearchOptions};
use crate::property_graph::query::resources::{MemoryError, QueryArena, QueryMemory};
use crate::property_graph::query::runtime::{NativeExecutionError, RuntimeContext, RuntimeError};
use crate::property_graph::query::{QueryError, QueryList, QueryValue};
use crate::property_graph::retrieval::RetrievalError;
use crate::property_graph::storage::GraphReadView;

/// Copies a `QueryList` numeric argument into owned charged `f32` storage.
/// The evaluator only ever produces `F64`/`I64` list elements for a
/// literal or parameter vector; anything else is a plan/argument-type
/// mismatch the caller should have rejected before invoking search.
fn copy_vector<'m, 'g>(
    memory: &'m QueryMemory<'g>,
    list: QueryList<'_>,
) -> Result<QueryArena<'m, 'g, f32>, NativeExecutionError> {
    let mut coordinates = QueryArena::new(memory, list.len()).map_err(RuntimeError::Memory)?;
    for index in 0..list.len() {
        let value = list.get(index).ok_or(RuntimeError::Batch)?;
        let coordinate = match value {
            QueryValue::F64(value) => {
                if !value.is_finite() {
                    return Err(RuntimeError::Value(QueryError::ArithmeticDomain).into());
                }
                let coordinate = value as f32;
                if !coordinate.is_finite() {
                    return Err(RuntimeError::Value(QueryError::ArithmeticOverflow).into());
                }
                coordinate
            }
            QueryValue::I64(value) => value as f32,
            _ => return Err(RuntimeError::Batch.into()),
        };
        coordinates.push(coordinate).map_err(RuntimeError::Memory)?;
    }
    Ok(coordinates)
}

pub(crate) struct NativeSearchAdapter<'a> {
    store: &'a Store,
}
impl<'a> NativeSearchAdapter<'a> {
    pub(crate) const fn new(store: &'a Store) -> Self {
        Self { store }
    }
}

fn lexical(store: &Store, text: &str, prefix: bool) -> crate::fts::query::LexicalQuery {
    let mut terms = store
        .tokenizer
        .analyze(text)
        .into_iter()
        .map(|token| token.term.into_bytes())
        .collect::<Vec<_>>();
    if prefix && let Some(prefix) = terms.pop() {
        crate::fts::query::LexicalQuery::TermsWithPrefix {
            terms,
            prefix,
            fields: crate::fts::search::FieldWeights::flat(&[crate::fts::index::DEFAULT_FIELD]),
        }
    } else {
        crate::fts::query::LexicalQuery::term(crate::fts::search::TermQuery::flat(
            terms,
            &[crate::fts::index::DEFAULT_FIELD],
        ))
    }
}

fn vector_options(
    mode: SearchMode,
    options: SearchOptions,
    window: usize,
) -> Result<crate::lifecycle::SearchOptions, RetrievalError> {
    use crate::lifecycle::{GraphSearchOptions, SearchTier};
    let mut result = crate::lifecycle::SearchOptions::default();
    result = match mode {
        SearchMode::Default => result,
        SearchMode::Auto => result.with_tier(SearchTier::Auto),
        SearchMode::Exact => result.with_tier(SearchTier::Exact),
        SearchMode::Scan => result.with_tier(SearchTier::Scan),
        SearchMode::Graph => {
            let profile = options
                .graph_profile
                .unwrap_or(crate::graph::search::GraphSearchProfile::SiftClass);
            let mut graph = GraphSearchOptions::new(profile).with_seed(options.graph_seed);
            if options.graph_ef != 0 {
                graph = graph.with_ef(options.graph_ef as usize);
            }
            result.with_tier(SearchTier::Graph(graph))
        }
    };
    if mode != SearchMode::Graph
        && (options.graph_profile.is_some() || options.graph_ef != 0 || options.graph_seed != 0)
    {
        return Err(RetrievalError::Control(RuntimeError::Value(
            QueryError::Type,
        )));
    }
    if options.rescore {
        if mode != SearchMode::Scan {
            return Err(RetrievalError::Control(RuntimeError::Value(
                QueryError::Type,
            )));
        }
        result = result.with_scan_rescore(
            crate::lifecycle::ScanRescoreOptions::new(1, window)
                .map_err(|_| RetrievalError::Memory)?,
        );
    }
    Ok(result)
}

fn report(
    invocation: &SearchInvocation<'_, '_, '_, '_, '_>,
    diagnostics: &crate::diag::QueryDiagnostics,
    kind: SearchKind,
) -> SearchReport {
    use super::super::{ActualTier, CandidateCoverage};
    let hybrid = diagnostics.hybrid.as_ref();
    let fusion = diagnostics.fusion.as_ref();
    let vector = kind != SearchKind::Lexical;
    let text = kind != SearchKind::Vector;
    let members = diagnostics
        .plan
        .iter()
        .map(|plan| plan.filter_cardinality)
        .sum::<u64>();
    let lexical_nonempty = hybrid.map_or(diagnostics.returned > 0, |report| {
        report.lexical_returned > 0
    });
    SearchReport {
        call: invocation.call,
        generation: invocation.generation,
        kind,
        requested_tier: None,
        actual_tier: (vector && members > 0).then_some(
            if diagnostics.plan.iter().any(|plan| {
                matches!(
                    plan.branch,
                    crate::planner::SegmentBranch::Graph
                        | crate::planner::SegmentBranch::FilteredGraph
                )
            }) {
                ActualTier::Graph
            } else if diagnostics.plan.iter().any(|plan| {
                matches!(
                    plan.scan_reason,
                    Some(crate::planner::ScanReason::ExplicitTier(
                        crate::planner::ExplicitScanTier::Scan
                    ))
                )
            }) {
                ActualTier::Scan
            } else {
                ActualTier::Exact
            },
        ),
        precision: if !vector {
            ScorePrecision::NotApplicable
        } else if diagnostics.exact_rescore {
            ScorePrecision::Original
        } else {
            ScorePrecision::Quantized
        },
        coverage: if diagnostics.approximate {
            CandidateCoverage::Approximate
        } else {
            CandidateCoverage::Exact
        },
        vector_leg: if !vector {
            LegState::NotRequested
        } else if members == 0 {
            LegState::NoEligibleMembers
        } else {
            LegState::Nonempty
        },
        lexical_leg: if !text {
            LegState::NotRequested
        } else if lexical_nonempty {
            LegState::Nonempty
        } else {
            LegState::NoQueryMatches
        },
        document_epoch: diagnostics.embedding_epoch.map(|epoch| epoch.value()),
        query_epoch: diagnostics.embedding_epoch.map(|epoch| epoch.value()),
        tokenizer_epoch: diagnostics.tokenizer_epoch.map(|epoch| epoch.value()),
        effective_alpha_bits: fusion.map_or(0, |report| report.effective_alpha.to_bits()),
        normalization_version: hybrid
            .map_or(0, |report| u32::from(report.normalization_policy_version)),
        rules_version: fusion.map_or(0, |report| u32::from(report.alpha_policy_version)),
        candidate_count: hybrid.map_or_else(
            || {
                if vector {
                    members
                } else {
                    diagnostics.counters.lexical.docs_evaluated
                }
            },
            |report| report.vector_returned as u64,
        ),
        cross_scored_count: hybrid.map_or(0, |report| {
            if report.provenance.cross_scores_complete {
                report.vector_returned as u64
            } else {
                0
            }
        }),
        fallback_count: diagnostics
            .plan
            .iter()
            .filter(|plan| plan.branch == crate::planner::SegmentBranch::GraphExactFallback)
            .count() as u64,
        cross_score_complete: hybrid.is_some_and(|report| report.provenance.cross_scores_complete),
        work: Default::default(),
    }
}

impl<'v, 'm, 'g> SearchAdapter<'v, 'm, 'g> for NativeSearchAdapter<'_> {
    fn search<'s>(
        &mut self,
        view: &'s GraphReadView<'s, 'v, 'm, 'g>,
        invocation: &SearchInvocation<'_, '_, 'v, 'm, 'g>,
        hits: &mut QueryArena<'m, 'g, SearchHit>,
        context: &mut RuntimeContext<'v, 'm, 'g>,
    ) -> Result<SearchReport, NativeExecutionError> {
        let outer_peak = context.reset_candidate_window_peak()?;
        let before = context.counters();
        let result = (|| {
            if invocation.k > invocation.window {
                return Err(RetrievalError::CandidateWindow {
                    required: invocation.k as usize,
                    window: invocation.window as usize,
                }
                .into());
            }
            let binding = view.retrieval_binding(context)?;
            let pin = view.search_documents()?;
            let ids = match &invocation.eligibility {
                Eligibility::AllIndexed => None,
                Eligibility::Set(set) => {
                    let source = set
                        .ids_for(context.view())
                        .map_err(RetrievalError::Eligibility)?;
                    let mut ids = QueryArena::new(context.memory(), source.len())
                        .map_err(RuntimeError::Memory)?;
                    for id in source {
                        ids.push(crate::ingest::DocId::new(id.get()))
                            .map_err(RuntimeError::Memory)?;
                    }
                    Some(ids)
                }
            };
            // The filter owns a numeric ID copy and, for large sets, a second
            // byte-ordered copy. Keep their reservation until the filter drops.
            let _filter_charge = if let Some(ids) = ids.as_ref() {
                let bytes = crate::lifecycle::QueryFilter::eligible_capacity_bytes(
                    self.store.schema(),
                    ids.len(),
                )
                .ok_or(RuntimeError::Memory(MemoryError::Limit))?;
                let mut charge = context
                    .memory()
                    .reserve_external_capacity()
                    .map_err(RuntimeError::Memory)?;
                charge
                    .reserve_additional(bytes)
                    .map_err(RuntimeError::Memory)?;
                Some(charge)
            } else {
                None
            };
            let filter = ids
                .as_ref()
                .map(QueryArena::as_slice)
                .map(|ids| crate::lifecycle::QueryFilter::eligible(self.store.schema(), ids));
            let control = context.values().control().clone();
            let (mut report, counters) = match invocation.arguments {
                SearchArguments::Text { query } => {
                    let query = lexical(self.store, query, invocation.options.last_as_prefix);
                    let (outcome, matching) = self
                        .store
                        .graph_text_in(pin, &query, invocation.k as usize, filter.as_ref(), control)
                        .map_err(RetrievalError::Fusion)?;
                    context.observe_candidate_window(outcome.candidates.len() as u64)?;
                    for hit in &outcome.candidates {
                        hits.push(SearchHit {
                            node: crate::property_graph::NodeId::from(hit.document.doc_id()),
                            score: hit.score,
                            vector_distance: None,
                            lexical_score: None,
                        })
                        .map_err(RuntimeError::Memory)?;
                    }
                    let mut mapped = report(invocation, &outcome.diagnostics, SearchKind::Lexical);
                    mapped.candidate_count = matching;
                    if ids.as_ref().is_some_and(QueryArena::is_empty) {
                        mapped.lexical_leg = LegState::NoEligibleMembers;
                    }
                    (mapped, outcome.diagnostics.counters)
                }
                SearchArguments::Vector { vector, mode }
                | SearchArguments::Hybrid { vector, mode, .. } => {
                    let tower = binding
                        .interpretation
                        .embedding()
                        .ok_or(RetrievalError::NoVectorSpace)?;
                    let coordinates = copy_vector(context.memory(), vector)?;
                    context.charge(
                        crate::property_graph::query::runtime::WorkKind::VectorCoordinates,
                        coordinates.len() as u64,
                    )?;
                    context.charge(
                        crate::property_graph::query::runtime::WorkKind::VectorBytes,
                        (coordinates.len() * std::mem::size_of::<f32>()) as u64,
                    )?;
                    if coordinates.len() != tower.dimensions() as usize {
                        return Err(RetrievalError::Dimension {
                            expected: tower.dimensions() as usize,
                            actual: coordinates.len(),
                        }
                        .into());
                    }
                    let options =
                        vector_options(mode, invocation.options, invocation.window as usize)?;
                    let request = crate::ingest::SearchRequest::new(coordinates.as_slice())
                        .with_filter(filter.as_ref());
                    // Eligibility is already present in the shared filter;
                    // adding it to the request again would copy it again.
                    let (mut mapped, counters) = if let SearchArguments::Hybrid { text, .. } =
                        invocation.arguments
                    {
                        let query = lexical(self.store, text, invocation.options.last_as_prefix);
                        let mut hybrid = crate::fusion::HybridQuery::new(invocation.k as usize);
                        hybrid.alpha = invocation.options.alpha;
                        hybrid.rules_enabled = invocation.options.rules_enabled;
                        if let Some(rounds) = invocation.options.max_rounds {
                            hybrid.max_rounds =
                                usize::try_from(rounds).map_err(|_| RuntimeError::Batch)?;
                        }
                        let outcome = self
                            .store
                            .graph_hybrid_in(pin, request, &query, &hybrid, options, control)
                            .map_err(RetrievalError::Fusion)?;
                        context.observe_candidate_window(
                            outcome
                                .diagnostics
                                .hybrid
                                .as_ref()
                                .map_or(outcome.hits.len(), |report| report.window)
                                as u64,
                        )?;
                        for hit in &outcome.hits {
                            hits.push(SearchHit {
                                node: crate::property_graph::NodeId::from(hit.key),
                                score: hit.fused_score,
                                vector_distance: hit.vector_squared_l2,
                                lexical_score: hit.lexical_bm25,
                            })
                            .map_err(RuntimeError::Memory)?;
                        }
                        (
                            report(invocation, &outcome.diagnostics, SearchKind::Hybrid),
                            outcome.diagnostics.counters,
                        )
                    } else {
                        let outcome = self.store.graph_vector_in(pin, request, invocation.k as usize, options, control)
                            .map_err(|error| RetrievalError::Storage(crate::property_graph::storage::tree::directory::TreeError::Control(error)))?;
                        context.observe_candidate_window(outcome.candidates.len() as u64)?;
                        for hit in &outcome.candidates {
                            hits.push(SearchHit {
                                node: crate::property_graph::NodeId::from(
                                    hit.document()
                                        .ok_or(RetrievalError::Invariant(
                                            "vector hit has no document identity",
                                        ))?
                                        .doc_id(),
                                ),
                                score: -(hit.score() as f64),
                                vector_distance: None,
                                lexical_score: None,
                            })
                            .map_err(RuntimeError::Memory)?;
                        }
                        (
                            report(invocation, &outcome.diagnostics, SearchKind::Vector),
                            outcome.diagnostics.counters,
                        )
                    };
                    mapped.requested_tier = options.explicit_tier();
                    (mapped, counters)
                }
            };
            use crate::property_graph::query::runtime::WorkKind;
            context.charge(WorkKind::VectorCoordinates, counters.scan.dims_touched)?;
            context.charge(WorkKind::VectorBytes, counters.scan.bytes_read)?;
            context.charge(WorkKind::LexicalPostings, counters.lexical.postings_decoded)?;
            context.charge(WorkKind::LexicalBlocks, counters.lexical.blocks_decoded)?;
            report.work = context.counters().since(before);
            Ok(report)
        })();
        context.restore_candidate_window_peak(outer_peak)?;
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lifecycle::{CancelToken, OpenOptions, QueryControl, Store};
    use crate::property_graph::query::{QueryError, QueryView, ValueContext};
    use crate::property_graph::resources::GraphResources;
    use crate::property_graph::{GraphGeneration, StoreInstanceId};

    #[test]
    #[allow(clippy::expect_used)]
    fn ze64_copy_vector_checks_finite_f32_conversion() {
        let root = tempfile::tempdir().expect("fixture");
        let store = Store::open(
            root.path(),
            OpenOptions::new().with_max_resident_bytes(1_048_576),
        )
        .expect("store");
        let shared = GraphResources::from_store(&store).expect("resources");
        let memory = QueryMemory::new(&shared, 4096).expect("memory");
        let view = QueryView::new(
            StoreInstanceId::new(1).expect("identity"),
            GraphGeneration::new(0),
        );
        let control = QueryControl::Cancel(CancelToken::new());
        let mut context = ValueContext::new(&view, &control, 1000).expect("context");
        let values = [
            QueryValue::F64(1.25),
            QueryValue::F64(-2.5),
            QueryValue::I64(i64::MIN),
            QueryValue::I64(i64::MAX),
        ];
        let list = QueryList::new(&values, &mut context).expect("list");
        let copied = copy_vector(&memory, list).expect("finite vector");
        assert_eq!(
            copied.as_slice(),
            &[1.25, -2.5, i64::MIN as f32, i64::MAX as f32]
        );
        for (value, expected) in [
            (f64::NAN, QueryError::ArithmeticDomain),
            (f64::INFINITY, QueryError::ArithmeticDomain),
            (f64::NEG_INFINITY, QueryError::ArithmeticDomain),
            (1e39, QueryError::ArithmeticOverflow),
            (-1e39, QueryError::ArithmeticOverflow),
        ] {
            let values = [QueryValue::F64(value)];
            let list = QueryList::new(&values, &mut context).expect("list");
            assert!(
                matches!(
                    copy_vector(&memory, list),
                    Err(NativeExecutionError::Runtime(RuntimeError::Value(error))) if error == expected
                ),
                "expected {expected:?} for {value}"
            );
        }
    }
}