// Copyright (c) 2023-2026 ParadeDB, Inc.
//
// This file is part of ParadeDB - Postgres for Search and Analytics
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
//! DataFusion `ExecutionPlan` implementations for scanning `pg_search` indexes.
//!
//! See the [JoinScan README](../../postgres/customscan/joinscan/README.md) for
//! how `PgSearchScanPlan` integrates with the JoinScan physical plan and
//! dynamic filters.
//!
//! This module provides the `PgSearchScanPlan`, which scans `pg_search` index segments as a
//! single lazily-claimed partition: segments are claimed dynamically from `ParallelScanState`
//! in parallel execution, or chained end-to-end when serial.
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::task::{Context, Poll};
use arrow_array::RecordBatch;
use arrow_schema::{DataType, SchemaRef, SortOptions};
use datafusion::common::stats::{ColumnStatistics, Precision};
use datafusion::common::{DataFusionError, Result, Statistics};
use datafusion::execution::{RecordBatchStream, SendableRecordBatchStream, TaskContext};
use datafusion::physical_expr::{
DynamicFilterTracker, DynamicFilterTracking, EquivalenceProperties, LexOrdering, PhysicalExpr,
PhysicalSortExpr,
};
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion::physical_plan::expressions::{Column, DynamicFilterPhysicalExpr};
use datafusion::physical_plan::filter_pushdown::{
ChildPushdownResult, FilterPushdownPhase, FilterPushdownPropagation, PushedDown,
};
use datafusion::physical_plan::metrics::{
BaselineMetrics, Count, ExecutionPlanMetricsSet, MetricBuilder, MetricsSet, RecordOutput,
};
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
};
use datafusion_distributed::{
DesiredTaskCountEvent, DesiredTaskCountEventResponse, ScaleUpLeafNodeEvent,
ScaleUpLeafNodeEventResponse,
};
use datafusion_proto::physical_plan::{
DefaultPhysicalExtensionCodec, DefaultPhysicalProtoConverter, PhysicalPlanDecodeContext,
PhysicalProtoConverterExtension,
};
use futures::Stream;
use pgrx::pg_sys;
use tantivy::Score;
use crate::api::OrderByInfo;
use crate::index::fast_fields_helper::FFHelper;
use crate::index::fast_fields_helper::{FieldDelivery, WhichFastField};
use crate::index::mvcc::MvccSatisfies;
use crate::index::reader::index::{SearchIndexReader, SegmentPruningEstimate};
use crate::index::stats::{PartitionSegments, segments_for_partition};
use crate::postgres::ParallelScanState;
use crate::postgres::customscan::explain::ExplainFormat;
use crate::postgres::customscan::mpp::interrupt::{cancel_pending, interrupted};
use crate::postgres::customscan::parallel::segment_view;
use crate::postgres::heap::VisibilityChecker;
use crate::postgres::options::{SortByDirection, SortByField};
use crate::postgres::rel::PgSearchRelation;
use crate::postgres::utils::ExprContextGuard;
use crate::query::SearchQueryInput;
use crate::scan::Scanner;
use crate::scan::deferred_encode::is_deferred_field;
use crate::scan::deferred_lookup::decoded_data_type;
use crate::scan::filter_passthrough_exec::FilterPassthroughExec;
use crate::scan::late_materialization::DeferredField;
use crate::scan::lazy_sort::build_lazy_sort_stream;
pub use crate::scan::lazy_sort::{
LazyParallelMode, LazySortConfig, LazySortTelemetry, LazySortTelemetryState, TopKSelectivity,
};
use crate::scan::pre_filter::{PreFilter, collect_filters, try_dynamic_filter_pushdown};
use crate::scan::range_partitioning::{RangePartitioning, RangeSplitPoints};
/// A wrapper that implements Send + Sync unconditionally.
/// UNSAFE: Only use this when you guarantee single-threaded access or manual synchronization.
/// This is safe in pg_search because Postgres extensions run single-threaded.
#[derive(Clone)]
pub(crate) struct UnsafeSendSync(pub T);
unsafe impl Send for UnsafeSendSync {}
unsafe impl Sync for UnsafeSendSync {}
/// Ingredients needed to construct a Scanner for deferred search.
#[derive(Clone)]
pub struct ScannerConfig {
pub which_fast_fields: Vec,
pub heap_relid: u32,
pub batch_size_hint: Option,
/// `need_scores` the index reader was opened with. Carried so a leader-dispatched worker
/// re-opens its reader with the same scoring behavior (the reader itself can't travel).
pub score_needed: bool,
/// Mode of the scan (e.g. Standard vs Tagged with optional lifted local query).
pub scan_mode: crate::scan::ScanMode,
}
/// State for a scan partition.
///
/// Uses `Arc` so the same FFHelper can be shared across multiple partitions.
///
/// Lazily claims segments from `ParallelScanState`. `source_idx = Some(i)` claims from source
/// `i`'s pool for MPP sources; `None` uses the single-counter `checkout_segment_for_source(0)`
/// for basescan and non-MPP parallel joins.
#[derive(Clone)]
pub struct ScanState {
pub source_idx: Option,
pub planner_estimated_rows: u64,
pub scanner_config: ScannerConfig,
pub ffhelper: Arc,
pub visibility: Box,
pub reader: SearchIndexReader,
}
/// Execution state for a single `PgSearchScanPlan`.
///
/// Under distributed execution, a task-specialized variant exposes one local partition.
/// Its `assigned_partition` maps that local partition back to the global partition whose
/// state and range bounds it must consume exactly once.
#[derive(Default, Clone)]
pub enum ExecutionState {
/// In Shared mode, we optionally load-balance via ParallelScanState.
/// The state is consumed at most once by this plan or one of its task variants.
Shared {
parallel_state: Option>,
scan_state: Box>,
},
/// In RangePartitioned mode, we static-partition using RangePartitioning.
/// A task variant maps its sole local partition to one range before consuming the state.
RangePartitioned {
range_boundaries: RangePartitioning,
scan_state: Box>,
},
/// The state has been consumed by a call to execute().
Consumed,
/// Uninitialized placeholder state.
#[default]
Uninitialized,
}
/// A DataFusion `ExecutionPlan` for scanning `pg_search` index segments.
///
/// Before task specialization, this plan's `output_partitioning` declares the planner-selected
/// global partition count. Each specialized variant then exposes one local partition while
/// retaining the global partition count and its `assigned_partition`, so local `execute(0)`
/// consumes exactly the assigned slice of the workload.
pub struct PgSearchScanPlan {
/// State consumed exactly once by this plan or one of its task-specialized clones.
///
/// We use a Mutex to allow taking ownership of the scanner during `execute()`.
/// We wrap the state in `UnsafeSendSync` to satisfy `ExecutionPlan`'s `Send` + `Sync`
/// requirements. This is safe because we are running in a single-threaded
/// environment (Postgres), which also means that the duration for which we
/// hold this Mutex does not impact performance.
state: Mutex,
/// Estimated row count, computed once at construction.
/// Stored separately so `partition_statistics` is deterministic, even after
/// the state has been consumed.
planner_estimated_rows: u64,
/// Candidate and pruned segment counts from this plan's static execution-time proof.
/// Seeded from the reader when already cached and computed on demand for EXPLAIN.
/// The reader still retains the full manifest/DSM view; this is an estimate and never
/// a segment-identity authority.
segment_pruning: OnceLock,
/// Number of partitions in the scan before task specialization. A specialized variant's
/// `output_partitioning` is always one, so this count is serialized separately and used to
/// rebuild the original range boundaries when the variant is decoded on its worker.
global_partition_count: usize,
properties: Arc,
resolved_query: SearchQueryInput,
/// Dynamic filters pushed down from parent operators (e.g. Top K threshold
/// from SortExec, join-key bounds from HashJoinExec). Each batch produced
/// by the scanner is filtered against all of these expressions so that rows
/// which cannot contribute to the final result are pruned early.
dynamic_filters: Vec>,
/// Metrics for EXPLAIN ANALYZE.
metrics: ExecutionPlanMetricsSet,
deferred_fields: Vec,
/// String columns the placement rule handed back to the scan to decode, kept for EXPLAIN
/// so the decision is visible where it was made.
eager_fields: Vec,
/// Shared FFHelper for deferred lookup and deferred visibility.
///
/// A scan may participate in late materialization, deferred visibility, or both.
/// Callers decide whether they should use it by checking the deferred metadata,
/// and cloning the Arc is cheap.
ffhelper: Option>,
pub indexrelid: u32,
pub table_alias: String,
/// The JoinScan source identity when visibility is deferred.
deferred_ctid_plan_position: Option,
/// Sort order preserved across `with_filter_pushdown` rebuilds so the
/// rebuilt plan keeps its equivalence properties.
sort_order: Option,
range_split_points: Option,
/// Global partition selected for a task-specialized variant. When present, this plan
/// exposes one local partition and maps `execute(0)` back to this global partition.
pub(crate) assigned_partition: Option,
pub(crate) partition_segments: Option,
pub(crate) scan_mode: crate::scan::ScanMode,
/// Optional iterative Top-K windowing configuration.
lazy_sort: Option,
/// Fallback ExprContext guard created during dispatch decode when heap filters are present
/// but no external ExprContext was supplied through the codec. Kept alive on the plan so
/// the underlying ExprContext remains valid across execution.
_expr_context_guard: Option>,
}
impl Clone for PgSearchScanPlan {
fn clone(&self) -> Self {
let state_guard = self.state.lock().unwrap();
let new_state = state_guard.clone();
Self {
state: Mutex::new(new_state),
planner_estimated_rows: self.planner_estimated_rows,
segment_pruning: self.segment_pruning.clone(),
global_partition_count: self.global_partition_count,
properties: Arc::clone(&self.properties),
resolved_query: self.resolved_query.clone(),
dynamic_filters: self.dynamic_filters.clone(),
metrics: self.metrics.clone(),
deferred_fields: self.deferred_fields.clone(),
eager_fields: self.eager_fields.clone(),
ffhelper: self.ffhelper.clone(),
indexrelid: self.indexrelid,
table_alias: self.table_alias.clone(),
deferred_ctid_plan_position: self.deferred_ctid_plan_position,
sort_order: self.sort_order.clone(),
range_split_points: self.range_split_points.clone(),
assigned_partition: self.assigned_partition,
partition_segments: self.partition_segments.clone(),
scan_mode: self.scan_mode.clone(),
lazy_sort: self.lazy_sort.clone(),
_expr_context_guard: self._expr_context_guard.clone(),
}
}
}
impl std::fmt::Debug for PgSearchScanPlan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PgSearchScanPlan")
.field("properties", &self.properties)
.finish()
}
}
impl PgSearchScanPlan {
/// Creates a new PgSearchScanPlan with pre-opened segments.
///
/// # Arguments
///
/// * `state` - The pre-opened scan state (or None for tests)
/// * `schema` - Arrow schema for the output
/// * `resolved_query` - The filter-combined, param-solved query the readers were opened
/// with. Used for EXPLAIN and shipped on dispatch.
/// * `sort_order` - Optional sort order declaration for equivalence properties
/// * `partition_count` - Planner-selected number of global partitions. Non-range scans cap
/// this at their segment count; range scans may expose more partitions than segments.
#[allow(clippy::too_many_arguments)]
pub fn new(
state: Option,
schema: SchemaRef,
resolved_query: SearchQueryInput,
sort_order: Option<&SortByField>,
deferred_fields: Vec,
ffhelper: Option>,
indexrelid: u32,
deferred_ctid_plan_position: Option,
partition_count: usize,
parallel_state: Option<*mut crate::postgres::ParallelScanState>,
range_split_points: Option,
) -> Self {
let needs_ffhelper = !deferred_fields.is_empty() || deferred_ctid_plan_position.is_some();
if needs_ffhelper && ffhelper.is_none() {
panic!("deferred lookup/visibility requires an FFHelper, but ffhelper is None");
}
// The split points seat only so many partitions; a task past them would be empty.
let partition_count = range_split_points
.as_ref()
.map_or(partition_count, |points| {
points.partitions_for(partition_count)
});
// Output partitioning tells datafusion-distributed how many tasks this leaf can naturally split into.
// If state is None, execute() will return an EmptyStream for this single partition.
let range_boundaries = range_split_points
.as_ref()
.map(|s| s.build(partition_count));
let partitioning =
declared_partitioning(&schema, partition_count, range_split_points.as_ref());
let eq_properties = build_equivalence_properties(schema, sort_order, None);
let properties = Arc::new(PlanProperties::new(
eq_properties,
partitioning,
EmissionType::Incremental,
Boundedness::Bounded,
));
let planner_estimated_rows = state
.as_ref()
.map(|s| s.planner_estimated_rows)
.unwrap_or(0);
let segment_pruning = state
.as_ref()
.and_then(|s| s.reader.cached_segment_pruning_estimate());
if range_split_points.is_none()
&& let Some(pruning) = segment_pruning
{
// A partition count exceeding the segment count indicates a bug in
// pg_search_scan_desired_task_count, which should cap the tasks
// to the segment count when range partitioning is off.
assert!(
partition_count <= pruning.candidate_segments.max(1),
"partition_count {} exceeds segment_count {}",
partition_count,
pruning.candidate_segments
);
}
let scan_mode = state
.as_ref()
.map(|s| s.scanner_config.scan_mode.clone())
.unwrap_or_else(|| crate::scan::ScanMode::standard(resolved_query.clone()));
let exec_state = match state {
Some(s) => {
if let Some(boundaries) = range_boundaries {
ExecutionState::RangePartitioned {
range_boundaries: boundaries,
scan_state: Box::new(UnsafeSendSync(s)),
}
} else {
ExecutionState::Shared {
parallel_state: parallel_state.map(UnsafeSendSync),
scan_state: Box::new(UnsafeSendSync(s)),
}
}
}
None => ExecutionState::Uninitialized,
};
Self {
state: Mutex::new(exec_state),
planner_estimated_rows,
segment_pruning: segment_pruning.map(OnceLock::from).unwrap_or_default(),
global_partition_count: partition_count,
properties,
resolved_query,
dynamic_filters: Vec::new(),
metrics: ExecutionPlanMetricsSet::new(),
deferred_fields,
eager_fields: Vec::new(),
ffhelper,
indexrelid,
table_alias: String::new(),
deferred_ctid_plan_position,
sort_order: sort_order.cloned(),
range_split_points,
assigned_partition: None,
partition_segments: None,
scan_mode,
lazy_sort: None,
_expr_context_guard: None,
}
}
pub fn with_table_alias(mut self, table_alias: impl Into) -> Self {
self.table_alias = table_alias.into();
self
}
/// Configures this scan to execute iterative, expanding-window Top-K pulls via
/// `SearchIndexReader::search_top_k_in_segments` (or range-filtered variants when
/// range-partitioned) instead of streaming segment-by-segment.
pub fn with_lazy_sort(mut self, lazy_sort: LazySortConfig) -> Self {
let schema = self.properties.eq_properties.schema().clone();
if self.range_split_points.is_none() {
self.global_partition_count = 1;
self.assigned_partition = None;
self.partition_segments = None;
if lazy_sort.parallel_mode == LazyParallelMode::Unpartitioned {
let mut state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let ExecutionState::Shared { parallel_state, .. } = &mut *state_guard {
*parallel_state = None;
}
}
}
self.lazy_sort = Some(lazy_sort);
self.rebuild_properties_with_schema(schema);
self
}
/// Collapses a range-partitioned or multi-partition scan to a single `Shared` partition
/// (`UnknownPartitioning(1)`). Used when a rank join cannot be co-partitioned in a single
/// stage and therefore falls back to `PartitionMode::CollectLeft`
/// (TODO: ).
pub(crate) fn into_single_shared_partition(mut self) -> Self {
self.global_partition_count = 1;
self.range_split_points = None;
self.assigned_partition = None;
self.partition_segments = None;
{
let mut state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let new_state =
match std::mem::replace(&mut *state_guard, ExecutionState::Uninitialized) {
ExecutionState::RangePartitioned { scan_state, .. } => ExecutionState::Shared {
parallel_state: None,
scan_state,
},
other => other,
};
*state_guard = new_state;
}
let schema = self.properties.eq_properties.schema().clone();
self.rebuild_properties_with_schema(schema);
self
}
pub fn lazy_sort(&self) -> Option<&LazySortConfig> {
self.lazy_sort.as_ref()
}
/// Returns a new copy of this plan resized to support exactly `target_partitions`.
///
/// This allows a `TaskEstimator` or distributed planner to override the natural
/// partition count of this plan when limited cluster resources prevent executing
/// the original quantity.
///
/// - For `Shared` mode, simply modifies the exposed metadata.
/// - For `RangePartitioned` mode, it asks the internal `range_split_points` to
/// down-sample the partitioning bounds so the new partition count has roughly
/// uniformly distributed boundaries. The count never exceeds what the points seat.
pub(crate) fn repartition(&self, target_partitions: usize) -> Result> {
if self.assigned_partition.is_some() {
return Err(DataFusionError::Internal(
"Cannot repartition a task-specialized PgSearchScanPlan".into(),
));
}
let target_partitions = self
.range_split_points
.as_ref()
.map_or(target_partitions, |points| {
points.partitions_for(target_partitions)
});
let new_state = {
let state_guard = self.state.lock().unwrap();
match &*state_guard {
ExecutionState::Shared {
parallel_state,
scan_state,
} => ExecutionState::Shared {
parallel_state: parallel_state.clone(),
scan_state: scan_state.clone(),
},
ExecutionState::RangePartitioned { scan_state, .. } => {
ExecutionState::RangePartitioned {
range_boundaries: self
.range_split_points
.as_ref()
.unwrap()
.build(target_partitions),
scan_state: scan_state.clone(),
}
}
ExecutionState::Uninitialized => ExecutionState::Uninitialized,
ExecutionState::Consumed => {
return Err(DataFusionError::Internal(
"Cannot repartition a consumed PgSearchScanPlan".to_string(),
));
}
}
};
let partitioning = declared_partitioning(
self.properties.eq_properties.schema(),
target_partitions,
self.range_split_points.as_ref(),
);
let new_properties = Arc::new(
PlanProperties::clone(self.properties.as_ref()).with_partitioning(partitioning),
);
Ok(self.with_overrides(
new_state,
new_properties,
self.dynamic_filters.clone(),
target_partitions,
))
}
fn with_overrides(
&self,
state: ExecutionState,
properties: Arc,
dynamic_filters: Vec>,
global_partition_count: usize,
) -> Arc {
Arc::new(Self {
state: Mutex::new(state),
planner_estimated_rows: self.planner_estimated_rows,
segment_pruning: self.segment_pruning.clone(),
global_partition_count,
properties,
resolved_query: self.resolved_query.clone(),
dynamic_filters,
metrics: self.metrics.clone(),
deferred_fields: self.deferred_fields.clone(),
eager_fields: self.eager_fields.clone(),
ffhelper: self.ffhelper.clone(),
indexrelid: self.indexrelid,
table_alias: self.table_alias.clone(),
deferred_ctid_plan_position: self.deferred_ctid_plan_position,
sort_order: self.sort_order.clone(),
range_split_points: self.range_split_points.clone(),
assigned_partition: self.assigned_partition,
partition_segments: self.partition_segments.clone(),
scan_mode: self.scan_mode.clone(),
lazy_sort: self.lazy_sort.clone(),
_expr_context_guard: self._expr_context_guard.clone(),
})
}
/// Returns a variant of this plan configured to execute assigned partition `assigned`.
///
/// The variant declares `Partitioning::UnknownPartitioning(1)` so DataFusion treats
/// it as a single-partition plan, while `assigned_partition` records which partition's
/// workload (range bounds or parallel state assignment) this variant executes.
pub(crate) fn with_assigned_partition(&self, assigned: usize) -> Arc {
self.assign_partition(assigned, None)
.expect("assignment without a received classification cannot be rejected")
}
/// Like [`Self::with_assigned_partition`], but reuses a received classification when it
/// names exactly this reader's segment view; see [`ReceivedClassification`] for what a
/// mismatch means.
pub(crate) fn assign_partition(
&self,
assigned: usize,
classified: Option,
) -> Result> {
assert!(
self.assigned_partition.is_none(),
"PgSearchScanPlan is already task-specialized"
);
assert!(
assigned < self.global_partition_count,
"assigned partition {assigned} is outside global partition count {}",
self.global_partition_count
);
let mut variant = self.clone();
variant.assigned_partition = Some(assigned);
let new_properties = Arc::new(
PlanProperties::clone(variant.properties.as_ref())
.with_partitioning(Partitioning::UnknownPartitioning(1)),
);
variant.properties = new_properties;
if let Some(ref range_split_points) = self.range_split_points {
let boundaries = range_split_points.build(self.global_partition_count);
let state = self.state.lock().unwrap();
if let ExecutionState::RangePartitioned { scan_state, .. } = &*state {
let reader = &scan_state.0.reader;
let partition_segments = match classified {
Some(
ReceivedClassification::SharedView(segments)
| ReceivedClassification::Snapshot(segments),
) if segments.covers_view(reader) => segments,
Some(ReceivedClassification::SharedView(_)) => {
return Err(DataFusionError::Internal(
"PgSearchScan dispatch: partition classification does not match \
the worker's segment view"
.into(),
));
}
_ => segments_for_partition(reader, &boundaries, assigned),
};
variant.partition_segments = Some(partition_segments);
}
}
Ok(Arc::new(variant))
}
/// Late-bind the shared `ParallelScanState` into this scan's execution state (#5667).
///
/// Under the plan-first MPP launch the leader builds its plan before the DSM exists, so
/// `Shared` scans start with `parallel_state: None`. Once the DSM is created and populated,
/// the launch stamps the leader's pointer in here — before the first `execute()`, which is
/// the only reader of the field. `RangePartitioned` and `Uninitialized` scans never consult
/// the pointer, so they are left untouched.
pub(crate) fn set_parallel_state(&self, ps: *mut ParallelScanState) {
if self
.lazy_sort
.as_ref()
.is_some_and(|ls| ls.parallel_mode == LazyParallelMode::Unpartitioned)
{
return;
}
let mut state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let ExecutionState::Shared { parallel_state, .. } = &mut *state_guard {
*parallel_state = Some(UnsafeSendSync(ps));
}
}
pub fn has_deferred_fields(&self) -> bool {
!self.deferred_fields.is_empty()
}
/// The `ParallelScanState` pool this scan claims segments from; `None` for a serial scan.
/// Only meaningful before execution: a consumed or never-initialized scan has no pool to
/// report, and asking is a caller bug.
pub(crate) fn source_idx(&self) -> Option {
let state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match &*state_guard {
ExecutionState::Shared { scan_state, .. }
| ExecutionState::RangePartitioned { scan_state, .. } => scan_state.0.source_idx,
ExecutionState::Consumed | ExecutionState::Uninitialized => {
crate::postgres::customscan::mpp::fail_loud(format!(
"PgSearchScan source_idx: scan {} has no execution state to read a pool from",
self.table_alias
))
}
}
}
/// The planner's row estimate for this scan, whole-plan and never divided among the
/// partitions the way `partition_statistics` divides it.
pub fn planner_estimated_rows(&self) -> u64 {
self.planner_estimated_rows
}
fn segment_pruning(&self) -> SegmentPruningEstimate {
*self.segment_pruning.get_or_init(|| {
let state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match &*state_guard {
ExecutionState::Shared { scan_state, .. }
| ExecutionState::RangePartitioned { scan_state, .. } => {
scan_state.0.reader.segment_pruning_estimate()
}
ExecutionState::Consumed | ExecutionState::Uninitialized => {
SegmentPruningEstimate::default()
}
}
})
}
/// Estimated fraction `[0.0, 1.0]` of index documents matched by this scan
/// (`planner_estimated_rows / total_docs`).
pub fn estimated_selectivity(&self) -> TopKSelectivity {
let total_docs = {
let state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match &*state_guard {
ExecutionState::Shared { scan_state, .. }
| ExecutionState::RangePartitioned { scan_state, .. } => {
scan_state.0.reader.total_docs()
}
ExecutionState::Consumed | ExecutionState::Uninitialized => {
self.planner_estimated_rows
}
}
};
if total_docs == 0 {
TopKSelectivity::ALL
} else {
TopKSelectivity(
(self.planner_estimated_rows as f64 / total_docs as f64).clamp(0.0, 1.0),
)
}
}
/// For `ScanMode::Tagged`, estimates the fraction `[0.0, 1.0]` of documents in this scan
/// matching at least one of its `local_queries` (`1 - prod_i (1 - s_i)`).
/// Returns `None` when the scan is not in `ScanMode::Tagged`.
pub fn estimated_tagged_selectivity(&self) -> Option {
let crate::scan::ScanMode::Tagged { local_queries, .. } = &self.scan_mode else {
return None;
};
if local_queries.is_empty() {
return Some(TopKSelectivity(0.0));
}
let state_guard = self
.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
match &*state_guard {
ExecutionState::Shared { scan_state, .. }
| ExecutionState::RangePartitioned { scan_state, .. } => {
let reader = &scan_state.0.reader;
let combined = local_queries
.iter()
.map(|tq| TopKSelectivity(reader.estimate_query_selectivity(&tq.query)))
.fold(TopKSelectivity(0.0), TopKSelectivity::or);
Some(combined)
}
ExecutionState::Consumed | ExecutionState::Uninitialized => {
drop(state_guard);
Some(self.estimated_selectivity())
}
}
}
pub fn resolved_query(&self) -> &SearchQueryInput {
&self.resolved_query
}
pub fn scan_mode(&self) -> &crate::scan::ScanMode {
&self.scan_mode
}
/// Returns `true` when this scan is in `ScanMode::Disjunctive` (`RankJoinRule`
/// elided predicate tagging for an eligible `RankJoinExec` subtree).
pub fn is_tagless_disjunctive(&self) -> bool {
matches!(self.scan_mode, crate::scan::ScanMode::Disjunctive { .. })
}
/// Converts a `ScanMode::Tagged` scan into a tagless `ScanMode::Disjunctive` scan for
/// `RankJoinExec` if `base_query` is `SearchQueryInput::All` and all of its `local_queries`
/// are in `elided_tags`. Strips the tag columns from the output schema and scanner
/// configuration, records the matched tag names in `matched_tags`, and returns the positional
/// `old_col_idx -> Option` mapping.
pub(crate) fn with_elided_disjunctive_tags(
&self,
elided_tags: &std::collections::BTreeSet,
matched_tags: &mut std::collections::BTreeSet,
) -> Option<(Self, Vec