kglite 0.17.10

Pure-Rust embedded Cypher knowledge graph engine with in-memory, mmap, and disk storage, and agent-facing schema introspection
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Retrieval over materialized rows or a proven whole type.

use super::helpers::*;
use super::ordering::{SortSpec, TopKCollector};
use super::*;
use crate::graph::schema::EmbeddingStore;
use crate::graph::storage::disk::type_index::TypeNodesRef;
use rustc_hash::FxHashMap;

struct VectorScoreArgs {
    variable: String,
    property: String,
    query: Vec<f32>,
    options: vector_options::VectorOptions,
}

enum HnswOutcome {
    Indexed(ResultSet, RetrievalDiagnostics),
    Exact(RetrievalDiagnostics),
}

struct HnswRowCoverage {
    node_to_row: FxHashMap<usize, usize>,
    ordered_whole_store: bool,
}

pub(super) enum RetrievalPopulation<'r> {
    Rows(&'r ResultSet),
    WholeType {
        nodes: TypeNodesRef<'r>,
        variable: &'r str,
        node_type: &'r str,
    },
}

impl RetrievalPopulation<'_> {
    pub(super) fn len(&self) -> usize {
        match self {
            Self::Rows(rows) => rows.rows.len(),
            Self::WholeType { nodes, .. } => nodes.len(),
        }
    }

    pub(super) fn row(&self, index: usize) -> std::borrow::Cow<'_, ResultRow> {
        match self {
            Self::Rows(rows) => std::borrow::Cow::Borrowed(&rows.rows[index]),
            Self::WholeType {
                nodes, variable, ..
            } => {
                let mut row = ResultRow::new();
                row.node_bindings.insert(
                    (*variable).to_owned(),
                    nodes.get(index).expect("validated retrieval position"),
                );
                std::borrow::Cow::Owned(row)
            }
        }
    }
}

