Skip to main content

ailake_query/
scanner.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2use std::sync::Arc;
3
4use rayon::prelude::*;
5use tracing::{debug, error, warn};
6
7use ailake_catalog::{CatalogProvider, DataFileEntry, IndexStatus, TableIdent};
8use ailake_core::{AilakeError, AilakeResult, EmbeddingModelInfo, RowId, VectorMetric};
9use ailake_file::AilakeFileReader;
10use ailake_index::AnyIndex;
11use ailake_store::Store;
12use ailake_vec::exact_distance;
13use arrow_array::{Array, RecordBatch};
14use bytes::Bytes;
15
16use crate::equality_delete::EqualityDeleteFilter;
17use crate::pruner::{BloomPruner, VectorPruner};
18use crate::schema_filler::SchemaFiller;
19
20/// Injectable per-result scoring function for hybrid ranking.
21///
22/// Called after HNSW retrieval with the HNSW distance and a single-row
23/// `RecordBatch` containing all Parquet columns for that result. Returns a
24/// replacement score (lower = better rank, same convention as distance).
25///
26/// Typical use: combine HNSW distance with recency and importance signals
27/// from the `episodic_columns` for agent memory tables:
28///
29/// ```rust,no_run
30/// use ailake_core::{hybrid_score, episodic_columns};
31/// use ailake_query::scanner::ScoreFn;
32/// use arrow_array::{RecordBatch, cast::AsArray};
33/// use arrow_array::types::Float32Type;
34///
35/// let score_fn = ScoreFn::new(|distance, row| {
36///     let recency = row
37///         .column_by_name(episodic_columns::RECENCY_WEIGHT)
38///         .and_then(|c| c.as_primitive_opt::<Float32Type>())
39///         .and_then(|a| a.iter().next().flatten())
40///         .unwrap_or(1.0);
41///     let importance = row
42///         .column_by_name(episodic_columns::IMPORTANCE_SCORE)
43///         .and_then(|c| c.as_primitive_opt::<Float32Type>())
44///         .and_then(|a| a.iter().next().flatten())
45///         .unwrap_or(1.0);
46///     hybrid_score(distance, recency, importance)
47/// });
48/// ```
49#[allow(clippy::type_complexity)]
50pub struct ScoreFn(pub std::sync::Arc<dyn Fn(f32, &RecordBatch) -> f32 + Send + Sync>);
51
52impl ScoreFn {
53    pub fn new(f: impl Fn(f32, &RecordBatch) -> f32 + Send + Sync + 'static) -> Self {
54        Self(std::sync::Arc::new(f))
55    }
56
57    #[inline]
58    pub fn call(&self, distance: f32, row: &RecordBatch) -> f32 {
59        (self.0)(distance, row)
60    }
61}
62
63impl Clone for ScoreFn {
64    fn clone(&self) -> Self {
65        Self(std::sync::Arc::clone(&self.0))
66    }
67}
68
69impl std::fmt::Debug for ScoreFn {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.write_str("ScoreFn(<fn>)")
72    }
73}
74
75#[derive(Debug, Clone)]
76pub struct SearchConfig {
77    pub top_k: usize,
78    pub ef_search: usize,
79    /// Maximum distance from query to file centroid edge for a file to be searched.
80    /// Files where `distance(query, centroid) - radius > pruning_threshold` are skipped.
81    /// Set to `f32::INFINITY` to disable pruning (scan all files).
82    pub pruning_threshold: f32,
83    /// When `Some(factor)`, fetch `top_k * factor` candidates from the HNSW index and
84    /// rerank them using exact F32 distances before truncating to `top_k`.
85    /// Corrects the approximation error introduced by PQ-compressed HNSW distances.
86    /// `None` (default) disables reranking.
87    pub rerank_factor: Option<usize>,
88    /// Hybrid BM25+vector search configuration.
89    ///
90    /// When set, the pipeline loads global IDF stats from the table's BM25 stats file,
91    /// fetches a larger candidate pool from HNSW (`candidate_pool` or `10 * top_k`),
92    /// scores each candidate with BM25 against `query_text`, then fuses vector distance
93    /// and BM25 score via RRF (default) or linear combination.
94    ///
95    /// The BM25 stats file (`metadata/ailake_bm25_stats.bin`) is populated automatically
96    /// by `TableWriter` when `bm25_text_column` is configured. If absent, pure vector
97    /// distances are used (BM25 scores default to 0).
98    pub hybrid: Option<crate::bm25::HybridConfig>,
99    /// Optional scoring function for hybrid ranking.
100    ///
101    /// When set, the search pipeline reads the Parquet row for each HNSW
102    /// candidate and calls `score_fn(distance, &single_row_batch)`. The
103    /// returned value replaces `distance` in `SearchResult` and determines
104    /// final ranking (lower = better).
105    ///
106    /// If `rerank_factor` is also set, `score_fn` receives the exact
107    /// (non-approximated) distance from the reranking step.
108    ///
109    /// Use `ScoreFn::new(|d, row| ...)` to construct. See `ScoreFn` docs
110    /// for an example using `hybrid_score` with episodic memory columns.
111    pub score_fn: Option<ScoreFn>,
112    /// Partition filter: only search files whose `DataFileEntry::partition_value`
113    /// matches this string. `None` searches all files (no partition pruning).
114    /// Set to `agent_id` in Agent.recall() for per-agent isolated search.
115    pub partition_filter: Option<String>,
116}
117
118impl Default for SearchConfig {
119    fn default() -> Self {
120        Self {
121            top_k: 10,
122            ef_search: 50,
123            pruning_threshold: f32::INFINITY,
124            rerank_factor: None,
125            score_fn: None,
126            partition_filter: None,
127            hybrid: None,
128        }
129    }
130}
131
132impl SearchConfig {
133    pub fn with_pruning(mut self, threshold: f32) -> Self {
134        self.pruning_threshold = threshold;
135        self
136    }
137
138    pub fn with_reranking(mut self, factor: usize) -> Self {
139        self.rerank_factor = Some(factor);
140        self
141    }
142
143    pub fn with_score_fn(
144        mut self,
145        f: impl Fn(f32, &RecordBatch) -> f32 + Send + Sync + 'static,
146    ) -> Self {
147        self.score_fn = Some(ScoreFn::new(f));
148        self
149    }
150
151    pub fn with_hybrid(mut self, cfg: crate::bm25::HybridConfig) -> Self {
152        self.hybrid = Some(cfg);
153        self
154    }
155}
156
157#[derive(Debug)]
158pub struct SearchResult {
159    pub row_id: RowId,
160    pub distance: f32,
161    pub file_path: String,
162}
163
164/// Search across all files in the latest snapshot, with geometric pruning.
165///
166/// Flow:
167/// 1. Load file list from catalog (includes centroid metadata)
168/// 2. Prune files whose centroid + radius cannot contain a result within `pruning_threshold`
169/// 3. For surviving files: load bytes, deserialize HNSW, run top-k search
170/// 4. Global merge of all per-file top-k lists, return global top-k
171pub async fn search(
172    table: &TableIdent,
173    query: &[f32],
174    config: SearchConfig,
175    vector_column: &str,
176    dim: u32,
177    catalog: Arc<dyn CatalogProvider>,
178    store: Arc<dyn Store>,
179) -> AilakeResult<Vec<SearchResult>> {
180    // Get file metadata (includes centroid info) without reading any data files
181    let all_files = catalog.list_files(table, None).await?;
182
183    // Determine vector metric from table metadata for correct distance computation
184    let table_meta = catalog.load_table(table).await?;
185
186    // Validate query dim against the column's stored dim.
187    // Primary column: use `ailake.vector-dim`. Secondary columns: use `ailake.dim-<col>`.
188    // Skip validation when the column has no stored dim (e.g. old tables written before
189    // multi-column support).
190    let primary_col = table_meta
191        .properties
192        .get("ailake.vector-column")
193        .map(String::as_str)
194        .unwrap_or("");
195    let stored_dim_key = if vector_column == primary_col {
196        "ailake.vector-dim".to_string()
197    } else {
198        format!("ailake.dim-{vector_column}")
199    };
200    if let Some(table_dim_str) = table_meta.properties.get(&stored_dim_key) {
201        if let Ok(table_dim) = table_dim_str.parse::<u32>() {
202            let query_dim = query.len() as u32;
203            if query_dim != table_dim {
204                let table_model = table_meta
205                    .properties
206                    .get(EmbeddingModelInfo::property_key())
207                    .cloned()
208                    .unwrap_or_else(|| format!("dim={}", table_dim));
209                return Err(AilakeError::ModelMismatch {
210                    table_model,
211                    table_dim,
212                    batch_model: format!("query dim={}", query_dim),
213                    batch_dim: query_dim,
214                });
215            }
216        }
217    }
218
219    // Metric: prefer per-column `ailake.metric-<col>`, fall back to primary metric.
220    let metric_key = if vector_column == primary_col {
221        "ailake.vector-metric".to_string()
222    } else {
223        format!("ailake.metric-{vector_column}")
224    };
225    let metric = parse_metric(
226        table_meta
227            .properties
228            .get(&metric_key)
229            .or_else(|| table_meta.properties.get("ailake.vector-metric"))
230            .map(String::as_str)
231            .unwrap_or("cosine"),
232    );
233
234    // Partition pruning: skip files not belonging to the requested partition value.
235    let all_files = if let Some(ref pv) = config.partition_filter {
236        let before = all_files.len();
237        let filtered: Vec<_> = all_files
238            .into_iter()
239            .filter(|f| f.partition_value.as_deref() == Some(pv.as_str()))
240            .collect();
241        debug!(
242            "ailake: partition pruning '{}' — {}/{} files survive",
243            pv,
244            filtered.len(),
245            before
246        );
247        filtered
248    } else {
249        all_files
250    };
251
252    // Geometric pruning: skip files whose centroid is too far from the query
253    let total_files = all_files.len();
254    let surviving_files = VectorPruner::prune(all_files, query, metric, config.pruning_threshold);
255    debug!(
256        "ailake: geometric pruning — {}/{} files survive (threshold={})",
257        surviving_files.len(),
258        total_files,
259        config.pruning_threshold
260    );
261
262    // Phase F — Bloom pruning: for hybrid queries, load per-file Bloom filters from
263    // the Puffin stats file and skip files where no query term can be present.
264    let surviving_files = if let Some(ref h) = config.hybrid {
265        let bloom_map = load_bloom_map(&table_meta, store.as_ref()).await;
266        if !bloom_map.is_empty() {
267            BloomPruner::prune(surviving_files, &h.query_text, &bloom_map)
268        } else {
269            surviving_files
270        }
271    } else {
272        surviving_files
273    };
274
275    // Phase H: load equality delete filter for this snapshot.
276    // Reads delete manifests from the catalog and downloads each equality delete Avro file.
277    // Empty filter is a no-op. On error: warn and continue with empty filter (data visible).
278    let eq_del_filter = match catalog.list_equality_deletes(table, None).await {
279        Ok(edfs) if !edfs.is_empty() => {
280            match EqualityDeleteFilter::from_files(&store, &edfs).await {
281                Ok(f) => f,
282                Err(e) => {
283                    warn!("ailake: equality delete filter build failed: {e} — rows may appear");
284                    EqualityDeleteFilter::empty()
285                }
286            }
287        }
288        _ => EqualityDeleteFilter::empty(),
289    };
290
291    // Compute candidate pool: hybrid needs a larger pool for BM25 re-ranking.
292    let candidate_k = match (&config.hybrid, config.rerank_factor) {
293        (Some(h), rf) => {
294            let pool = h.candidate_pool.unwrap_or(config.top_k * 10);
295            pool.max(rf.map_or(config.top_k, |f| f * config.top_k))
296        }
297        (None, Some(factor)) => config.top_k * factor,
298        (None, None) => config.top_k,
299    };
300
301    let use_hybrid = config.hybrid.is_some();
302
303    // Load BM25 stats from the table's stats file when hybrid search is active.
304    let bm25_stats: Option<crate::bm25::IdfStats> = if let Some(ref h) = config.hybrid {
305        if h.text_columns.is_empty() {
306            None
307        } else {
308            let stats_path = table_meta
309                .properties
310                .get(crate::bm25::BM25_STATS_PATH_PROP)
311                .map(String::as_str)
312                .unwrap_or(crate::bm25::BM25_STATS_FILE);
313            match store.get(stats_path).await {
314                Ok(bytes) => crate::bm25::IdfStats::from_bytes(&bytes).ok(),
315                Err(_) => {
316                    debug!(
317                        "ailake: BM25 stats not found at '{}' — falling back to empty corpus IDF",
318                        stats_path
319                    );
320                    None
321                }
322            }
323        }
324    } else {
325        None
326    };
327
328    // raw_candidates: (row_id, vec_dist, file_path, bm25_text) for hybrid re-ranking.
329    // Only populated when use_hybrid = true; otherwise all_results is populated directly.
330    let mut raw_candidates: Vec<(RowId, f32, String, String)> = Vec::new();
331    let mut all_results: Vec<SearchResult> = Vec::new();
332
333    // Observability for the flat-scan fallback below: `deferred` counts files still
334    // being indexed by our own deferred-write path (expected, transient). `unexpected`
335    // counts files with no AI-Lake index that are NOT in that state — most likely
336    // rewritten by a generic Iceberg engine (Spark/Trino OPTIMIZE, DuckDB) with no
337    // knowledge of AI-Lake. Those files still return correct results (flat scan is
338    // exact), just O(N) instead of O(log N), and silently forever unless recompacted.
339    let mut flat_scan_deferred = 0usize;
340    let mut flat_scan_unexpected = 0usize;
341
342    for file_entry in &surviving_files {
343        let file_bytes: Bytes = store.get(&file_entry.path).await?;
344        let reader = AilakeFileReader::new(file_bytes, vector_column, dim);
345
346        // V3 Deletion Vector: fetch bitmap once per file (range GET from Puffin .dvd).
347        // None for V2 tables or V3 files with no deletes. On fetch error: warn + continue
348        // without mask (surfacing deleted rows is safer than hard-failing the search).
349        let dv_bitmap: Option<roaring::RoaringBitmap> =
350            if let Some(ref dv) = file_entry.deletion_vector {
351                match crate::dv::load_deletion_vector(&store, dv).await {
352                    Ok(bm) => {
353                        debug!(
354                            "ailake: DV loaded ({} deletions) for {}",
355                            bm.len(),
356                            file_entry.path
357                        );
358                        Some(bm)
359                    }
360                    Err(e) => {
361                        warn!(
362                            "ailake: DV fetch failed for '{}': {e} — deleted rows may appear",
363                            file_entry.path
364                        );
365                        None
366                    }
367                }
368            } else {
369                None
370            };
371
372        // Parquet read required for: flat scan fallback, exact reranking, score_fn, hybrid,
373        // or when equality delete filter must check column values per-row.
374        let need_parquet = file_entry.index_status == IndexStatus::Indexing
375            || !reader.is_ailake_file()
376            || config.rerank_factor.is_some()
377            || config.score_fn.is_some()
378            || use_hybrid
379            || !eq_del_filter.is_empty();
380
381        if file_entry.index_status == IndexStatus::Indexing || !reader.is_ailake_file() {
382            match file_entry.index_status {
383                IndexStatus::Indexing => {
384                    flat_scan_deferred += 1;
385                    debug!(
386                        "ailake: flat scan fallback for {} — index build in progress \
387                         (deferred write, expected to resolve once background job completes)",
388                        file_entry.path
389                    );
390                }
391                IndexStatus::Failed => {
392                    // An internal indexing failure, not a foreign write — the file still
393                    // has a real (foreign-write-style) centroid_b64 from make_data_file_entry
394                    // *_indexing, since only index_status/index_error get patched on failure
395                    // (see writer.rs::patch_index_failed). Attributing this to an external
396                    // engine would send on-call looking for a Spark job that never ran.
397                    flat_scan_unexpected += 1;
398                    warn!(
399                        "ailake: flat scan fallback for {} — background index build failed \
400                         permanently ({}); serving via flat scan until the next compaction \
401                         rebuilds the index",
402                        file_entry.path,
403                        file_entry
404                            .index_error
405                            .as_deref()
406                            .unwrap_or("no error recorded")
407                    );
408                }
409                IndexStatus::Ready => {
410                    // Ready but no loadable index/footer: either a genuine foreign write
411                    // (no centroid_b64 — see CompactionPlanner::plan's detection) or a rare
412                    // internally-inconsistent state (Ready without ever getting an index).
413                    flat_scan_unexpected += 1;
414                    if file_entry.is_foreign() {
415                        warn!(
416                            "ailake: flat scan fallback for {} — file has no AI-Lake index \
417                             and no centroid; likely rewritten by a generic Iceberg engine \
418                             (OPTIMIZE / rewrite_data_files) with no knowledge of AI-Lake. \
419                             Results are still correct (exact O(N) scan), but degraded until \
420                             this file is recompacted by the AI-Lake SDK",
421                            file_entry.path
422                        );
423                    } else {
424                        warn!(
425                            "ailake: flat scan fallback for {} — marked Ready but has no \
426                             loadable AI-Lake index despite a recorded centroid; internal \
427                             inconsistency, not an external rewrite. Run compaction to rebuild",
428                            file_entry.path
429                        );
430                    }
431                }
432            }
433            let (raw_batch, raw_vectors) = reader.read_parquet()?;
434            // Phase G: inject columns added via schema evolution with initial_default values.
435            let batch = SchemaFiller::fill(raw_batch, &table_meta.schema_fields)?;
436            for (row_id, distance) in flat_search(&raw_vectors, query, candidate_k, metric) {
437                // Skip rows marked as deleted by a V3 Deletion Vector.
438                if dv_bitmap
439                    .as_ref()
440                    .is_some_and(|bm| bm.contains(row_id.as_u64() as u32))
441                {
442                    continue;
443                }
444                // Phase H: skip rows matched by an equality delete predicate.
445                if eq_del_filter.should_delete_row(&batch, row_id.as_u64() as usize) {
446                    continue;
447                }
448                if use_hybrid {
449                    let text = extract_text_for_row(
450                        &batch,
451                        row_id.as_u64() as usize,
452                        config.hybrid.as_ref().unwrap(),
453                    );
454                    raw_candidates.push((row_id, distance, file_entry.path.clone(), text));
455                } else {
456                    let final_score = apply_score_fn(&config.score_fn, distance, row_id, &batch);
457                    all_results.push(SearchResult {
458                        row_id,
459                        distance: final_score,
460                        file_path: file_entry.path.clone(),
461                    });
462                }
463            }
464            continue;
465        }
466
467        let index = reader.load_any_index_for_column(vector_column)?;
468        let local_results = index.search(query, candidate_k, config.ef_search);
469
470        let parquet_data = if need_parquet {
471            let (raw_batch, raw_vecs) = reader.read_parquet()?;
472            // Phase G: fill missing columns for old files before score_fn / hybrid BM25.
473            let filled = SchemaFiller::fill(raw_batch, &table_meta.schema_fields)?;
474            Some((filled, raw_vecs))
475        } else {
476            None
477        };
478
479        for (row_id, approx_dist) in local_results {
480            // Skip rows marked as deleted by a V3 Deletion Vector.
481            if dv_bitmap
482                .as_ref()
483                .is_some_and(|bm| bm.contains(row_id.as_u64() as u32))
484            {
485                continue;
486            }
487            let idx = row_id.as_u64() as usize;
488            // Phase H: skip rows matched by an equality delete predicate.
489            // parquet_data is always loaded when eq_del_filter is non-empty (see need_parquet).
490            if let Some((ref batch, _)) = parquet_data {
491                if eq_del_filter.should_delete_row(batch, idx) {
492                    continue;
493                }
494            }
495
496            let distance = if config.rerank_factor.is_some() {
497                match parquet_data.as_ref().and_then(|(_, vecs)| vecs.get(idx)) {
498                    Some(v) => exact_distance(metric, query, v),
499                    None => {
500                        error!(
501                            "ailake: invariant violated — row_id {} out of bounds \
502                             (file={}); Parquet and HNSW node count out of sync; \
503                             run compaction to rebuild",
504                            idx, file_entry.path
505                        );
506                        f32::INFINITY
507                    }
508                }
509            } else {
510                approx_dist
511            };
512
513            if use_hybrid {
514                let text = parquet_data.as_ref().map_or(String::new(), |(batch, _)| {
515                    extract_text_for_row(batch, idx, config.hybrid.as_ref().unwrap())
516                });
517                raw_candidates.push((row_id, distance, file_entry.path.clone(), text));
518            } else {
519                let final_score = if let Some((ref batch, _)) = parquet_data {
520                    apply_score_fn(&config.score_fn, distance, row_id, batch)
521                } else {
522                    distance
523                };
524                all_results.push(SearchResult {
525                    row_id,
526                    distance: final_score,
527                    file_path: file_entry.path.clone(),
528                });
529            }
530        }
531    }
532
533    if flat_scan_unexpected > 0 {
534        warn!(
535            "ailake: search degraded — {}/{} files scanned without an AI-Lake index \
536             (unexpected — likely external rewrites; {} more in expected deferred-indexing \
537             state). Run compaction to restore O(log N) search on affected files",
538            flat_scan_unexpected,
539            surviving_files.len(),
540            flat_scan_deferred
541        );
542    } else if flat_scan_deferred > 0 {
543        debug!(
544            "ailake: search — {}/{} files scanned via flat fallback (deferred indexing)",
545            flat_scan_deferred,
546            surviving_files.len()
547        );
548    }
549
550    // Hybrid BM25 fusion: applied after all HNSW candidates are collected.
551    if let Some(ref h) = config.hybrid {
552        let empty_stats = crate::bm25::IdfStats::default();
553        let stats = bm25_stats.as_ref().unwrap_or(&empty_stats);
554        let scorer = crate::bm25::BM25Scorer::new(stats);
555
556        // Compute BM25 scores before sorting so they stay positionally aligned.
557        let bm25_scores_pre: Vec<f32> = raw_candidates
558            .iter()
559            .map(|(_, _, _, text)| scorer.score(&h.query_text, text))
560            .collect();
561
562        // Zip BM25 scores into candidates so they sort together — avoids index mismatch
563        // when raw_candidates is reordered by distance below.
564        let mut candidates_with_bm25: Vec<((RowId, f32, String, String), f32)> =
565            raw_candidates.into_iter().zip(bm25_scores_pre).collect();
566        candidates_with_bm25.sort_by(|a, b| a.0 .1.total_cmp(&b.0 .1));
567        let n = candidates_with_bm25.len();
568
569        let vec_ranks: Vec<usize> = (0..n).collect();
570
571        // Rank by BM25 score descending using post-sort aligned scores.
572        let mut bm25_indexed: Vec<(usize, f32)> = candidates_with_bm25
573            .iter()
574            .map(|(_, b)| *b)
575            .enumerate()
576            .collect();
577        bm25_indexed.sort_by(|a, b| b.1.total_cmp(&a.1));
578        let mut bm25_rank_of = vec![0usize; n];
579        for (rank, (idx, _)) in bm25_indexed.iter().enumerate() {
580            bm25_rank_of[*idx] = rank;
581        }
582
583        use crate::bm25::{linear_score, rrf_score, HybridFusion};
584
585        let fused: Vec<f32> = match h.fusion {
586            HybridFusion::Rrf => vec_ranks
587                .iter()
588                .enumerate()
589                .map(|(i, &vr)| rrf_score(vr, bm25_rank_of[i], h.bm25_weight))
590                .collect(),
591            HybridFusion::Linear => {
592                let min_d = candidates_with_bm25
593                    .iter()
594                    .map(|(r, _)| r.1)
595                    .fold(f32::INFINITY, f32::min);
596                let max_d = candidates_with_bm25
597                    .iter()
598                    .map(|(r, _)| r.1)
599                    .fold(f32::NEG_INFINITY, f32::max);
600                let min_b = candidates_with_bm25
601                    .iter()
602                    .map(|(_, b)| *b)
603                    .fold(f32::INFINITY, f32::min);
604                let max_b = candidates_with_bm25
605                    .iter()
606                    .map(|(_, b)| *b)
607                    .fold(f32::NEG_INFINITY, f32::max);
608                candidates_with_bm25
609                    .iter()
610                    .map(|(r, b)| linear_score(r.1, min_d, max_d, *b, min_b, max_b, h.bm25_weight))
611                    .collect()
612            }
613        };
614
615        for (i, ((row_id, _, file_path, _), _)) in candidates_with_bm25.into_iter().enumerate() {
616            all_results.push(SearchResult {
617                row_id,
618                distance: fused[i],
619                file_path,
620            });
621        }
622
623        // For RRF: lower (more negative) = better; for Linear: lower = better. Same convention.
624        all_results.sort_by(|a, b| a.distance.total_cmp(&b.distance));
625    } else {
626        all_results.sort_by(|a, b| a.distance.total_cmp(&b.distance));
627    }
628
629    all_results.truncate(config.top_k);
630    Ok(all_results)
631}
632
633/// Extract concatenated text from specified columns for a single row.
634fn extract_text_for_row(
635    batch: &RecordBatch,
636    row_idx: usize,
637    hybrid: &crate::bm25::HybridConfig,
638) -> String {
639    use arrow_array::cast::AsArray;
640    hybrid
641        .text_columns
642        .iter()
643        .filter_map(|col| {
644            batch.column_by_name(col).and_then(|arr| {
645                arr.as_string_opt::<i32>().and_then(|sa| {
646                    if row_idx < sa.len() && sa.is_valid(row_idx) {
647                        Some(sa.value(row_idx).to_string())
648                    } else {
649                        None
650                    }
651                })
652            })
653        })
654        .collect::<Vec<_>>()
655        .join(" ")
656}
657
658/// One query arm in a cross-modal search.
659#[derive(Debug, Clone)]
660pub struct ModalQuery<'a> {
661    /// Vector column to search (must exist in the table).
662    pub column: &'a str,
663    /// Query vector for this modality.
664    pub query: &'a [f32],
665    /// Relative weight applied in the RRF formula: `weight / (k + rank)`.
666    /// `1.0` means equal weight across all modalities.
667    pub weight: f32,
668    /// Dimensionality of this column's vectors. `0` = auto-detect from table metadata
669    /// (`ailake.dim-<column>` for secondary columns, `ailake.vector-dim` for primary).
670    pub dim: u32,
671}
672
673/// Fusion method for combining results from multiple vector columns.
674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
675pub enum FusionMethod {
676    /// Reciprocal Rank Fusion: `score(d) = Σ weight_i / (k + rank_i(d))`.
677    /// `k = 60` (standard). Returned `SearchResult.distance` = `-rrf_score`
678    /// so that sort-ascending-by-distance gives the correct RRF ranking.
679    Rrf,
680}
681
682/// Cross-modal search: run independent HNSW searches across N vector columns,
683/// then fuse per-column ranked lists using Reciprocal Rank Fusion.
684///
685/// Each `ModalQuery` specifies a column name, its query vector, RRF weight, and dim.
686/// When `ModalQuery.dim == 0`, the dim is auto-detected from `ailake.dim-<col>` /
687/// `ailake.vector-dim` in table metadata.
688/// Results are de-duplicated by `(file_path, row_id)` and ranked by aggregate
689/// RRF score. `SearchResult.distance` stores `-rrf_score` (lower = better) so
690/// existing sort-ascending callers get the correct ordering.
691pub async fn search_multimodal(
692    table: &TableIdent,
693    queries: &[ModalQuery<'_>],
694    config: SearchConfig,
695    catalog: Arc<dyn CatalogProvider>,
696    store: Arc<dyn Store>,
697    fusion: FusionMethod,
698) -> AilakeResult<Vec<SearchResult>> {
699    use std::collections::HashMap;
700
701    if queries.is_empty() {
702        return Err(AilakeError::InvalidArgument(
703            "search_multimodal requires at least one ModalQuery".into(),
704        ));
705    }
706
707    // Load table metadata once for dim auto-detection and metric resolution.
708    let table_meta = catalog.load_table(table).await?;
709    let primary_col = table_meta
710        .properties
711        .get("ailake.vector-column")
712        .cloned()
713        .unwrap_or_default();
714    let primary_dim: u32 = table_meta
715        .properties
716        .get("ailake.vector-dim")
717        .and_then(|s| s.parse().ok())
718        .unwrap_or(0);
719
720    // Fetch more candidates per column so RRF has enough to fuse.
721    let per_col_k = (config.top_k * queries.len().max(2)).min(1000);
722
723    let mut per_col_results: Vec<(f32, Vec<SearchResult>)> = Vec::with_capacity(queries.len());
724    for mq in queries {
725        // Resolve dim: caller-supplied > per-column property > primary column dim.
726        let resolved_dim = if mq.dim > 0 {
727            mq.dim
728        } else if mq.column == primary_col {
729            primary_dim
730        } else {
731            table_meta
732                .properties
733                .get(&format!("ailake.dim-{}", mq.column))
734                .and_then(|s| s.parse().ok())
735                .unwrap_or(mq.query.len() as u32)
736        };
737
738        let col_config = SearchConfig {
739            top_k: per_col_k,
740            ef_search: config.ef_search,
741            pruning_threshold: config.pruning_threshold,
742            rerank_factor: config.rerank_factor,
743            score_fn: None,
744            partition_filter: config.partition_filter.clone(),
745            hybrid: None,
746        };
747        let results = search(
748            table,
749            mq.query,
750            col_config,
751            mq.column,
752            resolved_dim,
753            catalog.clone(),
754            store.clone(),
755        )
756        .await?;
757        per_col_results.push((mq.weight, results));
758    }
759
760    // RRF fusion: accumulate score per (file_path, row_id).
761    const K: f32 = 60.0;
762    let mut scores: HashMap<(String, u64), f32> = HashMap::new();
763
764    for (weight, results) in &per_col_results {
765        for (rank, r) in results.iter().enumerate() {
766            let key = (r.file_path.clone(), r.row_id.as_u64());
767            let rrf = weight / (K + rank as f32 + 1.0);
768            *scores.entry(key).or_insert(0.0) += rrf;
769        }
770    }
771
772    // Build SearchResult list sorted by descending RRF score.
773    // Store `-rrf_score` as `.distance` so callers sorting ascending get correct order.
774    let all_files = catalog.list_files(table, None).await?;
775    let _ = all_files; // centroid not needed for fusion — just need file_path+row_id
776
777    // Collect unique candidates: prefer the row's appearance in the first column's results.
778    let mut seen: HashMap<(String, u64), f32> = HashMap::new();
779    for (_, results) in &per_col_results {
780        for r in results {
781            let key = (r.file_path.clone(), r.row_id.as_u64());
782            let rrf_score = *scores.get(&key).unwrap_or(&0.0);
783            seen.entry(key).or_insert(rrf_score);
784        }
785    }
786
787    let mut fused: Vec<SearchResult> = seen
788        .into_iter()
789        .map(|((file_path, row_id_u64), rrf_score)| SearchResult {
790            row_id: RowId::new(row_id_u64),
791            distance: -rrf_score,
792            file_path,
793        })
794        .collect();
795
796    fused.sort_by(|a, b| {
797        a.distance
798            .partial_cmp(&b.distance)
799            .unwrap_or(std::cmp::Ordering::Equal)
800    });
801    fused.truncate(config.top_k);
802
803    let _ = fusion; // only RRF implemented; enum is extensible
804
805    Ok(fused)
806}
807
808/// Apply `score_fn` to a single result row, or return `distance` unchanged.
809///
810/// Slices the batch to a 1-row RecordBatch at `row_id` and calls the fn.
811/// If `score_fn` is `None` or the row index is out of bounds, returns `distance`.
812#[inline]
813fn apply_score_fn(
814    score_fn: &Option<ScoreFn>,
815    distance: f32,
816    row_id: RowId,
817    batch: &RecordBatch,
818) -> f32 {
819    match score_fn {
820        None => distance,
821        Some(f) => {
822            let idx = row_id.as_u64() as usize;
823            if idx < batch.num_rows() {
824                f.call(distance, &batch.slice(idx, 1))
825            } else {
826                distance
827            }
828        }
829    }
830}
831
832/// Brute-force top-k search over raw vectors. Used for Indexing shards.
833fn flat_search(
834    raw: &[Vec<f32>],
835    query: &[f32],
836    top_k: usize,
837    metric: VectorMetric,
838) -> Vec<(RowId, f32)> {
839    let mut results: Vec<(RowId, f32)> = raw
840        .iter()
841        .enumerate()
842        .map(|(i, v)| (RowId::new(i as u64), exact_distance(metric, query, v)))
843        .collect();
844    results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
845    results.truncate(top_k);
846    results
847}
848
849fn parse_metric(s: &str) -> VectorMetric {
850    match s {
851        "euclidean" => VectorMetric::Euclidean,
852        "dotproduct" | "dot_product" | "dot" => VectorMetric::DotProduct,
853        "normalized_cosine" | "normalizedcosine" => VectorMetric::NormalizedCosine,
854        _ => VectorMetric::Cosine,
855    }
856}
857
858/// Pre-loaded search session: all HNSW indexes loaded into memory once.
859///
860/// Useful for benchmarks and servers that issue many queries against the same
861/// snapshot. Avoids re-loading and re-deserializing indexes on every call.
862pub struct SearchSession {
863    shards: Vec<LoadedShard>,
864    metric: VectorMetric,
865}
866
867struct LoadedShard {
868    entry: DataFileEntry,
869    /// None when the shard is still being indexed (IndexStatus::Indexing).
870    index: Option<AnyIndex>,
871    /// Raw F32 vectors: always present for Indexing shards (flat scan), optionally
872    /// present for Ready shards when `load_raw = true` (reranking).
873    raw_vectors: Option<Vec<Vec<f32>>>,
874}
875
876impl SearchSession {
877    /// Load all indexes for the latest snapshot into memory.
878    ///
879    /// Pass `load_raw = true` when reranking will be used (`rerank_factor` is
880    /// `Some`); it reads the full parquet columns so exact distances are
881    /// available without extra I/O during `search_query`.
882    pub async fn load(
883        table: &TableIdent,
884        vector_column: &str,
885        dim: u32,
886        catalog: Arc<dyn CatalogProvider>,
887        store: Arc<dyn Store>,
888        load_raw: bool,
889    ) -> AilakeResult<Self> {
890        let all_files = catalog.list_files(table, None).await?;
891        let table_meta = catalog.load_table(table).await?;
892        let metric = parse_metric(
893            table_meta
894                .properties
895                .get("ailake.vector-metric")
896                .map(String::as_str)
897                .unwrap_or("cosine"),
898        );
899
900        let mut shards = Vec::with_capacity(all_files.len());
901        for entry in all_files {
902            let file_bytes: Bytes = store.get(&entry.path).await?;
903            let reader = AilakeFileReader::new(file_bytes, vector_column, dim);
904
905            if entry.index_status == IndexStatus::Indexing {
906                // HNSW not yet built — load raw vectors for flat scan.
907                let (_, raw_vecs) = reader.read_parquet()?;
908                shards.push(LoadedShard {
909                    entry,
910                    index: None,
911                    raw_vectors: Some(raw_vecs),
912                });
913            } else if reader.is_ailake_file() {
914                let mut index = reader.load_any_index_for_column(vector_column)?;
915                let raw_vectors = if load_raw {
916                    index.quantize_to_f16();
917                    let (_, vecs) = reader.read_parquet()?;
918                    Some(vecs)
919                } else {
920                    None
921                };
922                shards.push(LoadedShard {
923                    entry,
924                    index: Some(index),
925                    raw_vectors,
926                });
927            }
928        }
929
930        Ok(Self { shards, metric })
931    }
932
933    /// Number of loaded shards.
934    pub fn shard_count(&self) -> usize {
935        self.shards.len()
936    }
937
938    /// Search multiple queries in one call.
939    ///
940    /// For shards with raw vectors (Indexing or reranking): dispatches to GPU batch
941    /// matmul when a CUDA device is available, falling back to CPU flat scan.
942    /// For indexed shards (HNSW / IVF-PQ): rayon parallel-map over queries — graph
943    /// traversal is inherently sequential and has no GPU batch path.
944    ///
945    /// Returns one `Vec<SearchResult>` per input query, in the same order.
946    pub fn search_batch(
947        &self,
948        queries: &[Vec<f32>],
949        config: &SearchConfig,
950    ) -> Vec<Vec<SearchResult>> {
951        if queries.is_empty() {
952            return vec![];
953        }
954
955        let n_queries = queries.len();
956        let candidate_k = match config.rerank_factor {
957            Some(factor) => config.top_k * factor,
958            None => config.top_k,
959        };
960        let use_nvidia = ailake_index::hardware::detect_cuda();
961        let use_amd = ailake_index::hardware::detect_rocm();
962
963        // Accumulate per-query results across all shards.
964        let mut all_results: Vec<Vec<SearchResult>> = (0..n_queries).map(|_| Vec::new()).collect();
965
966        for shard in &self.shards {
967            if let Some(raw) = &shard.raw_vectors {
968                // Flat-scan shard — try GPU batch path (NVIDIA first, then AMD ROCm).
969                if !raw.is_empty() {
970                    let dim = raw[0].len();
971                    let flat: Vec<f32> = raw.iter().flat_map(|v| v.iter().copied()).collect();
972                    let row_ids: Vec<u64> = (0..raw.len() as u64).collect();
973                    let q_refs: Vec<&[f32]> = queries.iter().map(|q| q.as_slice()).collect();
974
975                    let gpu_batch = if use_nvidia {
976                        ailake_index::gpu::try_nvidia_search_batch(
977                            &q_refs,
978                            &row_ids,
979                            &flat,
980                            dim,
981                            self.metric,
982                            candidate_k,
983                        )
984                    } else if use_amd {
985                        ailake_index::gpu::try_rocm_search_batch(
986                            &q_refs,
987                            &row_ids,
988                            &flat,
989                            dim,
990                            self.metric,
991                            candidate_k,
992                        )
993                    } else {
994                        None
995                    };
996
997                    if let Some(batch) = gpu_batch {
998                        for (qi, results) in batch.into_iter().enumerate() {
999                            for (row_id, distance) in results {
1000                                all_results[qi].push(SearchResult {
1001                                    row_id,
1002                                    distance,
1003                                    file_path: shard.entry.path.clone(),
1004                                });
1005                            }
1006                        }
1007                        continue;
1008                    }
1009                }
1010
1011                // CPU fallback for flat scan.
1012                for (qi, query) in queries.iter().enumerate() {
1013                    for (row_id, distance) in flat_search(raw, query, candidate_k, self.metric) {
1014                        all_results[qi].push(SearchResult {
1015                            row_id,
1016                            distance,
1017                            file_path: shard.entry.path.clone(),
1018                        });
1019                    }
1020                }
1021            } else if let Some(index) = &shard.index {
1022                // Indexed shard — rayon parallel-map over queries.
1023                let shard_results: Vec<Vec<SearchResult>> = queries
1024                    .par_iter()
1025                    .map(|query| {
1026                        index
1027                            .search(query, candidate_k, config.ef_search)
1028                            .into_iter()
1029                            .map(|(row_id, distance)| SearchResult {
1030                                row_id,
1031                                distance,
1032                                file_path: shard.entry.path.clone(),
1033                            })
1034                            .collect()
1035                    })
1036                    .collect();
1037
1038                for (qi, results) in shard_results.into_iter().enumerate() {
1039                    all_results[qi].extend(results);
1040                }
1041            }
1042        }
1043
1044        // Sort + truncate per query.
1045        for results in &mut all_results {
1046            results.sort_by(|a, b| {
1047                a.distance
1048                    .partial_cmp(&b.distance)
1049                    .unwrap_or(std::cmp::Ordering::Equal)
1050            });
1051            results.truncate(config.top_k);
1052        }
1053
1054        all_results
1055    }
1056
1057    /// Search using pre-loaded indexes. No I/O — pure in-memory search.
1058    pub fn search_query(&self, query: &[f32], config: &SearchConfig) -> Vec<SearchResult> {
1059        let candidate_k = match config.rerank_factor {
1060            Some(factor) => config.top_k * factor,
1061            None => config.top_k,
1062        };
1063
1064        let mut all_results: Vec<SearchResult> = self
1065            .shards
1066            .par_iter()
1067            .flat_map(|shard| {
1068                // Geometric pruning per shard.
1069                if let Some(centroid) = ailake_catalog::decode_centroid(&shard.entry, self.metric) {
1070                    let dist = match self.metric {
1071                        VectorMetric::Cosine | VectorMetric::NormalizedCosine => {
1072                            ailake_vec::cosine_distance(query, &centroid.values)
1073                        }
1074                        VectorMetric::Euclidean => {
1075                            ailake_vec::euclidean_distance(query, &centroid.values)
1076                        }
1077                        VectorMetric::DotProduct => {
1078                            -ailake_vec::dot_product(query, &centroid.values)
1079                        }
1080                    };
1081                    if dist - centroid.radius > config.pruning_threshold {
1082                        return vec![];
1083                    }
1084                }
1085
1086                if let Some(index) = &shard.index {
1087                    // Ready shard: HNSW or IVF-PQ search (dispatched by AnyIndex).
1088                    let local_results = index.search(query, candidate_k, config.ef_search);
1089                    if config.rerank_factor.is_some() {
1090                        if let Some(raw) = &shard.raw_vectors {
1091                            local_results
1092                                .into_iter()
1093                                .map(|(row_id, _approx_dist)| {
1094                                    let idx = row_id.as_u64() as usize;
1095                                    let exact_dist = raw
1096                                        .get(idx)
1097                                        .map(|v| exact_distance(self.metric, query, v))
1098                                        .unwrap_or(f32::INFINITY);
1099                                    SearchResult {
1100                                        row_id,
1101                                        distance: exact_dist,
1102                                        file_path: shard.entry.path.clone(),
1103                                    }
1104                                })
1105                                .collect()
1106                        } else {
1107                            local_results
1108                                .into_iter()
1109                                .map(|(row_id, distance)| SearchResult {
1110                                    row_id,
1111                                    distance,
1112                                    file_path: shard.entry.path.clone(),
1113                                })
1114                                .collect()
1115                        }
1116                    } else {
1117                        local_results
1118                            .into_iter()
1119                            .map(|(row_id, distance)| SearchResult {
1120                                row_id,
1121                                distance,
1122                                file_path: shard.entry.path.clone(),
1123                            })
1124                            .collect()
1125                    }
1126                } else if let Some(raw) = &shard.raw_vectors {
1127                    // Indexing shard: exact flat scan.
1128                    flat_search(raw, query, candidate_k, self.metric)
1129                        .into_iter()
1130                        .map(|(row_id, distance)| SearchResult {
1131                            row_id,
1132                            distance,
1133                            file_path: shard.entry.path.clone(),
1134                        })
1135                        .collect()
1136                } else {
1137                    vec![]
1138                }
1139            })
1140            .collect();
1141
1142        all_results.sort_by(|a, b| {
1143            a.distance
1144                .partial_cmp(&b.distance)
1145                .unwrap_or(std::cmp::Ordering::Equal)
1146        });
1147        all_results.truncate(config.top_k);
1148        all_results
1149    }
1150}
1151
1152/// Pure BM25 full-text search across all Parquet files in the table.
1153///
1154/// Scans every surviving file (O(N) complexity), scores each row with BM25 against
1155/// `query_text`, and returns the global top-k by score. IDF stats are loaded from
1156/// `metadata/ailake_bm25_stats.bin` (written by `TableWriter` when `bm25_text_column`
1157/// is configured). If the stats file is absent, IDF defaults to an empty corpus
1158/// (all terms treated as maximally rare — directionally correct but less precise).
1159///
1160/// For pure-lexical search at scale (millions of rows, hundreds of files), consider
1161/// using SQL `LIKE` / `ILIKE` via DuckDB/Trino over the Iceberg-compatible table.
1162/// This function is best suited for small-medium tables or as a lexical complement
1163/// to `search()` for tables where the document count per file is manageable.
1164pub async fn search_text(
1165    table: &TableIdent,
1166    query_text: &str,
1167    text_columns: &[&str],
1168    top_k: usize,
1169    catalog: Arc<dyn CatalogProvider>,
1170    store: Arc<dyn Store>,
1171    partition_filter: Option<&str>,
1172) -> AilakeResult<Vec<SearchResult>> {
1173    use arrow_array::cast::AsArray;
1174
1175    if text_columns.is_empty() {
1176        return Err(AilakeError::InvalidArgument(
1177            "search_text requires at least one text column".into(),
1178        ));
1179    }
1180
1181    let all_files = catalog.list_files(table, None).await?;
1182    let table_meta = catalog.load_table(table).await?;
1183
1184    // Partition pruning
1185    let files: Vec<_> = if let Some(pv) = partition_filter {
1186        all_files
1187            .into_iter()
1188            .filter(|f| f.partition_value.as_deref() == Some(pv))
1189            .collect()
1190    } else {
1191        all_files
1192    };
1193
1194    // Load BM25 stats
1195    let stats_path = table_meta
1196        .properties
1197        .get(crate::bm25::BM25_STATS_PATH_PROP)
1198        .map(String::as_str)
1199        .unwrap_or(crate::bm25::BM25_STATS_FILE);
1200    let stats = match store.get(stats_path).await {
1201        Ok(bytes) => crate::bm25::IdfStats::from_bytes(&bytes).unwrap_or_default(),
1202        Err(_) => {
1203            debug!(
1204                "ailake: BM25 stats not found at '{}' — using empty corpus IDF",
1205                stats_path
1206            );
1207            crate::bm25::IdfStats::default()
1208        }
1209    };
1210    let scorer = crate::bm25::BM25Scorer::new(&stats);
1211
1212    // Phase H: equality delete filter for search_text results.
1213    let eq_del_filter = match catalog.list_equality_deletes(table, None).await {
1214        Ok(edfs) if !edfs.is_empty() => {
1215            match EqualityDeleteFilter::from_files(&store, &edfs).await {
1216                Ok(f) => f,
1217                Err(e) => {
1218                    warn!("ailake: equality delete filter build failed in search_text: {e}");
1219                    EqualityDeleteFilter::empty()
1220                }
1221            }
1222        }
1223        _ => EqualityDeleteFilter::empty(),
1224    };
1225
1226    let mut results: Vec<SearchResult> = Vec::new();
1227
1228    for file_entry in &files {
1229        let file_bytes = store.get(&file_entry.path).await?;
1230        // Use dim=0 — we only read the Parquet columns, not the HNSW.
1231        let reader = AilakeFileReader::new(file_bytes.clone(), "", 0);
1232
1233        // Fast path: per-file Tantivy index (O(log N) via inverted index).
1234        // Falls back to BM25 O(N) brute-force for files without an FTS section.
1235        if let Ok(Some(fts_blob)) = reader.load_fts_blob() {
1236            match ailake_fts::FtsSearcher::from_blob(&fts_blob) {
1237                Ok(fts) => {
1238                    let hits = fts.search(query_text, top_k * 3).unwrap_or_default();
1239                    if !hits.is_empty() {
1240                        // Load batch only for equality delete checking (not for scoring).
1241                        let reader2 = AilakeFileReader::new(file_bytes, "", 0);
1242                        let (raw_batch, _) = reader2.read_parquet()?;
1243                        let batch = SchemaFiller::fill(raw_batch, &table_meta.schema_fields)?;
1244                        for hit in hits {
1245                            let row_idx = hit.row_id as usize;
1246                            if row_idx >= batch.num_rows() {
1247                                continue;
1248                            }
1249                            if eq_del_filter.should_delete_row(&batch, row_idx) {
1250                                continue;
1251                            }
1252                            results.push(SearchResult {
1253                                row_id: RowId::new(hit.row_id),
1254                                distance: -hit.score,
1255                                file_path: file_entry.path.clone(),
1256                            });
1257                        }
1258                    }
1259                    continue; // skip O(N) BM25 fallback
1260                }
1261                Err(e) => {
1262                    warn!("ailake: FTS blob corrupt for '{}': {e}", file_entry.path);
1263                    // fall through to BM25 brute-force
1264                }
1265            }
1266        }
1267
1268        // Fallback: O(N) BM25 brute-force — unchanged from pre-Phase-T behaviour.
1269        let reader_fb = AilakeFileReader::new(file_bytes, "", 0);
1270        let (raw_batch, _) = reader_fb.read_parquet()?;
1271        // Phase G: fill missing columns for old files before BM25 text extraction.
1272        let batch = SchemaFiller::fill(raw_batch, &table_meta.schema_fields)?;
1273
1274        for row_idx in 0..batch.num_rows() {
1275            // Phase H: skip rows matched by equality delete predicate.
1276            if eq_del_filter.should_delete_row(&batch, row_idx) {
1277                continue;
1278            }
1279            let doc_text: String = text_columns
1280                .iter()
1281                .filter_map(|&col| {
1282                    batch.column_by_name(col).and_then(|arr| {
1283                        arr.as_string_opt::<i32>().and_then(|sa| {
1284                            if sa.is_valid(row_idx) {
1285                                Some(sa.value(row_idx).to_string())
1286                            } else {
1287                                None
1288                            }
1289                        })
1290                    })
1291                })
1292                .collect::<Vec<_>>()
1293                .join(" ");
1294
1295            if doc_text.is_empty() {
1296                continue;
1297            }
1298
1299            let bm25 = scorer.score(query_text, &doc_text);
1300            if bm25 > 0.0 {
1301                // Negate so that sort-ascending = best-first (lower distance = higher BM25).
1302                results.push(SearchResult {
1303                    row_id: RowId::new(row_idx as u64),
1304                    distance: -bm25,
1305                    file_path: file_entry.path.clone(),
1306                });
1307            }
1308        }
1309    }
1310
1311    results.sort_by(|a, b| a.distance.total_cmp(&b.distance));
1312    results.truncate(top_k);
1313    Ok(results)
1314}
1315
1316/// Fetch full row data for a slice of search results.
1317///
1318/// Groups results by Parquet file, reads each file once, extracts the matching rows
1319/// via `arrow_select::take`, then concatenates everything back in original top-k order
1320/// with a `_distance: Float32` column appended.
1321///
1322/// Use this immediately after `search()` to retrieve the actual text / metadata
1323/// columns (e.g. `chunk_text`, `document_title`) alongside the distance scores.
1324pub async fn fetch_rows(
1325    results: &[SearchResult],
1326    store: Arc<dyn Store>,
1327    vector_column: &str,
1328    dim: u32,
1329) -> AilakeResult<RecordBatch> {
1330    use std::collections::HashMap;
1331
1332    use arrow_array::{ArrayRef, Float32Array, UInt32Array};
1333    use arrow_schema::{DataType, Field, Schema};
1334    use arrow_select::{concat::concat_batches, take::take};
1335
1336    if results.is_empty() {
1337        return Ok(RecordBatch::new_empty(Arc::new(Schema::empty())));
1338    }
1339
1340    // Group by file path; preserve original position for re-sorting.
1341    let mut by_file: HashMap<&str, Vec<(u64, f32, usize)>> = HashMap::new();
1342    for (i, r) in results.iter().enumerate() {
1343        by_file
1344            .entry(r.file_path.as_str())
1345            .or_default()
1346            .push((r.row_id.as_u64(), r.distance, i));
1347    }
1348
1349    use arrow_array::FixedSizeListArray;
1350
1351    // (original_index, distance, single-row RecordBatch, decoded F32 vector)
1352    let mut collected: Vec<(usize, f32, RecordBatch, Vec<f32>)> = Vec::with_capacity(results.len());
1353
1354    for (file_path, rows) in &by_file {
1355        let bytes = store.get(file_path).await?;
1356        let reader = AilakeFileReader::new(bytes, vector_column, dim);
1357        let (batch, vectors) = reader.read_parquet()?;
1358
1359        for &(row_id, distance, pos) in rows {
1360            let idx = row_id as usize;
1361            if idx >= batch.num_rows() {
1362                tracing::warn!(
1363                    "fetch_rows: row_id {} out of bounds (file_rows={}, file={}), skipping",
1364                    idx,
1365                    batch.num_rows(),
1366                    file_path
1367                );
1368                continue;
1369            }
1370
1371            let indices = UInt32Array::from(vec![idx as u32]);
1372            let row_cols: Vec<ArrayRef> = batch
1373                .columns()
1374                .iter()
1375                .map(|col| {
1376                    take(col.as_ref(), &indices, None)
1377                        .map_err(|e| AilakeError::Arrow(e.to_string()))
1378                })
1379                .collect::<AilakeResult<Vec<_>>>()?;
1380
1381            let row_batch = RecordBatch::try_new(batch.schema(), row_cols)
1382                .map_err(|e| AilakeError::Arrow(e.to_string()))?;
1383
1384            // Capture decoded F32 vector for this row (empty vec if not available).
1385            let vec = vectors
1386                .get(idx)
1387                .cloned()
1388                .unwrap_or_else(|| vec![0.0f32; dim as usize]);
1389
1390            collected.push((pos, distance, row_batch, vec));
1391        }
1392    }
1393
1394    if collected.is_empty() {
1395        return Ok(RecordBatch::new_empty(Arc::new(Schema::empty())));
1396    }
1397
1398    // Restore original top-k order from the search results slice.
1399    collected.sort_by_key(|(pos, _, _, _)| *pos);
1400
1401    let distances: Vec<f32> = collected.iter().map(|(_, d, _, _)| *d).collect();
1402    let row_batches: Vec<&RecordBatch> = collected.iter().map(|(_, _, b, _)| b).collect();
1403    let base_schema = collected[0].2.schema();
1404
1405    let combined =
1406        concat_batches(&base_schema, row_batches).map_err(|e| AilakeError::Arrow(e.to_string()))?;
1407
1408    // Build FixedSizeList<Float32> column with decoded vectors (F32, not raw F16 bytes).
1409    let flat_vecs: Vec<f32> = collected
1410        .iter()
1411        .flat_map(|(_, _, _, v)| v.iter().copied())
1412        .collect();
1413    let item_field = Arc::new(Field::new("item", DataType::Float32, false));
1414    let values_arr = Arc::new(Float32Array::from(flat_vecs)) as ArrayRef;
1415    let vec_col = FixedSizeListArray::new(item_field.clone(), dim as i32, values_arr, None);
1416    let vec_field = Arc::new(Field::new(
1417        vector_column,
1418        DataType::FixedSizeList(item_field, dim as i32),
1419        false,
1420    ));
1421
1422    // Schema: tabular cols, then decoded vector col, then _distance.
1423    let mut fields: Vec<Arc<Field>> = base_schema.fields().to_vec();
1424    fields.push(vec_field);
1425    fields.push(Arc::new(Field::new("_distance", DataType::Float32, false)));
1426    let new_schema = Arc::new(Schema::new(fields));
1427
1428    let mut columns: Vec<ArrayRef> = combined.columns().to_vec();
1429    columns.push(Arc::new(vec_col));
1430    columns.push(Arc::new(Float32Array::from(distances)));
1431
1432    RecordBatch::try_new(new_schema, columns).map_err(|e| AilakeError::Arrow(e.to_string()))
1433}
1434
1435/// Load per-file BM25 Bloom filters from the Puffin stats file for the current snapshot.
1436///
1437/// Returns a map of `file_path → BloomFilter`. Empty map = no stats file available
1438/// (V2 table, first write, or fetch failure). The scanner applies Bloom pruning only
1439/// when the map is non-empty.
1440async fn load_bloom_map(
1441    table_meta: &ailake_catalog::TableMetadata,
1442    store: &dyn Store,
1443) -> std::collections::HashMap<String, crate::bloom::BloomFilter> {
1444    let stats_path = match &table_meta.current_statistics_path {
1445        Some(p) => p.clone(),
1446        None => return std::collections::HashMap::new(),
1447    };
1448    let bytes = match store.get(&stats_path).await {
1449        Ok(b) => b,
1450        Err(e) => {
1451            debug!("ailake: Phase F — could not load Puffin stats ({stats_path}): {e}");
1452            return std::collections::HashMap::new();
1453        }
1454    };
1455    let reader = ailake_catalog::AilakePuffinReader::new(&bytes);
1456    let bloom_entries = match reader.read_bm25_blooms() {
1457        Ok(e) => e,
1458        Err(e) => {
1459            warn!("ailake: Phase F — Puffin bloom parse error: {e}");
1460            return std::collections::HashMap::new();
1461        }
1462    };
1463    bloom_entries
1464        .into_iter()
1465        .filter_map(|entry| {
1466            let bf = crate::bloom::BloomFilter::from_bytes(&entry.bloom_bytes)?;
1467            Some((entry.path, bf))
1468        })
1469        .collect()
1470}
1471
1472#[cfg(test)]
1473mod tests {
1474    use super::*;
1475    use crate::writer::MultiVectorBatch;
1476    use ailake_catalog::{HadoopCatalog, TableIdent};
1477    use ailake_core::{VectorMetric, VectorPrecision, VectorStoragePolicy};
1478    use ailake_store::LocalStore;
1479    use arrow_array::{Int32Array, RecordBatch};
1480    use arrow_schema::{DataType, Field, Schema};
1481    use std::sync::Arc;
1482    use tempfile::TempDir;
1483
1484    fn make_policy(dim: u32) -> VectorStoragePolicy {
1485        VectorStoragePolicy {
1486            column_name: "embedding".to_string(),
1487            dim,
1488            metric: VectorMetric::Cosine,
1489            precision: VectorPrecision::F16,
1490            pq: None,
1491            keep_raw_for_reranking: true,
1492            pre_normalize: false,
1493            hnsw_m: None,
1494            hnsw_ef_construction: None,
1495            ivf_residual: false,
1496            embedding_model: None,
1497            modality: None,
1498            partition_by: None,
1499            partition_value: None,
1500            partition_column_type: None,
1501            partition_fields: vec![],
1502        }
1503    }
1504
1505    async fn write_demo_table(dir: &TempDir, dim: usize, rows: usize) {
1506        let store: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1507        let catalog = Arc::new(HadoopCatalog::new(store.clone(), "warehouse"));
1508        let table = TableIdent::new("default", "table");
1509
1510        let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
1511        let ids: Vec<i32> = (0..rows as i32).collect();
1512        let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(ids))]).unwrap();
1513
1514        // Each row i has embedding with 1.0 at dimension i and 0 elsewhere (unit basis vectors)
1515        let embeddings: Vec<Vec<f32>> = (0..rows)
1516            .map(|i| {
1517                let mut v = vec![0.0f32; dim];
1518                v[i % dim] = 1.0;
1519                v
1520            })
1521            .collect();
1522
1523        let mut writer =
1524            crate::TableWriter::create_or_open(catalog, store, make_policy(dim as u32), table, 2)
1525                .await
1526                .unwrap();
1527        writer.write_batch(&batch, &embeddings).await.unwrap();
1528        writer.commit().await.unwrap();
1529    }
1530
1531    #[tokio::test]
1532    async fn rerank_returns_correct_top_k_count() {
1533        let dir = TempDir::new().unwrap();
1534        let dim = 8usize;
1535        write_demo_table(&dir, dim, 8).await;
1536
1537        let store: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1538        let catalog: Arc<dyn CatalogProvider> =
1539            Arc::new(HadoopCatalog::new(store.clone(), "warehouse"));
1540        let table = TableIdent::new("default", "table");
1541
1542        let query = vec![1.0f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
1543        let config = SearchConfig {
1544            top_k: 3,
1545            ef_search: 50,
1546            pruning_threshold: f32::INFINITY,
1547            rerank_factor: Some(2),
1548            score_fn: None,
1549            partition_filter: None,
1550            hybrid: None,
1551        };
1552
1553        let results = search(
1554            &table,
1555            &query,
1556            config,
1557            "embedding",
1558            dim as u32,
1559            catalog,
1560            store,
1561        )
1562        .await
1563        .unwrap();
1564
1565        assert_eq!(results.len(), 3);
1566    }
1567
1568    #[tokio::test]
1569    async fn rerank_nearest_is_exact_match() {
1570        let dir = TempDir::new().unwrap();
1571        let dim = 8usize;
1572        write_demo_table(&dir, dim, 8).await;
1573
1574        let store: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1575        let catalog: Arc<dyn CatalogProvider> =
1576            Arc::new(HadoopCatalog::new(store.clone(), "warehouse"));
1577        let table = TableIdent::new("default", "table");
1578
1579        // Row 0 has [1,0,0,...] — cosine distance to same query is 0
1580        let query = vec![1.0f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
1581        let config = SearchConfig {
1582            top_k: 1,
1583            ef_search: 50,
1584            pruning_threshold: f32::INFINITY,
1585            rerank_factor: Some(4),
1586            score_fn: None,
1587            partition_filter: None,
1588            hybrid: None,
1589        };
1590
1591        let results = search(
1592            &table,
1593            &query,
1594            config,
1595            "embedding",
1596            dim as u32,
1597            catalog,
1598            store,
1599        )
1600        .await
1601        .unwrap();
1602
1603        assert_eq!(results.len(), 1);
1604        // Exact cosine distance between identical unit vectors is ~0 (F16 rounding allowed)
1605        assert!(
1606            results[0].distance < 1e-3,
1607            "distance was {}",
1608            results[0].distance
1609        );
1610        assert_eq!(results[0].row_id, RowId::new(0));
1611    }
1612
1613    #[tokio::test]
1614    async fn no_rerank_matches_default_behavior() {
1615        let dir = TempDir::new().unwrap();
1616        let dim = 4usize;
1617        write_demo_table(&dir, dim, 4).await;
1618
1619        let store_a: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1620        let store_b: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1621        let cat_a: Arc<dyn CatalogProvider> =
1622            Arc::new(HadoopCatalog::new(store_a.clone(), "warehouse"));
1623        let cat_b: Arc<dyn CatalogProvider> =
1624            Arc::new(HadoopCatalog::new(store_b.clone(), "warehouse"));
1625        let table = TableIdent::new("default", "table");
1626
1627        let query = vec![1.0f32, 0.0, 0.0, 0.0];
1628        let cfg_plain = SearchConfig {
1629            top_k: 2,
1630            ef_search: 50,
1631            pruning_threshold: f32::INFINITY,
1632            rerank_factor: None,
1633            score_fn: None,
1634            partition_filter: None,
1635            hybrid: None,
1636        };
1637        let cfg_rerank = SearchConfig {
1638            top_k: 2,
1639            ef_search: 50,
1640            pruning_threshold: f32::INFINITY,
1641            rerank_factor: Some(2),
1642            score_fn: None,
1643            partition_filter: None,
1644            hybrid: None,
1645        };
1646
1647        let plain = search(
1648            &table,
1649            &query,
1650            cfg_plain,
1651            "embedding",
1652            dim as u32,
1653            cat_a,
1654            store_a,
1655        )
1656        .await
1657        .unwrap();
1658        let reranked = search(
1659            &table,
1660            &query,
1661            cfg_rerank,
1662            "embedding",
1663            dim as u32,
1664            cat_b,
1665            store_b,
1666        )
1667        .await
1668        .unwrap();
1669
1670        // Both should return same top-1 result (row 0, distance ~0)
1671        assert_eq!(plain[0].row_id, reranked[0].row_id);
1672    }
1673
1674    #[tokio::test]
1675    async fn multimodal_rrf_returns_top_k() {
1676        let dir = TempDir::new().unwrap();
1677        let dim = 4usize;
1678        write_demo_table(&dir, dim, 4).await;
1679
1680        let store: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1681        let catalog: Arc<dyn CatalogProvider> =
1682            Arc::new(HadoopCatalog::new(store.clone(), "warehouse"));
1683        let table = TableIdent::new("default", "table");
1684
1685        // Two modal queries using the same column (single-column table).
1686        // Different queries to exercise RRF merging.
1687        let q1 = vec![1.0f32, 0.0, 0.0, 0.0];
1688        let q2 = vec![0.0f32, 1.0, 0.0, 0.0];
1689
1690        let queries = vec![
1691            ModalQuery {
1692                column: "embedding",
1693                query: &q1,
1694                weight: 0.7,
1695                dim: dim as u32,
1696            },
1697            ModalQuery {
1698                column: "embedding",
1699                query: &q2,
1700                weight: 0.3,
1701                dim: dim as u32,
1702            },
1703        ];
1704
1705        let config = SearchConfig {
1706            top_k: 2,
1707            ef_search: 50,
1708            pruning_threshold: f32::INFINITY,
1709            rerank_factor: None,
1710            score_fn: None,
1711            partition_filter: None,
1712            hybrid: None,
1713        };
1714
1715        let results =
1716            search_multimodal(&table, &queries, config, catalog, store, FusionMethod::Rrf)
1717                .await
1718                .unwrap();
1719
1720        assert_eq!(results.len(), 2);
1721        // RRF score stored as -distance; all should be negative
1722        assert!(results[0].distance <= 0.0);
1723        // Top result should be one of rows 0 or 1 (nearest to q1 or q2)
1724        assert!(results[0].row_id.as_u64() < 4);
1725    }
1726
1727    /// True cross-modal test: two columns with DIFFERENT dims (4 + 2).
1728    /// Verifies that search_multimodal correctly routes to each column's HNSW
1729    /// and that the dim validation in search() handles secondary columns.
1730    #[tokio::test]
1731    async fn multimodal_rrf_cross_modal_different_dims() {
1732        let dir = TempDir::new().unwrap();
1733        let store: Arc<dyn Store> = Arc::new(LocalStore::new(dir.path()));
1734        let catalog: Arc<dyn CatalogProvider> =
1735            Arc::new(HadoopCatalog::new(store.clone(), "warehouse"));
1736        let table = TableIdent::new("default", "table");
1737
1738        // Write a 2-column table: "embedding" dim=4, "img_embedding" dim=2
1739        let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
1740        let rows = 4usize;
1741        let ids: Vec<i32> = (0..rows as i32).collect();
1742        let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(ids))]).unwrap();
1743
1744        let text_embs: Vec<Vec<f32>> = (0..rows)
1745            .map(|i| {
1746                let mut v = vec![0.0f32; 4];
1747                v[i % 4] = 1.0;
1748                v
1749            })
1750            .collect();
1751        let img_embs: Vec<Vec<f32>> = (0..rows)
1752            .map(|i| {
1753                let mut v = vec![0.0f32; 2];
1754                v[i % 2] = 1.0;
1755                v
1756            })
1757            .collect();
1758
1759        let text_policy = make_policy(4);
1760        let img_policy = VectorStoragePolicy {
1761            column_name: "img_embedding".to_string(),
1762            dim: 2,
1763            metric: VectorMetric::Cosine,
1764            precision: VectorPrecision::F16,
1765            pq: None,
1766            keep_raw_for_reranking: true,
1767            pre_normalize: false,
1768            hnsw_m: None,
1769            hnsw_ef_construction: None,
1770            ivf_residual: false,
1771            embedding_model: None,
1772            modality: None,
1773            partition_by: None,
1774            partition_value: None,
1775            partition_column_type: None,
1776            partition_fields: vec![],
1777        };
1778
1779        let mut writer = crate::TableWriter::create_or_open(
1780            catalog.clone(),
1781            store.clone(),
1782            text_policy,
1783            table.clone(),
1784            2,
1785        )
1786        .await
1787        .unwrap();
1788
1789        let batches = [
1790            MultiVectorBatch {
1791                policy: make_policy(4),
1792                embeddings: &text_embs,
1793            },
1794            MultiVectorBatch {
1795                policy: img_policy,
1796                embeddings: &img_embs,
1797            },
1798        ];
1799        writer.write_batch_multi(&batch, &batches).await.unwrap();
1800        writer.commit().await.unwrap();
1801
1802        // Cross-modal search: text query (dim=4) + image query (dim=2).
1803        let q_text = vec![1.0f32, 0.0, 0.0, 0.0];
1804        let q_img = vec![1.0f32, 0.0];
1805
1806        let queries = vec![
1807            ModalQuery {
1808                column: "embedding",
1809                query: &q_text,
1810                weight: 0.6,
1811                dim: 4,
1812            },
1813            ModalQuery {
1814                column: "img_embedding",
1815                query: &q_img,
1816                weight: 0.4,
1817                dim: 2,
1818            },
1819        ];
1820        let config = SearchConfig {
1821            top_k: 2,
1822            ef_search: 50,
1823            pruning_threshold: f32::INFINITY,
1824            rerank_factor: None,
1825            score_fn: None,
1826            partition_filter: None,
1827            hybrid: None,
1828        };
1829
1830        let results =
1831            search_multimodal(&table, &queries, config, catalog, store, FusionMethod::Rrf)
1832                .await
1833                .unwrap();
1834
1835        assert!(!results.is_empty(), "should return results");
1836        assert!(results[0].distance <= 0.0, "distance is -rrf_score");
1837        // Row 0 is nearest to both q_text=[1,0,0,0] and q_img=[1,0]
1838        assert_eq!(results[0].row_id.as_u64(), 0, "row 0 should rank first");
1839    }
1840}