chrevanthreddy commented on code in PR #20107:
URL: https://github.com/apache/hudi/pull/20107#discussion_r4384294616


##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/analysis/PositionalParquetFetcher.scala:
##########
@@ -0,0 +1,587 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.hudi.analysis
+
+import org.apache.hudi.common.index.vector.{ScoredVectorPostingMatch, 
VectorIndexMdtSearchUtils, VectorPostingMatch}
+import org.apache.hudi.common.model.HoodieRecord
+import org.apache.hudi.common.schema.HoodieSchema
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.apache.parquet.column.page.PageReadStore
+import org.apache.parquet.hadoop.ParquetFileReader
+import org.apache.parquet.hadoop.metadata.{BlockMetaData, ColumnChunkMetaData, 
ParquetMetadata}
+import org.apache.parquet.internal.column.columnindex.OffsetIndex
+import org.apache.parquet.internal.filter2.columnindex.RowRanges
+import org.apache.parquet.io.{ColumnIOFactory, RecordReader}
+import org.apache.parquet.io.api.{Binary, Converter, GroupConverter, 
PrimitiveConverter, RecordMaterializer}
+import org.apache.parquet.schema.MessageType
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions.GenericInternalRow
+import 
org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction.DistanceMetric
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
+import org.slf4j.LoggerFactory
+
+import java.util.PrimitiveIterator
+import java.util.concurrent.ConcurrentHashMap
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable
+
+/**
+ * Fetches exact vector-search rerank candidates from Parquet by physical row 
position.
+ *
+ * The fetcher uses Parquet page indexes to turn candidate row positions into 
row ranges, so
+ * the reader can skip non-candidate pages instead of scanning whole Hudi file 
slices.
+ */
+private[analysis] final class PositionalParquetFetcher(
+    conf: Configuration,
+    embeddingCol: String,
+    vectorSchema: HoodieSchema.Vector,
+    queryVector: Array[Double],
+    metric: DistanceMetric.Value,
+    outputSchema: StructType,
+    failOnMissingOffsetIndex: Boolean,
+    vectorOnlyProjection: Boolean,
+    verifyKeys: Boolean) extends Serializable {
+
+  import PositionalParquetFetcher._
+
+  private val distanceOrdinal = 
outputSchema.fieldIndex(HoodieVectorSearchPlanBuilder.DISTANCE_COL)
+  private val recordKeyOrdinal = 
fieldOrdinal(HoodieRecord.RECORD_KEY_METADATA_FIELD)
+  private val partitionPathOrdinal = 
fieldOrdinal(HoodieRecord.PARTITION_PATH_METADATA_FIELD)
+  private val fileGroupIdOrdinal = 
fieldOrdinal(HoodieVectorSearchPlanBuilder.FILE_GROUP_ID_COL)
+  private val scorer = new VectorExactScorer(vectorSchema, queryVector, metric)
+  private var scoreMs: Long = 0L
+
+  def fetch(
+      filePath: String,
+      candidates: Seq[ScoredVectorPostingMatch]): FetchResult = {
+    val startNs = System.nanoTime()
+    if (candidates.isEmpty) {
+      FetchResult(Iterator.empty, Seq.empty, FetchMetrics(elapsedMs = 
elapsedMs(startNs)))
+    } else {
+      fetchNonEmpty(filePath, candidates, startNs)
+    }
+  }
+
+  private def fetchNonEmpty(
+      filePath: String,
+      candidates: Seq[ScoredVectorPostingMatch],
+      startNs: Long): FetchResult = {
+    val path = new Path(filePath)
+    configureRandomRead(conf)
+    val fs = path.getFileSystem(conf)
+    val fileLen = fs.getFileStatus(path).getLen
+    val fileCacheKey = s"$filePath#$fileLen"
+    val stats = Option(FileSystem.getStatistics(path.toUri.getScheme, 
fs.getClass))
+    val physicalBefore = stats.map(_.getBytesRead).getOrElse(0L)
+
+    val footerStartNs = System.nanoTime()
+    val footerResult = footer(conf, path, fileCacheKey)
+    val footerMs = elapsedMs(footerStartNs)
+    val metadata = footerResult.metadata
+    val fileSchema = metadata.getFileMetaData.getSchema
+    val requestedParquetSchema = requestedSchema(fileSchema)
+
+    val rowGroups = metadata.getBlocks.asScala.toIndexedSeq
+    val rowGroupStarts = cumulativeRowGroupStarts(rowGroups)
+    val byRowGroup: Map[Int, Seq[ScoredVectorPostingMatch]] =
+      candidates.groupBy(candidate => rowGroupOrdinal(rowGroupStarts, 
rowGroups, rowPosition(candidate)))
+
+    val rows = mutable.ArrayBuffer.empty[InternalRow]
+    val keyMismatches = mutable.ArrayBuffer.empty[ScoredVectorPostingMatch]
+    var rowGroupsSelected = 0
+    var pagesInSelectedRowGroups = 0L
+    var pagesSelected = 0L
+    var offsetIndexHits = 0L
+    var offsetIndexMissing = 0L
+    var pageBytesFetched = 0L
+    var rangedGets = 0L
+    var rowsDecoded = 0L
+    var rowsMaterialized = 0L
+    var offsetIndexMs = 0L
+    var decodeMs = 0L
+    scoreMs = 0L
+
+    val reader = new ParquetFileReader(conf, path, metadata)
+    try {
+      reader.setRequestedSchema(requestedParquetSchema)
+      byRowGroup.toSeq.sortBy(_._1).foreach { case (rgOrdinal, rgCandidates) =>
+        val block = rowGroups(rgOrdinal)
+        val rowGroupStart = rowGroupStarts(rgOrdinal)
+        val embeddingChunk = findColumn(block, embeddingCol)
+          .getOrElse(throw new IllegalArgumentException(s"Parquet file 
'$filePath' is missing vector column '$embeddingCol'."))
+
+        val offsetStartNs = System.nanoTime()
+        val embeddingOffsetIndex = offsetIndex(reader, fileCacheKey, 
rgOrdinal, embeddingChunk)
+        offsetIndexMs += elapsedMs(offsetStartNs)
+        val relativeRows = rgCandidates.map(candidate => 
rowPosition(candidate) - rowGroupStart).sorted
+        val candidateRows = relativeRows.toSet
+        val candidateByRelativeRow = rgCandidates
+          .map(candidate => rowPosition(candidate) - rowGroupStart -> 
candidate)
+          .toMap
+
+        if (embeddingOffsetIndex == null && failOnMissingOffsetIndex) {
+          offsetIndexMissing += 1
+          throw new IllegalStateException(
+            s"Parquet file '$filePath' has no OffsetIndex for vector column 
'$embeddingCol'; positional exact fetch cannot honor pages.")
+        }
+
+        rowGroupsSelected += 1
+        val (pageStore, rowRanges) = if (embeddingOffsetIndex == null) {
+          offsetIndexMissing += 1
+          LOG.warn(
+            "Parquet file {} rowGroup={} has no OffsetIndex for vector column 
{}; falling back to row-group fetch.",
+            filePath,
+            Int.box(rgOrdinal),
+            embeddingCol)
+          pagesInSelectedRowGroups += 0L
+          pagesSelected += 0L
+          rangedGets += 1L
+          pageBytesFetched += requestedParquetSchema.getFields.asScala
+            .flatMap(field => findColumn(block, field.getName))
+            .map(_.getTotalSize)
+            .sum
+          (reader.readRowGroup(rgOrdinal), 
RowRanges.createSingle(block.getRowCount))
+        } else {
+          offsetIndexHits += 1
+          pagesInSelectedRowGroups += embeddingOffsetIndex.getPageCount
+          val selectedVectorPages = selectedPages(embeddingOffsetIndex, 
block.getRowCount, relativeRows)
+          pagesSelected += selectedVectorPages.size
+          val selectedRanges = requestedParquetSchema.getFields.asScala
+            .flatMap(field => findColumn(block, field.getName))
+            .flatMap { chunk =>
+              val oiStartNs = System.nanoTime()
+              val chunkOffsetIndex = offsetIndex(reader, fileCacheKey, 
rgOrdinal, chunk)
+              offsetIndexMs += elapsedMs(oiStartNs)
+              if (chunkOffsetIndex == null) {
+                offsetIndexMissing += 1
+                Seq.empty
+              } else {
+                offsetIndexHits += 1
+                selectedPages(chunkOffsetIndex, block.getRowCount, 
relativeRows).map { pageOrdinal =>
+                  val start = chunkOffsetIndex.getOffset(pageOrdinal)
+                  PageRange(start, start + 
chunkOffsetIndex.getCompressedPageSize(pageOrdinal))
+                }
+              }
+            }
+          val mergedRanges = mergeRanges(selectedRanges.sortBy(_.start).toSeq)
+          rangedGets += mergedRanges.size
+          pageBytesFetched += mergedRanges.iterator.map(range => range.end - 
range.start).sum
+          val ranges = RowRanges.create(block.getRowCount, 
primitiveIntIterator(selectedVectorPages), embeddingOffsetIndex)
+          (reader.readFilteredRowGroup(rgOrdinal, ranges), ranges)
+        }
+
+        val decodeStartNs = System.nanoTime()
+        val recordReader = parquetRecordReader(fileSchema, 
requestedParquetSchema, pageStore)
+        val rowIterator = rowRanges.iterator()
+        while (rowIterator.hasNext) {
+          val relativeRow = rowIterator.nextLong()
+          val row = recordReader.read()
+          rowsDecoded += 1
+          candidateByRelativeRow.get(relativeRow).foreach { candidate =>
+            if (verifyKeys && decodedRecordKey(row) != candidate.getRecordKey) 
{
+              keyMismatches += candidate
+            } else {
+              fillSyntheticFields(row, candidate)
+              rows += row
+              rowsMaterialized += 1
+            }
+          }
+        }
+        decodeMs += elapsedMs(decodeStartNs)
+      }
+    } finally {
+      reader.close()
+    }
+
+    val physicalAfter = stats.map(_.getBytesRead).getOrElse(physicalBefore)
+    val metrics = FetchMetrics(
+      rerankCandidates = candidates.size,
+      rowGroupsTotal = rowGroups.size,
+      rowGroupsSelected = rowGroupsSelected,
+      pagesInSelectedRowGroups = pagesInSelectedRowGroups,
+      pagesSelected = pagesSelected,
+      offsetIndexHits = offsetIndexHits,
+      offsetIndexMissing = offsetIndexMissing,
+      rangedGets = rangedGets,
+      pageBytesFetched = pageBytesFetched,
+      rowsDecoded = rowsDecoded,
+      rowsMaterialized = rowsMaterialized,
+      fetchKeyMismatch = keyMismatches.size,
+      physicalBytesRead = math.max(0L, physicalAfter - physicalBefore),
+      footerReads = if (footerResult.cacheHit) 0 else 1,
+      footerCacheHits = if (footerResult.cacheHit) 1 else 0,
+      footerMs = footerMs,
+      offsetIndexMs = offsetIndexMs,
+      fetchWaitMs = 0L,
+      decodeMs = decodeMs,
+      scoreMs = scoreMs,
+      elapsedMs = elapsedMs(startNs))
+    FetchResult(rows.iterator, keyMismatches.toSeq, metrics)
+  }
+
+  private def parquetRecordReader(
+      fileSchema: MessageType,
+      requestedParquetSchema: MessageType,
+      pageStore: PageReadStore): RecordReader[InternalRow] = {
+    val materializer = new InternalRowMaterializer(requestedParquetSchema, 
outputSchema, embeddingCol, distanceOrdinal)
+    new ColumnIOFactory().getColumnIO(requestedParquetSchema, fileSchema)
+      .getRecordReader(pageStore, materializer)
+  }
+
+  private def requestedSchema(fileSchema: MessageType): MessageType = {
+    val parquetFields =
+      if (vectorOnlyProjection) {
+        mutable.ArrayBuffer.empty[org.apache.parquet.schema.Type]
+      } else {
+        outputSchema.fields
+          .filterNot(field => isSyntheticOutputField(field.name))
+          .map(field => fieldByName(fileSchema, field.name))
+          .toBuffer[org.apache.parquet.schema.Type]
+      }
+    if ((verifyKeys || vectorOnlyProjection) && 
!parquetFields.exists(_.getName == HoodieRecord.RECORD_KEY_METADATA_FIELD)) {
+      parquetFields += fieldByName(fileSchema, 
HoodieRecord.RECORD_KEY_METADATA_FIELD)
+    }
+    if (!parquetFields.exists(_.getName == embeddingCol)) {
+      parquetFields += fieldByName(fileSchema, embeddingCol)
+    }
+    new MessageType(fileSchema.getName, parquetFields.asJava)
+  }
+
+  private def isSyntheticOutputField(name: String): Boolean =
+    name == HoodieVectorSearchPlanBuilder.DISTANCE_COL ||
+      name == HoodieRecord.RECORD_KEY_METADATA_FIELD ||
+      name == HoodieRecord.PARTITION_PATH_METADATA_FIELD ||
+      name == HoodieVectorSearchPlanBuilder.FILE_GROUP_ID_COL
+
+  private def fieldByName(schema: MessageType, name: String): 
org.apache.parquet.schema.Type =
+    schema.getFields.asScala.find(_.getName == name)
+      .getOrElse(throw new IllegalArgumentException(s"Parquet schema is 
missing requested field '$name'."))
+
+  private def rowPosition(candidate: ScoredVectorPostingMatch): Long = {
+    val location = candidate.getLocation
+    if (location == null) {
+      throw new IllegalArgumentException(
+        s"Vector exact positional fetch requires a row-position locator for 
record ${candidate.getRecordKey}.")
+    }
+    location.getPosition
+  }
+
+  private def decodedRecordKey(row: InternalRow): String =
+    recordKeyOrdinal.flatMap(ordinal => 
Option(row.getUTF8String(ordinal))).map(_.toString).orNull
+
+  private def fillSyntheticFields(row: InternalRow, candidate: 
ScoredVectorPostingMatch): Unit = {
+    val liveLocation = Option(candidate.getLocation)
+    recordKeyOrdinal.foreach(row.update(_, 
UTF8String.fromString(candidate.getRecordKey)))
+    partitionPathOrdinal.foreach(row.update(_, UTF8String.fromString(
+      
liveLocation.map(_.getPartitionPath).orElse(Option(candidate.getPartitionPath)).getOrElse(""))))
+    fileGroupIdOrdinal.foreach(row.update(_, UTF8String.fromString(
+      
liveLocation.map(_.getFileId).orElse(Option(candidate.getFileGroupId)).getOrElse(""))))
+  }
+
+  private def fieldOrdinal(name: String): Option[Int] =
+    outputSchema.fields.indexWhere(_.name == name) match {
+      case -1 => None
+      case ordinal => Some(ordinal)
+    }
+
+  private def scoreVector(bytes: Array[Byte]): Double = 
scorer.scoreBytes(bytes)
+
+  private final class InternalRowMaterializer(
+      requestedParquetSchema: MessageType,
+      outputSchema: StructType,
+      embeddingCol: String,
+      distanceOrdinal: Int) extends RecordMaterializer[InternalRow] {
+
+    private val values = new Array[Any](outputSchema.length)
+    private var current: InternalRow = _
+    private var vectorBytes: Array[Byte] = _
+
+    private val root = new GroupConverter {
+      private val converters = 
requestedParquetSchema.getFields.asScala.map(converterFor).toIndexedSeq
+
+      override def getConverter(fieldIndex: Int): Converter =
+        converters(fieldIndex)
+
+      override def start(): Unit = {
+        var idx = 0
+        while (idx < values.length) {
+          values(idx) = null
+          idx += 1
+        }
+        vectorBytes = null
+      }
+
+      override def end(): Unit = {
+        if (vectorBytes == null) {
+          throw new IllegalStateException(s"Vector column '$embeddingCol' was 
not decoded for positional exact fetch.")

Review Comment:
   **Fixed**. A live row with a NULL embedding is skipped (counted as 
`nullEmbeddingsSkipped`), matching brute force.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/analysis/VectorExactSearchPlanner.scala:
##########
@@ -0,0 +1,390 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.hudi.analysis
+
+import org.apache.hudi.SparkAdapterSupport
+import org.apache.hudi.client.common.HoodieSparkEngineContext
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.config.TypedProperties
+import org.apache.hudi.common.index.vector.{ScoredVectorPostingMatch, 
VectorDistanceMetric, VectorIndexArbiter, VectorIndexMdtSearchUtils, 
VectorIndexMetadataCache, VectorIndexOptions, VectorPostingMatch, 
VectorStalePolicy}
+import org.apache.hudi.common.model.{FileSlice, HoodieIndexDefinition, 
HoodieRecord}
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, 
TableSchemaResolver}
+import org.apache.hudi.common.table.timeline.{HoodieTimeline, 
InstantComparison}
+import 
org.apache.hudi.common.table.timeline.InstantComparison.compareTimestamps
+import org.apache.hudi.common.table.view.HoodieTableFileSystemView
+import org.apache.hudi.data.HoodieJavaRDD
+import org.apache.hudi.hadoop.fs.HadoopFSUtils
+import org.apache.hudi.metadata.{HoodieTableMetadata, HoodieTableMetadataUtil}
+
+import org.apache.spark.api.java.JavaSparkContext
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.parser.ParseException
+import 
org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction
+import 
org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction.{DistanceMetric,
 SearchAlgorithm}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.expressions.Window
+import org.apache.spark.sql.functions.{broadcast, col, 
monotonically_increasing_id, row_number}
+import org.apache.spark.sql.hudi.command.exception.HoodieAnalysisException
+import org.apache.spark.sql.types.{ArrayType, ByteType, DataType, DoubleType, 
FloatType, Metadata, StructField, StructType}
+import org.apache.spark.util.LongAccumulator
+import org.slf4j.LoggerFactory
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable.ArrayBuffer
+import scala.util.{Failure, Success, Try}
+
+/** Exact reranking and file-slice resolution for the IVF/RaBitQ search plan. 
*/
+private[analysis] object VectorExactSearchPlanner extends SparkAdapterSupport {
+  import HoodieVectorSearchPlanBuilder._
+  import IvfRaBitQMdtSearchAlgorithm.{isLogResidentCandidate, 
isPartitionedRecordIndex, toVectorMetric, VectorSearchPlanContext}
+
+  private val LOG = LoggerFactory.getLogger(getClass)
+
+  def buildRaBitQExactCandidateDf(
+      spark: SparkSession,
+      ctx: VectorSearchPlanContext,
+      outputSchema: StructType,
+      embeddingCol: String,
+      vectorSchema: HoodieSchema.Vector,
+      queryVector: Array[Float],
+      exactQueryVector: Array[Double],
+      k: Int): DataFrame = {
+    val planStartNs = System.nanoTime()
+    val storageConf = 
HadoopFSUtils.getStorageConf(spark.sessionState.newHadoopConf())
+    val cacheLoadStartNs = System.nanoTime()
+    val cache = ctx.cache
+    val mergedOptions = ctx.tuningOptions
+    val metric = toVectorMetric(ctx.metric)
+    val residualEncoding = cache.isResidualEncoding
+    val numProbes = math.min(math.max(1, 
VectorIndexOptions.getNumProbes(mergedOptions.asJava)), cache.numClusters())
+    val topClusters = cache.findTopClusters(queryVector, numProbes, metric)
+    val topClusterSeq = topClusters.toSeq
+    val cacheLoadMs = elapsedMs(cacheLoadStartNs)
+
+    // Shard counts from cache — no extra MDT IO.
+    val shardCounts = cache.getShardCounts(topClusters)
+    val shardCountsScala = shardCounts.asScala.map { case (clusterId, count) =>
+      clusterId.intValue() -> count.intValue()
+    }.toMap
+    val postingPrefixCount = 
VectorIndexMdtSearchUtils.buildPostingPrefixes(cache.getGenerationId, 
shardCounts).size()
+    LOG.info(
+      s"[vector_search][plan] basePath=${ctx.basePath} 
indexPartition=${ctx.indexPartition} cacheLoadMs=$cacheLoadMs " +
+        s"generationId=${cache.getGenerationId} 
dimension=${cache.getDimension} numClusters=${cache.numClusters()} " +
+        s"numProbes=$numProbes 
refineFactor=${VectorIndexOptions.getRefineFactor(mergedOptions.asJava)} 
residualEncoding=$residualEncoding " +
+        s"topClusters=${summarizeInts(topClusterSeq)} 
shardCounts=${summarizeShardCounts(shardCountsScala)} " +
+        s"postingPrefixes=$postingPrefixCount")
+    if (shardCounts.isEmpty) {
+      sparkAdapter.getUnsafeUtils.createDataFrameFromRDD(
+        spark, spark.sparkContext.emptyRDD[InternalRow], outputSchema)
+    } else {
+      val refineK = math.max(k, k * 
VectorIndexOptions.getRefineFactor(mergedOptions.asJava))
+      val emptyDf = sparkAdapter.getUnsafeUtils.createDataFrameFromRDD(
+        spark, spark.sparkContext.emptyRDD[InternalRow], outputSchema)
+
+      val topCandidates = VectorIndexMdtSearchUtils.scanPostingCandidates(
+        ctx.metadataTable, ctx.indexPartition, cache.getGenerationId, 
shardCounts,
+        queryVector, cache.getDimension, cache.getQuantizerSeed, 
cache.getRaBitQBits, cache.isAssumeNormalized,
+        metric, 
VectorIndexOptions.isRaBitQAsymmetricScoring(mergedOptions.asJava),
+        residualEncoding, if (residualEncoding) cache.getCentroids else null, 
refineK)
+      val topCandidateMaterializeStartNs = System.nanoTime()
+      val materializedCandidates = try {
+        topCandidates.collectAsList().asScala.toSeq
+      } finally {
+        topCandidates.unpersistWithDependencies()
+      }
+      val topCandidateList = materializedCandidates
+        .filter(candidate => candidate.getFileGroupId != null && 
candidate.getFileGroupId.nonEmpty)
+      val candidatesWithoutLocator = materializedCandidates.size - 
topCandidateList.size
+      LOG.info(
+        s"[vector_search][stage][materialize_top_candidates] refineK=$refineK 
rerankCandidates=${materializedCandidates.size} " +
+          s"candidatesWithLocators=${topCandidateList.size} 
candidatesWithoutLocators=$candidatesWithoutLocator " +
+          
s"distinctFileGroups=${topCandidateList.map(_.getFileGroupId).distinct.size} 
elapsedMs=${elapsedMs(topCandidateMaterializeStartNs)}")
+      if (candidatesWithoutLocator > 0) {
+        throw new HoodieAnalysisException(
+          s"Vector exact search found $candidatesWithoutLocator rerank 
candidates without file-group locators. " +
+            s"Exact rerank requires per-candidate posting locators.")
+      }
+
+      // RFC-109 RLI finalist arbiter. Exact mode uses refreshed RLI locations 
for every live
+      // candidate: SERVE retains positional trust; STALE is resolved by key 
in the live base file.
+      val arbiterEnabled = 
VectorIndexOptions.isFinalistArbiterEnabled(mergedOptions.asJava)
+      val serveCandidates: Seq[ScoredVectorPostingMatch] =
+        if (arbiterEnabled) {
+          val arb = VectorIndexMdtSearchUtils.arbitrateMaterializedFinalists(
+            ctx.metadataTable, topCandidateList.asJava, 
isPartitionedRecordIndex(ctx))
+          val staleFailPolicy = 
VectorIndexOptions.isStaleLocatorPolicyFail(mergedOptions.asJava)
+          LOG.info(
+            s"[vector_search][exact][arbiter] 
arbiterExclusions{stale=${arb.staleCount}, deleted=${arb.deletedCount}} " +
+              s"serve=${arb.serve.size} stalePolicy=${if (staleFailPolicy) 
"fail" else "fallback"}")
+          if (staleFailPolicy && !arb.stale.isEmpty) {
+            throw new HoodieAnalysisException(
+              s"Vector exact search rejected ${arb.staleCount} stale 
finalist(s) because " +
+                "vector.stale.locator.policy=FAIL.")
+          }
+          arb.serve.asScala.toSeq ++ arb.stale.asScala.toSeq
+        } else {
+          topCandidateList
+        }
+
+      if (serveCandidates.isEmpty) {
+        emptyDf
+      } else {
+        val candidatesByPartition = serveCandidates
+          .groupBy(candidate => 
Option(candidate.getLocation).map(_.getPartitionPath).getOrElse(""))
+          .map { case (partitionPath, candidates) =>
+            partitionPath -> candidates.flatMap(candidate => 
Option(candidate.getLocation).map(_.getFileId)).toSet
+          }
+        val fileSliceMap = preResolveFileSlices(
+          ctx.metadataTable, ctx.metaClient, ctx.timeline, 
ctx.latestInstantTime, candidatesByPartition)
+        if (fileSliceMap.isEmpty) {
+          throw new HoodieAnalysisException(
+            s"Vector exact search resolved zero file slices for 
${serveCandidates.size} rerank candidates " +
+              s"across ${candidatesByPartition.values.map(_.size).sum} file 
groups. Candidate locators are present, so this indicates " +
+              s"a file-slice resolution bug or stale vector index.")
+        }
+        val bFileSliceMap = spark.sparkContext.broadcast(fileSliceMap)
+        // MOR log-resident candidates carry their raw embedding in a log 
block, not the base Parquet
+        // file, so the positional fetcher cannot read them. Split them out 
and materialize them via a
+        // merged (base + log) read; base-resident candidates keep the fast 
positional path.
+        val (logResidentCandidates, baseCandidates) = 
serveCandidates.partition { candidate =>
+          bFileSliceMap.value.get(candidate.getLocation.getFileId).exists { 
slice =>
+            isLogResidentCandidate(candidate, slice.getBaseInstantTime, 
slice.getLogFiles.findAny().isPresent)
+          }
+        }
+        val exactFetchParallelism = math.max(
+          1,
+          math.min(refineK, math.max(1, spark.sparkContext.defaultParallelism 
* 4)))
+        val groupedCandidates = 
baseCandidates.groupBy(_.getLocation.getFileId).toSeq.sortBy(_._1)
+        val targetBatchesPerGroup = math.max(1, exactFetchParallelism / 
math.max(1, groupedCandidates.size))
+        val fetchBatches = groupedCandidates.flatMap { case (fgId, candidates) 
=>
+          val sorted = candidates.sortBy(candidate => 
candidate.getLocation.getPosition)
+          val batchSize = math.max(1, math.ceil(sorted.size.toDouble / 
targetBatchesPerGroup).toInt)
+          sorted.grouped(batchSize).map(batch => (fgId, batch)).toSeq
+        }
+        val byFetchBatch: RDD[(String, Seq[ScoredVectorPostingMatch])] =
+          if (fetchBatches.isEmpty) {
+            spark.sparkContext.emptyRDD[(String, 
Seq[ScoredVectorPostingMatch])]
+          } else {
+            spark.sparkContext.parallelize(fetchBatches, 
math.min(exactFetchParallelism, fetchBatches.size))
+          }
+        LOG.info(
+          s"[vector_search][stage][exact_read_plan] 
rerankCandidates=${serveCandidates.size} " +
+            s"candidateGroups=${groupedCandidates.size} 
resolvedSlices=${fileSliceMap.size} " +
+            s"fileGroupPartitions=${byFetchBatch.getNumPartitions} 
exactFetchParallelism=$exactFetchParallelism")
+
+        val vectorOnlyProjection = 
mergedOptions.get(VECTOR_ONLY_PROJECTION_OPT)
+          .orElse(spark.conf.getOption(VECTOR_ONLY_PROJECTION_SPARK_CONF))
+          .exists(_.equalsIgnoreCase("true"))
+        val fetchSkippedLogResidentAcc: LongAccumulator =
+          
spark.sparkContext.longAccumulator("vector_fetch_skipped_log_resident")
+        val fetchKeyMismatchAcc: LongAccumulator = 
spark.sparkContext.longAccumulator("vector_fetch_key_mismatch")
+        val rowsMaterializedAcc: LongAccumulator = 
spark.sparkContext.longAccumulator("vector_rows_materialized")
+        val exactRows: RDD[InternalRow] = byFetchBatch.mapPartitions { batches 
=>
+          val startNs = System.nanoTime()
+          val rows = ArrayBuffer.empty[InternalRow]
+          var batchCount = 0
+          var resolvedSlices = 0
+          var missingSlices = 0
+          var candidateKeys = 0L
+          var baseFiles = 0
+          var logFiles = 0L
+          var totalSliceBytes = 0L
+          var staleCandidates = 0L
+          var fetchSkippedLogResident = 0L
+          var fetchKeyMismatch = 0L
+          var keyLookupRowsDecoded = 0L
+          var metrics = PositionalParquetFetcher.FetchMetrics()
+          val fetcher = new PositionalParquetFetcher(
+            storageConf.newInstance().unwrap(),
+            embeddingCol,
+            vectorSchema,
+            exactQueryVector,
+            ctx.metric,
+            outputSchema,
+            
mergedOptions.getOrElse("vector.exact_fetch.offset_index_missing_policy", 
"fallback").equalsIgnoreCase("fail"),
+            vectorOnlyProjection,
+            VectorIndexOptions.shouldVerifyFetchKeys(mergedOptions.asJava))
+          val keyLocator = new 
ParquetRecordKeyLocator(storageConf.newInstance().unwrap())
+          while (batches.hasNext) {
+            val (fgId, candidates) = batches.next()
+            batchCount += 1
+            val fileSliceOpt = bFileSliceMap.value.get(fgId)
+            if (fileSliceOpt.isEmpty) {
+              missingSlices += 1
+              throw new HoodieAnalysisException(
+                s"Vector exact search could not resolve file group '$fgId' for 
${candidates.size} rerank candidates. " +
+                  s"No record-level-index fallback is active in this path.")
+            } else {
+              resolvedSlices += 1
+              val fileSlice = fileSliceOpt.get
+              val logFileCount = fileSlice.getLogFiles.count()
+              val currentBaseInstantTime = fileSlice.getBaseInstantTime
+              val logResident = candidates.filter(candidate =>
+                isLogResidentCandidate(candidate, currentBaseInstantTime, 
logFileCount > 0))
+              if (logResident.nonEmpty) {
+                fetchSkippedLogResident += logResident.size
+                fetchSkippedLogResidentAcc.add(logResident.size)
+                LOG.warn(
+                  s"Vector exact fetch skipped ${logResident.size} 
log-resident candidate(s) in file group '$fgId'; " +
+                    "they remain a result shortfall and the retained candidate 
pool will refill where candidates remain")
+              }
+              val liveCandidates = candidates.filterNot(logResident.toSet)
+              staleCandidates += liveCandidates.count(candidate =>
+                candidate.getArbiterDecision == 
VectorIndexArbiter.Decision.STALE)
+              if (liveCandidates.nonEmpty) {
+                val positionalCandidates = liveCandidates.filter { candidate =>
+                  val location = candidate.getLocation
+                  location != null && location.getPosition >= 0 &&
+                    candidate.getArbiterDecision != 
VectorIndexArbiter.Decision.STALE &&
+                    (location.getInstantTime == null || 
location.getInstantTime == currentBaseInstantTime)
+                }
+                val keyCandidates = 
liveCandidates.filterNot(positionalCandidates.toSet)
+                val recordKeys = liveCandidates.map(_.getRecordKey).toSet
+                candidateKeys += recordKeys.size
+                if (fileSlice.getBaseFile.isEmpty) {
+                  throw new HoodieAnalysisException(
+                    s"Vector exact key fallback requires a base Parquet file 
for file group '$fgId'; " +
+                      "the remaining candidates are not classified as 
log-resident.")
+                }
+                baseFiles += 1
+                logFiles += logFileCount
+                totalSliceBytes += fileSlice.getTotalFileSize
+                val baseFilePath = fileSlice.getBaseFile.get.getPath
+                val locatedByKey = keyLocator.locate(baseFilePath, 
keyCandidates)
+                keyLookupRowsDecoded += locatedByKey.metrics.rowsDecoded
+                if (locatedByKey.metrics.located != keyCandidates.size) {
+                  throw new HoodieAnalysisException(
+                    s"Vector exact key fallback located 
${locatedByKey.metrics.located} of ${keyCandidates.size} " +
+                      s"candidate key(s) in the live base file for file group 
'$fgId'.")
+                }
+                val firstFetch = fetcher.fetch(baseFilePath, 
positionalCandidates ++ locatedByKey.candidates)
+                rows ++= firstFetch.rows
+                metrics = metrics.add(firstFetch.metrics)
+                rowsMaterializedAcc.add(firstFetch.metrics.rowsMaterialized)
+                if (firstFetch.retryByKey.nonEmpty) {
+                  fetchKeyMismatch += firstFetch.retryByKey.size
+                  fetchKeyMismatchAcc.add(firstFetch.retryByKey.size)
+                  val retries = keyLocator.locate(baseFilePath, 
firstFetch.retryByKey)
+                  keyLookupRowsDecoded += retries.metrics.rowsDecoded
+                  if (retries.metrics.located != firstFetch.retryByKey.size) {
+                    throw new HoodieAnalysisException(
+                      s"Vector exact fetch could not relocate 
${firstFetch.retryByKey.size - retries.metrics.located} " +
+                        s"key mismatch(es) in file group '$fgId'.")
+                  }
+                  val retryFetch = fetcher.fetch(baseFilePath, 
retries.candidates)
+                  if (retryFetch.retryByKey.nonEmpty) {
+                    throw new HoodieAnalysisException(
+                      s"Vector exact fetch could not self-heal 
${retryFetch.retryByKey.size} key mismatch(es) " +
+                        s"in file group '$fgId' after key-based relocation.")
+                  }
+                  rows ++= retryFetch.rows
+                  metrics = metrics.add(retryFetch.metrics)
+                  rowsMaterializedAcc.add(retryFetch.metrics.rowsMaterialized)
+                }
+              }
+            }
+          }
+          LOG.info(
+            s"[vector_search][stage][exact_read] 
rerankCandidates=$candidateKeys candidateFileCount=$resolvedSlices " +
+              s"fetchBatches=$batchCount resolvedSlices=$resolvedSlices 
missingSlices=$missingSlices " +
+              s"rowsDecoded=${metrics.rowsDecoded} 
rowsMaterialized=${metrics.rowsMaterialized} " +
+              s"keyLookupRowsDecoded=$keyLookupRowsDecoded 
fetchKeyMismatch=$fetchKeyMismatch " +
+              s"fetchSkippedLogResident=$fetchSkippedLogResident " +
+              s"rowGroupsTotal=${metrics.rowGroupsTotal} 
rowGroupsSelected=${metrics.rowGroupsSelected} " +
+              s"pagesInSelectedRowGroups=${metrics.pagesInSelectedRowGroups} 
pagesSelected=${metrics.pagesSelected} " +
+              s"offsetIndexHits=${metrics.offsetIndexHits} 
offsetIndexMissing=${metrics.offsetIndexMissing} " +
+              s"rangedGets=${metrics.rangedGets} 
pageBytesFetched=${metrics.pageBytesFetched} " +
+              s"physicalBytesRead=${metrics.physicalBytesRead} 
footerReads=${metrics.footerReads} footerCacheHits=${metrics.footerCacheHits} " 
+
+              s"fetchKeyMismatchMetric=${metrics.fetchKeyMismatch} 
staleCandidates=$staleCandidates " +
+              s"baseFiles=$baseFiles logFiles=$logFiles " +
+              s"sliceBytes=$totalSliceBytes footerMs=${metrics.footerMs} 
offsetIndexMs=${metrics.offsetIndexMs} " +
+              s"fetchWaitMs=${metrics.fetchWaitMs} 
decodeMs=${metrics.decodeMs} scoreMs=${metrics.scoreMs} 
elapsedMs=${elapsedMs(startNs)}")
+          rows.iterator
+        }
+        val logResidentRows: Seq[InternalRow] =
+          if (logResidentCandidates.isEmpty) {
+            Seq.empty
+          } else {
+            val dataSchema = new 
TableSchemaResolver(ctx.metaClient).getTableSchema(true)
+            val scorer = new VectorExactScorer(vectorSchema, exactQueryVector, 
ctx.metric)
+            val logFetcher = new LogResidentVectorFetcher(
+              storageConf, ctx.metaClient, dataSchema, ctx.latestInstantTime,
+              embeddingCol, outputSchema, scorer)
+            val fetched = logResidentCandidates
+              .groupBy(candidate =>
+                (Option(candidate.getLocation.getPartitionPath).getOrElse(""), 
candidate.getLocation.getFileId))
+              .flatMap { case ((partitionPath, fgId), candidates) =>
+                logFetcher.fetchSlice(partitionPath, fileSliceMap(fgId), 
candidates.map(_.getRecordKey).toSet)

Review Comment:
   **Fixed** `10f50b3319`. Merged (base+log) reads run in executor tasks over 
the broadcast slice map, not on the driver.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/analysis/VectorSearchAlgorithms.scala:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.hudi.analysis
+
+import org.apache.hudi.SparkAdapterSupport

Review Comment:
   **Fixed** `3cde5283ea`. Removed.



##########
hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/analysis/VectorSearchAlgorithms.scala:
##########
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.hudi.analysis
+
+import org.apache.hudi.SparkAdapterSupport
+import org.apache.hudi.client.common.HoodieSparkEngineContext
+import org.apache.hudi.common.config.HoodieMetadataConfig
+import org.apache.hudi.common.config.TypedProperties
+import org.apache.hudi.common.index.vector.{ScoredVectorPostingMatch, 
VectorDistanceMetric, VectorIndexArbiter, VectorIndexMdtSearchUtils, 
VectorIndexMetadataCache, VectorIndexOptions, VectorPostingMatch, 
VectorStalePolicy}
+import org.apache.hudi.common.model.{FileSlice, HoodieIndexDefinition, 
HoodieRecord}
+import org.apache.hudi.common.schema.HoodieSchema
+import org.apache.hudi.common.table.{HoodieTableMetaClient, 
TableSchemaResolver}
+import org.apache.hudi.common.table.timeline.{HoodieTimeline, 
InstantComparison}
+import 
org.apache.hudi.common.table.timeline.InstantComparison.compareTimestamps
+import org.apache.hudi.common.table.view.HoodieTableFileSystemView
+import org.apache.hudi.data.HoodieJavaRDD
+import org.apache.hudi.hadoop.fs.HadoopFSUtils
+import org.apache.hudi.metadata.{HoodieTableMetadata, HoodieTableMetadataUtil}
+
+import org.apache.spark.api.java.JavaSparkContext
+import org.apache.spark.rdd.RDD
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row, SparkSession}
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.parser.ParseException
+import 
org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction
+import 
org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction.{DistanceMetric,
 SearchAlgorithm}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.expressions.Window
+import org.apache.spark.sql.functions.{broadcast, col, 
monotonically_increasing_id, row_number}
+import org.apache.spark.sql.hudi.command.exception.HoodieAnalysisException
+import org.apache.spark.sql.types.{ArrayType, ByteType, DataType, DoubleType, 
FloatType, Metadata, StructField, StructType}
+import org.apache.spark.util.LongAccumulator
+import org.slf4j.LoggerFactory
+
+import scala.collection.JavaConverters._
+import scala.collection.mutable.ArrayBuffer
+import scala.util.{Failure, Success, Try}
+
+case class VectorSearchTable(df: DataFrame, basePath: Option[String])
+
+/**
+ * Extension point for vector search algorithms. Each implementation provides
+ * the Spark logical plan for single-query and batch-query KNN search.
+ *
+ * To add a new algorithm (e.g. RowMatrix, HNSW):
+ *  1. Create an object extending this trait
+ *  2. Add a value to [[SearchAlgorithm]]
+ *  3. Register the mapping in 
[[HoodieVectorSearchPlanBuilder.resolveAlgorithm]]
+ *
+ * Implementations can use the shared validation helpers on
+ * [[HoodieVectorSearchPlanBuilder]] (validateEmbeddingColumn, 
validateBatchDimensions, etc.)
+ * and the raw distance functions on [[VectorDistanceUtils]].
+ *
+ * The output schema contract:
+ *  - Single-query: all corpus columns (minus the embedding column) + 
`_hudi_distance: Double`
+ *  - Batch-query: all corpus columns (minus the embedding column) + clashing 
query columns
+ *    (prefixed with `_hudi_query_`) + `_hudi_distance: Double` + 
`_hudi_query_index: Long`
+ *  - Results are ordered by `_hudi_distance` ascending (lower = more similar)
+ *  - `_hudi_query_index` is an opaque grouping identifier (not a sequential 
index). Values may be
+ *    large non-contiguous numbers because they are generated by 
`monotonically_increasing_id()`.
+ */
+trait VectorSearchAlgorithm {
+
+  /** Human-readable name for error messages and logging. */
+  def name: String
+
+  /**
+   * Build a plan that finds the k nearest corpus rows to a single query 
vector.
+   *
+   * @param spark          active SparkSession
+   * @param corpusTable    resolved corpus table (may be Hudi, Parquet, or 
temp view)
+   * @param embeddingCol   name of the array-typed embedding column in corpusDf
+   * @param queryVector    the query vector, normalized to Array[Double]
+   * @param k              number of nearest neighbors to return
+   * @param metric         distance metric (COSINE, L2, DOT_PRODUCT)
+   * @return an analyzed LogicalPlan whose output matches the single-query 
schema contract
+   */
+  def buildSingleQueryPlan(
+      spark: SparkSession,
+      corpusTable: VectorSearchTable,
+      embeddingCol: String,
+      queryVector: Array[Double],
+      k: Int,
+      metric: DistanceMetric.Value,
+      runtimeOptions: Map[String, String] = Map.empty): LogicalPlan
+
+  /**
+   * Build a plan that finds the k nearest corpus rows for each row in the 
query table.
+   *
+   * @param spark              active SparkSession
+   * @param corpusTable        resolved corpus table
+   * @param corpusEmbeddingCol name of the embedding column in corpusDf
+   * @param queryDf            resolved query DataFrame
+   * @param queryEmbeddingCol  name of the embedding column in queryDf
+   * @param k                  number of nearest neighbors per query
+   * @param metric             distance metric (COSINE, L2, DOT_PRODUCT)
+   * @return an analyzed LogicalPlan whose output matches the batch-query 
schema contract
+   * @note Batch mode broadcasts the query table to all executors via a 
cross-join.
+   *       This is designed for small-to-medium query sets (tens to low 
hundreds of rows).
+   *       For large query tables, memory pressure on executors may occur.
+   */
+  def buildBatchQueryPlan(
+      spark: SparkSession,
+      corpusTable: VectorSearchTable,
+      corpusEmbeddingCol: String,
+      queryDf: DataFrame,
+      queryEmbeddingCol: String,
+      k: Int,
+      metric: DistanceMetric.Value,
+      runtimeOptions: Map[String, String] = Map.empty): LogicalPlan
+}
+
+/**
+ * Resolves [[SearchAlgorithm]] values to [[VectorSearchAlgorithm]] 
implementations
+ * and provides shared validation helpers used across algorithms.
+ */
+object HoodieVectorSearchPlanBuilder {
+
+  private[analysis] val LOG = LoggerFactory.getLogger(getClass)
+
+  val DISTANCE_COL = "_hudi_distance"
+  val FILE_GROUP_ID_COL = "_hudi_file_group_id"
+  val VECTOR_ONLY_PROJECTION_OPT = "vector.exact_fetch.vector_only_projection"
+  val VECTOR_ONLY_PROJECTION_SPARK_CONF = 
"spark.hudi.vector.exact_fetch.vector_only_projection"
+  private[analysis] val QUERY_ID_COL = "_hudi_query_index"
+  private[analysis] val QUERY_EMB_ALIAS = "_hudi_query_emb"
+  private[analysis] val RANK_COL = "_hudi_rank"
+  private[analysis] val QUERY_COL_PREFIX = "_hudi_query_"
+
+  private[analysis] def elapsedMs(startNs: Long): Long = (System.nanoTime() - 
startNs) / 1000000L
+
+  private[analysis] def summarizeInts(values: Seq[Int], limit: Int = 16): 
String = {
+    val preview = values.take(limit).mkString("[", ", ", "]")
+    if (values.length > limit) s"$preview...(${values.length} total)" else 
preview
+  }
+
+  private[analysis] def summarizeShardCounts(shardCounts: collection.Map[Int, 
Int], limit: Int = 16): String = {
+    val preview = shardCounts.toSeq.sortBy(_._1).take(limit).map { case 
(clusterId, count) =>
+      s"$clusterId->$count"
+    }.mkString("[", ", ", "]")
+    if (shardCounts.size > limit) s"$preview...(${shardCounts.size} total)" 
else preview
+  }
+
+  private[analysis] def logRddLineage(label: String, rdd: RDD[_]): Unit = {
+    Try(rdd.toDebugString) match {
+      case Success(debug) =>
+        LOG.info(s"[vector_search][$label] lineage:\n$debug")
+      case Failure(error) =>
+        LOG.warn(s"[vector_search][$label] unable to fetch RDD lineage", error)
+    }
+  }
+
+  /** Resolve a [[SearchAlgorithm]] enum value to its implementation. */
+  def resolveAlgorithm(algorithm: SearchAlgorithm.Value): 
VectorSearchAlgorithm = algorithm match {
+    case SearchAlgorithm.BRUTE_FORCE => BruteForceSearchAlgorithm
+    case SearchAlgorithm.IVF_RABITQ_MDT => IvfRaBitQMdtSearchAlgorithm
+    case other => throw new HoodieAnalysisException(
+      s"Unsupported search algorithm: $other")
+  }
+
+  private[analysis] def validateEmbeddingColumn(df: DataFrame, colName: 
String): Unit = {
+    val fieldOpt = df.schema.fields.find(_.name.equalsIgnoreCase(colName))
+    val field = fieldOpt.getOrElse(
+      throw new HoodieAnalysisException(
+        s"Embedding column '$colName' not found in table schema. " +
+          s"Available columns: ${df.schema.fieldNames.mkString(", ")}"))
+    field.dataType match {
+      case ArrayType(FloatType, _) | ArrayType(DoubleType, _) | 
ArrayType(ByteType, _) => // valid
+      case other =>
+        throw new HoodieAnalysisException(
+          s"Embedding column '$colName' has type $other, " +
+            "expected array<float>, array<double>, or array<byte>")
+    }
+  }
+
+  /**
+   * Validates that the query vector dimension matches the corpus embedding 
dimension
+   * when the corpus column has VECTOR(dim) metadata.
+   */
+  private[analysis] def validateQueryVectorDimension(
+      df: DataFrame, embeddingCol: String, queryDim: Int): Unit = {
+    extractVectorSchema(df, embeddingCol).map(_.getDimension).foreach { 
corpusDim =>
+      if (corpusDim != queryDim) {
+        throw new HoodieAnalysisException(
+          s"Query vector dimension ($queryDim) does not match " +
+            s"corpus embedding dimension ($corpusDim) for column 
'$embeddingCol'")
+      }
+    }
+  }
+
+  /**
+   * Validates that corpus and query embedding columns have the same element 
type.
+   *
+   * This is a deliberate design choice: we require strict type matching 
rather than
+   * silently upcasting (e.g. float to double). While some vector search 
systems
+   * auto-convert, strict matching avoids subtle precision differences and 
makes
+   * type mismatches between pipelines explicit. This can be relaxed to support
+   * automatic widening (byte -> float -> double) in a future iteration if 
needed.
+   */
+  private[analysis] def validateElementTypeCompatibility(
+      corpusDf: DataFrame, corpusCol: String,
+      queryDf: DataFrame, queryCol: String): Unit = {
+    val corpusElemType = getElementType(corpusDf, corpusCol)
+    val queryElemType = getElementType(queryDf, queryCol)
+    if (corpusElemType != queryElemType) {
+      throw new HoodieAnalysisException(
+        s"Corpus embedding column '$corpusCol' has element type 
$corpusElemType " +
+          s"but query embedding column '$queryCol' has element type 
$queryElemType. " +
+          "Both must use the same element type (e.g. array<float>).")
+    }
+  }
+
+  /**
+   * Validates that corpus and query embedding dimensions match when both have
+   * VECTOR(dim) metadata.
+   */
+  private[analysis] def validateBatchDimensions(
+      corpusDf: DataFrame, corpusCol: String,
+      queryDf: DataFrame, queryCol: String): Unit = {
+    (extractVectorSchema(corpusDf, corpusCol).map(_.getDimension), 
extractVectorSchema(queryDf, queryCol).map(_.getDimension)) match {
+      case (Some(corpusDim), Some(queryDim)) if corpusDim != queryDim =>
+        throw new HoodieAnalysisException(
+          s"Corpus embedding dimension ($corpusDim) does not match " +
+            s"query embedding dimension ($queryDim)")
+      case _ => // dimensions match or metadata not available
+    }
+  }
+
+  private[analysis] def getElementType(df: DataFrame, colName: String): 
DataType = {
+    val field = 
df.schema.fields.find(_.name.equalsIgnoreCase(colName)).getOrElse(
+      throw new HoodieAnalysisException(
+        s"Embedding column '$colName' not found in table schema. " +
+          s"Available columns: ${df.schema.fieldNames.mkString(", ")}"))
+    field.dataType match {
+      case ArrayType(elemType, _) => elemType
+      case other =>
+        throw new HoodieAnalysisException(
+          s"Embedding column '$colName' has type $other, expected an array 
type")
+    }
+  }
+
+  /** Extracts VECTOR schema from column metadata, if present. */
+  private[analysis] def extractVectorSchema(df: DataFrame, colName: String): 
Option[HoodieSchema.Vector] = {
+    df.schema.fields.find(_.name.equalsIgnoreCase(colName)).flatMap { field =>
+      val meta = field.metadata
+      if (meta.contains(HoodieSchema.TYPE_METADATA_FIELD)) {
+        val typeDesc = meta.getString(HoodieSchema.TYPE_METADATA_FIELD)
+        Try(HoodieSchema.parseTypeDescriptor(typeDesc)) match {
+          case Success(v: HoodieSchema.Vector) => Some(v)
+          case Success(_) => throw new HoodieAnalysisException(
+            s"Column '$colName' has type '$typeDesc' which is not a VECTOR 
type. " +
+              "Only VECTOR columns are supported for vector search.")
+          case Failure(e) => throw new HoodieAnalysisException(
+            s"Column '$colName' has malformed type metadata '$typeDesc': 
${e.getMessage}")
+        }
+      } else None
+    }
+  }
+
+  private[analysis] def quoteIdentifier(name: String): String = 
s"`${name.replace("`", "``")}`"
+}
+
+/**
+ * Brute-force KNN vector search: computes distance between every corpus row 
and
+ * every query vector, then selects the top-K closest.
+ *
+ * <p>Complexity: O(|corpus| * |queries| * dimensions) — linear scan with no 
index.
+ *
+ * <p><b>Single-query mode:</b> applies a distance UDF per corpus row, then
+ * {@code orderBy + limit(k)} (Spark optimizes this to a partial sort via 
TakeOrderedAndProject).
+ *
+ * <p><b>Batch-query mode:</b> broadcast cross-joins the (small) query table 
with
+ * the corpus, computes pairwise distances, then uses a window function to rank
+ * and select top-K per query. The cross-join produces O(|corpus| * |queries|)
+ * intermediate rows, so this is suitable for small-to-medium query sets
+ * (tens to low hundreds of queries) against moderate corpora.
+ */
+object BruteForceSearchAlgorithm extends VectorSearchAlgorithm {
+
+  import HoodieVectorSearchPlanBuilder._
+
+  override val name: String = "brute_force"
+
+  private def applyFilter(df: DataFrame, filterExpr: String): DataFrame = {
+    try {
+      df.filter(filterExpr)
+    } catch {
+      case e @ (_: ParseException | _: AnalysisException) =>
+        throw new HoodieAnalysisException(
+          s"Invalid pre-filter expression '$filterExpr': ${e.getMessage}")
+    }
+  }
+
+  private def filterOption(runtimeOptions: Map[String, String]): 
Option[String] =
+    
runtimeOptions.get(HoodieVectorSearchTableValuedFunction.BRUTE_FORCE_FILTER_OPT)
+
+  private def maxDistanceOption(runtimeOptions: Map[String, String]): 
Option[Double] =
+    
runtimeOptions.get(HoodieVectorSearchTableValuedFunction.BRUTE_FORCE_MAX_DISTANCE_OPT).map(_.toDouble)
+
+  override def buildSingleQueryPlan(
+      spark: SparkSession,
+      corpusTable: VectorSearchTable,
+      embeddingCol: String,
+      queryVector: Array[Double],
+      k: Int,
+      metric: DistanceMetric.Value,
+      runtimeOptions: Map[String, String] = Map.empty): LogicalPlan = {
+    val corpusDf = corpusTable.df
+    validateEmbeddingColumn(corpusDf, embeddingCol)
+    validateQueryVectorDimension(corpusDf, embeddingCol, queryVector.length)
+
+    val elemType = getElementType(corpusDf, embeddingCol)
+    var filteredDf = corpusDf.filter(col(embeddingCol).isNotNull)

Review Comment:
   **Fixed** `3cde5283ea`. Replaced with two small helpers.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to