impl<'a> CypherExecutor<'a> {
    /// A plain initial scan has no seed, filter, anchor or secondary-label
    /// carriers; only its primary type bucket determines candidate order.
    fn plain_retrieval_type<'q>(&self, matched: &'q MatchClause) -> Option<(&'q str, &'q str)> {
        let [pattern] = matched.patterns.as_slice() else {
            return None;
        };
        let [PatternElement::Node(node)] = pattern.elements.as_slice() else {
            return None;
        };
        let (Some(variable), Some(node_type)) = (&node.variable, &node.node_type) else {
            return None;
        };
        if node.properties.is_some()
            || node.multi_label_constrained()
            || !node.label_params.is_empty()
            || !matched.path_assignments.is_empty()
            || !matched.node_anchors.is_empty()
            || matched.where_clause.is_some()
            || matched.limit_hint.is_some()
            || matched.distinct_node_hint.is_some()
            || self
                .graph
                .secondary_label_index
                .get(&InternedKey::from_str(node_type))
                .is_some_and(|nodes| !nodes.is_empty())
        {
            return None;
        }
        Some((variable, node_type))
    }

    /// A trial entry shares the MATCH exclusions and never performs stale
    /// index maintenance before deciding whether the established route owns it.
    pub(super) fn try_retrieval_entry(
        &self,
        clauses: &[Clause],
    ) -> Result<Option<ResultSet>, String> {
        match clauses {
            [Clause::Match(matched), Clause::FusedVectorScoreTopK {
                return_clause,
                score_item_index,
                score_call,
                descending: true,
                limit,
            }, ..] => self.try_vector_retrieval_entry(
                matched,
                return_clause,
                *score_item_index,
                score_call,
                *limit,
            ),
            [Clause::Match(matched), Clause::FusedTextBm25TopK {
                return_clause,
                score_item_index,
                score_call,
                sort_keys,
                limit,
            }, ..] => self.try_text_retrieval_entry(
                matched,
                return_clause,
                *score_item_index,
                score_call,
                sort_keys,
                *limit,
            ),
            _ => Ok(None),
        }
    }

    pub(super) fn plain_retrieval_population<'q>(
        &'q self,
        matched: &'q MatchClause,
    ) -> Result<Option<RetrievalPopulation<'q>>, String> {
        let Some((variable, node_type)) = self.plain_retrieval_type(matched) else {
            return Ok(None);
        };
        let Some(nodes) = self.graph.type_indices.get(node_type) else {
            return Ok(None);
        };
        if nodes.is_empty() {
            return Ok(None);
        }
        self.budget.check_work(nodes.len(), "MATCH")?;
        self.check_deadline()?;
        Ok(Some(RetrievalPopulation::WholeType {
            nodes,
            variable,
            node_type,
        }))
    }

    fn try_vector_retrieval_entry(
        &self,
        matched: &MatchClause,
        return_clause: &ReturnClause,
        score_item_index: usize,
        score_call: &Expression,
        limit: usize,
    ) -> Result<Option<ResultSet>, String> {
        if limit == 0 {
            return Ok(None);
        }
        let Some(population) = self.plain_retrieval_population(matched)? else {
            return Ok(None);
        };
        let RetrievalPopulation::WholeType {
            variable,
            node_type,
            ..
        } = &population
        else {
            unreachable!("plain retrieval population is a whole type");
        };
        let score_expr = self.fold_constants_expr(score_call);
        let seed = population.row(0);
        let Some(args) = self.constant_vector_args(&score_expr, &seed)? else {
            return Ok(None);
        };
        if args.variable != *variable {
            return Ok(None);
        }
        let Some(store) = self.graph.embedding_store(node_type, &args.property) else {
            return Ok(None);
        };
        if args.options.exact || !store.has_index() {
            return self.try_exact_vector_entry(
                &args,
                &score_expr,
                limit,
                &population,
                return_clause,
                score_item_index,
            );
        }
        // A pending refresh belongs to the established route, including its
        // warnings and fallback. A trial entry must not refresh twice.
        if store.index_is_stale() {
            return Ok(None);
        }
        match self.try_hnsw_fused_top_k(
            &score_expr,
            true,
            limit,
            &population,
            return_clause,
            score_item_index,
        )? {
            HnswOutcome::Indexed(result, info) => {
                self.record_retrieval(info);
                Ok(Some(result))
            }
            HnswOutcome::Exact(_) => Ok(None),
        }
    }

    fn ordered_store_coverage(
        &self,
        nodes: &TypeNodesRef<'_>,
        store: &EmbeddingStore,
    ) -> Result<bool, String> {
        if nodes.len() != store.len() {
            return Ok(false);
        }
        for (position, (node, &stored)) in nodes.iter().zip(&store.slot_to_node).enumerate() {
            if position % INTERRUPT_POLL_INTERVAL == 0 {
                self.check_deadline()?;
            }
            if node.index() != stored {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Complete ordered coverage proves every candidate has a numeric score
    /// and its input position is its embedding slot. Other populations keep
    /// scalar NULL handling and the existing policy diagnostics.
    fn try_exact_vector_entry(
        &self,
        parsed: &VectorScoreArgs,
        score_expr: &Expression,
        limit: usize,
        population: &RetrievalPopulation<'_>,
        return_clause: &ReturnClause,
        score_item_index: usize,
    ) -> Result<Option<ResultSet>, String> {
        let RetrievalPopulation::WholeType { nodes, .. } = population else {
            return Ok(None);
        };
        let seed = population.row(0);
        let node = *seed
            .node_bindings
            .get(&parsed.variable)
            .expect("validated retrieval variable");
        let node_type = self
            .graph
            .graph
            .node_view(node)
            .expect("live type member")
            .node_type_str(&self.graph.interner);
        let store = self
            .graph
            .embedding_store(node_type, &parsed.property)
            .expect("validated retrieval store");
        if !self.ordered_store_coverage(nodes, store)? {
            return Ok(None);
        }
        let Expression::FunctionCall { args, .. } = score_expr else {
            return Ok(None);
        };
        let uncached;
        let prepared = match self.vs_cache.get(args, node_type) {
            Some(cached) => cached,
            None => match self
                .vs_cache
                .park(self.prepare_vector_score(args, &seed, node_type)?)
            {
                Ok(parked) => parked,
                Err(entry) => {
                    uncached = entry;
                    &uncached
                }
            },
        };
        Self::check_vector_score_dimension(prepared.query_vec.len(), store.dimension)?;
        let winners = self.exact_vector_winners(store, prepared, limit)?;
        let result = self.project_retrieval_winners(
            winners.into_iter(),
            score_expr,
            population,
            return_clause,
            score_item_index,
        )?;
        // Forced exact is reported before store metadata on the scalar route.
        let mut info = RetrievalDiagnostics::exact(if parsed.options.exact {
            "forced_exact"
        } else {
            "no_index"
        });
        if parsed.options.exact {
            info.requested_policy = "exact".into();
        } else {
            info.store = Some(format!("{node_type}.{}", parsed.property));
        }
        self.record_retrieval(info);
        Ok(Some(result))
    }

    fn exact_vector_winners(
        &self,
        store: &EmbeddingStore,
        prepared: &VectorScoreCache,
        limit: usize,
    ) -> Result<Vec<(usize, Value)>, String> {
        let mut collector = TopKCollector::new(
            vec![SortSpec {
                ascending: false,
                nulls: NullsPlacement::First,
            }],
            limit,
        );
        self.check_deadline()?;
        for position in 0..store.len() {
            if position % INTERRUPT_POLL_INTERVAL == 0 {
                self.check_deadline()?;
            }
            let start = position * store.dimension;
            let score = prepared.scorer.score(
                &prepared.query_vec,
                &store.data[start..start + store.dimension],
                store.norms[position],
            );
            let keys = [Value::Float64(score as f64)];
            if collector.accepts(&keys, position) {
                collector.push(&keys, position, position);
            }
        }
        Ok(collector
            .into_sorted()
            .into_iter()
            .map(|(mut keys, position)| (position, keys.pop().expect("one exact vector score key")))
            .collect())
    }

    /// Parse the constant arguments required by indexed or whole-store retrieval.
    /// Returning `None` delegates unsupported expression shapes to the exact
    /// scorer; evaluation errors keep their established error channel.
    fn constant_vector_args(
        &self,
        score_expr: &Expression,
        first_row: &ResultRow,
    ) -> Result<Option<VectorScoreArgs>, String> {
        let args = match score_expr {
            Expression::FunctionCall { name, args, .. }
                if name == "vector_score" && (3..=5).contains(&args.len()) =>
            {
                args
            }
            _ => return Ok(None),
        };
        // A whole-population search cannot reuse row-dependent selectors.
        // This also recognizes constant options maps without broadly changing
        // expression folding or accepting non-deterministic calls.
        if VectorScoreCache::key_for(args).is_none() {
            return Ok(None);
        }
        let variable = match &args[0] {
            Expression::Variable(variable) => variable.clone(),
            _ => return Ok(None),
        };
        let property = match self.evaluate_expression(&args[1], first_row)? {
            Value::String(property) => property,
            _ => return Ok(None),
        };
        let query = self.extract_float_list(&args[2], first_row)?;
        let tail = args[3..]
            .iter()
            .map(|expr| self.evaluate_expression(expr, first_row))
            .collect::<Result<Vec<_>, _>>()?;
        let options = vector_options::parse(&tail)?;
        Ok(Some(VectorScoreArgs {
            variable,
            property,
            query,
            options,
        }))
    }

    /// Build the node-to-row lookup while validating the single-type,
    /// duplicate-free contract required by the HNSW path. The common ordered
    /// whole-store case is proved during this same walk, avoiding the rejected
    /// second store-sized membership pass.
    fn hnsw_row_coverage(
        &self,
        variable: &str,
        node_type: &str,
        store: &EmbeddingStore,
        first_idx: petgraph::graph::NodeIndex,
        result_set: &ResultSet,
    ) -> Option<HnswRowCoverage> {
        let mut node_to_row =
            FxHashMap::with_capacity_and_hasher(result_set.rows.len(), Default::default());
        node_to_row.insert(first_idx.index(), 0);
        let mut ordered_whole_store = result_set.rows.len() == store.len()
            && store.slot_to_node.first() == Some(&first_idx.index());
        if !ordered_whole_store && !store.node_to_slot.contains_key(&first_idx.index()) {
            return None;
        }

        for (row_index, row) in result_set.rows.iter().enumerate().skip(1) {
            let idx = *row.node_bindings.get(variable)?;
            if ordered_whole_store && store.slot_to_node.get(row_index) == Some(&idx.index()) {
                if node_to_row.insert(idx.index(), row_index).is_some() {
                    return None;
                }
                continue;
            }
            ordered_whole_store = false;
            let current_type = self
                .graph
                .graph
                .node_view(idx)?
                .node_type_str(&self.graph.interner);
            // Unembedded rows score NULL and precede numeric scores in DESC.
            // ANN cannot omit them, even if it found enough numeric candidates.
            if current_type != node_type
                || !store.node_to_slot.contains_key(&idx.index())
                || node_to_row.insert(idx.index(), row_index).is_some()
            {
                return None;
            }
        }
        Some(HnswRowCoverage {
            node_to_row,
            ordered_whole_store,
        })
    }

    pub(super) fn project_retrieval_winners(
        &self,
        scored: impl ExactSizeIterator<Item = (usize, Value)>,
        score_expr: &Expression,
        population: &RetrievalPopulation<'_>,
        return_clause: &ReturnClause,
        score_item_index: usize,
    ) -> Result<ResultSet, String> {
        let columns = return_clause
            .items
            .iter()
            .map(return_item_column_name)
            .collect();
        let folded_exprs: Vec<Expression> = return_clause
            .items
            .iter()
            .enumerate()
            .map(|(index, item)| {
                if index == score_item_index {
                    score_expr.clone()
                } else {
                    self.fold_constants_expr(&item.expression)
                }
            })
            .collect();

        let mut rows = Vec::with_capacity(scored.len());
        for (row_index, score) in scored {
            let row = population.row(row_index);
            let mut projected = Bindings::with_capacity(return_clause.items.len());
            for (index, item) in return_clause.items.iter().enumerate() {
                let value = if index == score_item_index {
                    score.clone()
                } else {
                    self.evaluate_expression(&folded_exprs[index], &row)?
                };
                projected.insert(return_item_column_name(item), value);
            }
            rows.push(ResultRow {
                node_bindings: row.node_bindings.clone(),
                edge_bindings: row.edge_bindings.clone(),
                path_bindings: row.path_bindings.clone(),
                projected,
            });
        }
        Ok(ResultSet {
            rows,
            columns,
            lazy_return_items: None,
        })
    }

    /// Use HNSW candidates only for constant selectors over one fully embedded,
    /// duplicate-free row population and a compatible index metric. Re-score
    /// survivors on the scalar score scale. Explicit exact policy bypasses
    /// both index refresh and selection. Unsupported shape, stale index,
    /// incompatible metric or filtered underfill delegates to the exact scan
    /// with the actual decline reason; no hypothetical route is reported.
    fn try_hnsw_fused_top_k(
        &self,
        score_expr: &Expression,
        descending: bool,
        limit: usize,
        population: &RetrievalPopulation<'_>,
        return_clause: &ReturnClause,
        score_item_index: usize,
    ) -> Result<HnswOutcome, String> {
        use crate::graph::algorithms::vector as vs;
        let mut info = RetrievalDiagnostics::exact("unsupported_shape");
        if let Expression::FunctionCall { args, .. } = score_expr {
            if (3..=5).contains(&args.len()) {
                info.requested_policy = self.requested_retrieval_policy(args)?;
            }
        }

        // ANN models "top-k most similar" — descending score, non-empty limit.
        if !descending || limit == 0 {
            return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape")));
        }

        let first_row = population.row(0);
        let args = match self.constant_vector_args(score_expr, &first_row)? {
            Some(args) => args,
            None => return Ok(HnswOutcome::Exact(info.fallback("row_dependent_selectors"))),
        };
        info.requested_policy = if args.options.exact { "exact" } else { "auto" }.into();

        if args.options.exact {
            return Ok(HnswOutcome::Exact(info.fallback("forced_exact")));
        }

        // Resolve the first row's store before building membership. This lets
        // the existing row walk prove the common ordered whole-store shape by
        // comparing each binding with the parallel slot_to_node entry, without
        // a second store-sized HashMap lookup pass.
        let first_idx = match first_row.node_bindings.get(&args.variable) {
            Some(&idx) => idx,
            None => return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape"))),
        };
        let node_type = match self.graph.graph.node_view(first_idx) {
            Some(node) => node.node_type_str(&self.graph.interner).to_string(),
            None => return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape"))),
        };
        let store = match self.graph.embedding_store(&node_type, &args.property) {
            Some(store) => store,
            None => return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape"))),
        };
        let coverage = match population {
            RetrievalPopulation::Rows(result_set) => {
                match self.hnsw_row_coverage(
                    &args.variable,
                    &node_type,
                    store,
                    first_idx,
                    result_set,
                ) {
                    Some(coverage) => Some(coverage),
                    None => return Ok(HnswOutcome::Exact(info.fallback("row_coverage"))),
                }
            }
            RetrievalPopulation::WholeType { nodes, .. } => {
                if !self.ordered_store_coverage(nodes, store)? {
                    return Ok(HnswOutcome::Exact(info.fallback("row_coverage")));
                }
                None
            }
        };
        info.store = Some(format!("{node_type}.{}", args.property));

        let index = match store.index_for_query(self.graph.read_only) {
            Some(i) => i,
            None => {
                // No index, a read-only graph, or a delta too large to fold in
                // inline — all three fall through to the exact scan, which is
                // the *oracle* the approximate path is measured against. A
                // stale vector index therefore costs latency and nothing else,
                // which is why this arm serves rows rather than nulls. The
                // warning is for the one case the caller can act on: an index
                // exists and has fallen behind what a query will catch up.
                if store.has_index() && store.index_is_stale() {
                    self.warn(format!(
                        "vector index '{}.{}' is behind its store by {} vectors, over its \
                         auto_refresh_limit of {} — this query was served by exact scan. \
                         Rebuild with build_vector_index() to restore the index path.",
                        node_type,
                        args.property,
                        store.delta_size(),
                        store.auto_refresh_limit(),
                    ));
                }
                let reason = if store.has_index() {
                    "stale_index"
                } else {
                    "no_index"
                };
                return Ok(HnswOutcome::Exact(info.fallback(reason)));
            }
        };
        if args.query.len() != store.dimension {
            return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape"))); // let the exact path raise the dimension error
        }
        // Resolve metric: explicit > stored > cosine; Poincaré → exact.
        let metric =
            match args.options.metric.or_else(|| {
                vs::DistanceMetric::from_name(store.metric.as_deref().unwrap_or("cosine"))
            }) {
                Some(metric) => metric,
                None => return Ok(HnswOutcome::Exact(info.fallback("unsupported_shape"))),
            };
        if crate::graph::algorithms::hnsw::HnswMetric::from_distance(metric) != Some(index.metric())
        {
            return Ok(HnswOutcome::Exact(info.fallback("metric_mismatch")));
        }

        // HNSW search → membership filter → re-score for exact score scale.
        let scorer = vs::Scorer::new(metric, &args.query);
        let query_norm = vs::dot_product(&args.query, &args.query).sqrt();
        let whole_store = coverage.as_ref().is_none_or(|coverage| {
            coverage.ordered_whole_store
                || (coverage.node_to_row.len() >= store.len()
                    && vs::store_is_fully_selected(store, |node| {
                        coverage.node_to_row.contains_key(&node)
                    }))
        });
        let k_fetch = limit.saturating_mul(4).max(limit).min(store.len());
        let ef = k_fetch.max(index.params().ef_search);
        let raw = index.search(
            &args.query,
            query_norm,
            k_fetch,
            Some(ef),
            &store.data,
            &store.norms,
        );

        let mut scored: Vec<(usize, f64)> = Vec::with_capacity(limit.min(raw.len()));
        for (slot, _dist) in raw {
            let node_raw = store.slot_to_node[slot as usize];
            let row_index = match &coverage {
                Some(coverage) => coverage.node_to_row.get(&node_raw).copied(),
                None => Some(slot as usize),
            };
            if let Some(ri) = row_index {
                let start = slot as usize * store.dimension;
                let emb = &store.data[start..start + store.dimension];
                let norm = store.norms[slot as usize];
                scored.push((ri, scorer.score(&args.query, emb, norm) as f64));
            }
        }
        // Stable sort: ties keep row order (matches the exact path's behaviour
        // closely enough; ANN is approximate by contract anyway).
        scored.sort_by(|a, b| {
            b.1.partial_cmp(&a.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.0.cmp(&b.0))
        });
        scored.truncate(limit);

        // Filtered + underfilled (a tight WHERE ate the over-fetch) → exact scan.
        if !whole_store && scored.len() < limit {
            return Ok(HnswOutcome::Exact(info.fallback("filtered_underfill")));
        }

        let result = self.project_retrieval_winners(
            scored
                .into_iter()
                .map(|(position, score)| (position, Value::Float64(score))),
            score_expr,
            population,
            return_clause,
            score_item_index,
        )?;
        info.actual_mode = "hnsw".into();
        info.fallback_reason = None;
        Ok(HnswOutcome::Indexed(result, info))
    }

    pub(super) fn execute_fused_vector_score_top_k(
        &self,
        return_clause: &ReturnClause,
        score_item_index: usize,
        score_call: &Expression,
        descending: bool,
        limit: usize,
        result_set: ResultSet,
    ) -> Result<ResultSet, String> {
        if result_set.rows.is_empty() || limit == 0 {
            let columns: Vec<String> = return_clause
                .items
                .iter()
                .map(return_item_column_name)
                .collect();
            return Ok(ResultSet {
                rows: Vec::new(),
                columns,
                lazy_return_items: None,
            });
        }

        let score_expr = self.fold_constants_expr(score_call);

        // HNSW fast path: when the score is `vector_score` over a single type
        // whose store carries a built index, search the index instead of scoring
        // every row (the same opt-in approximate path the fluent API auto-uses).
        // Declines to the exact scan below whenever it isn't applicable (no index, unsupported metric, filtered+underfilled,
        // mixed types, duplicate node bindings, ASC order).
        match self.try_hnsw_fused_top_k(
            &score_expr,
            descending,
            limit,
            &RetrievalPopulation::Rows(&result_set),
            return_clause,
            score_item_index,
        )? {
            HnswOutcome::Indexed(rs, info) => {
                self.record_retrieval(info);
                return Ok(rs);
            }
            HnswOutcome::Exact(info) => self.record_retrieval(info),
        }

        // The generic collector preserves NULLs and stable ties. Reusing it
        // also keeps exact fallback aligned with ordinary ORDER BY semantics.
        let sort_keys = [FusedSortKey {
            expression: score_expr,
            ascending: !descending,
            nulls: if descending {
                NullsPlacement::First
            } else {
                NullsPlacement::Last
            },
            return_item: (score_item_index < return_clause.items.len()).then_some(score_item_index),
        }];
        self.execute_fused_order_by_top_k(return_clause, &sort_keys, limit, result_set)
    }
}