Skip to main content

icydb_core/db/executor/explain/
mod.rs

1//! Module: db::executor::explain
2//! Responsibility: assemble executor-owned EXPLAIN descriptor payloads.
3//! Does not own: explain rendering formats or logical plan projection.
4//! Boundary: centralized execution-plan-to-descriptor mapping used by EXPLAIN surfaces.
5
6mod descriptor;
7
8#[cfg(test)]
9use crate::db::executor::planning::route::AggregateRouteShape;
10#[cfg(test)]
11use crate::db::query::builder::AggregateExpr;
12use crate::{
13    db::{
14        Query, TraceReuseEvent,
15        executor::{BytesByProjectionMode, EntityAuthority, PreparedExecutionPlan},
16        predicate::{CoercionId, CompareOp},
17        query::{
18            builder::{AggregateExplain, ProjectionExplain},
19            explain::{
20                ExplainAccessPath, ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
21                ExplainExecutionNodeType, ExplainOrderPushdown, ExplainPredicate,
22                FinalizedQueryDiagnostics,
23            },
24            intent::{QueryError, StructuralQuery},
25            plan::{AccessPlannedQuery, VisibleIndexes, explain_access_kind_label},
26        },
27    },
28    model::entity::EntityModel,
29    traits::{EntityKind, EntityValue},
30    value::Value,
31};
32
33#[cfg(test)]
34pub(in crate::db) use descriptor::assemble_load_execution_node_descriptor;
35use descriptor::assemble_load_execution_verbose_diagnostics_from_route_facts;
36#[cfg(feature = "sql")]
37#[cfg(feature = "sql")]
38pub(in crate::db) use descriptor::assemble_scalar_aggregate_execution_descriptor_with_projection;
39pub(in crate::db) use descriptor::{
40    assemble_aggregate_terminal_execution_descriptor,
41    assemble_load_execution_node_descriptor_for_authority,
42    assemble_load_execution_node_descriptor_from_route_facts,
43    freeze_load_execution_route_facts_for_authority,
44    freeze_load_execution_route_facts_for_model_only,
45};
46
47impl StructuralQuery {
48    // Assemble one finalized diagnostics artifact from route facts that were
49    // already frozen by the caller-selected schema authority.
50    fn finalized_execution_diagnostics_from_route_facts(
51        plan: &AccessPlannedQuery,
52        route_facts: &crate::db::executor::explain::descriptor::LoadExecutionRouteFacts,
53        reuse: Option<TraceReuseEvent>,
54    ) -> FinalizedQueryDiagnostics {
55        let descriptor =
56            assemble_load_execution_node_descriptor_from_route_facts(plan, route_facts);
57        let route_diagnostics =
58            assemble_load_execution_verbose_diagnostics_from_route_facts(plan, route_facts);
59        let explain = plan.explain();
60
61        // Phase 1: add descriptor-stage summaries for key execution operators.
62        let mut logical_diagnostics = Vec::new();
63        logical_diagnostics.push(format!(
64            "diag.d.has_top_n_seek={}",
65            descriptor.contains_type(ExplainExecutionNodeType::TopNSeek)
66        ));
67        logical_diagnostics.push(format!(
68            "diag.d.has_index_range_limit_pushdown={}",
69            descriptor.contains_type(ExplainExecutionNodeType::IndexRangeLimitPushdown)
70        ));
71        logical_diagnostics.push(format!(
72            "diag.d.has_index_predicate_prefilter={}",
73            descriptor.contains_type(ExplainExecutionNodeType::IndexPredicatePrefilter)
74        ));
75        logical_diagnostics.push(format!(
76            "diag.d.has_residual_filter={}",
77            descriptor.contains_type(ExplainExecutionNodeType::ResidualFilter)
78        ));
79
80        // Phase 2: append logical-plan diagnostics relevant to verbose explain.
81        logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
82        logical_diagnostics.push(format!(
83            "diag.p.order_pushdown={}",
84            plan_order_pushdown_label(explain.order_pushdown())
85        ));
86        logical_diagnostics.push(format!(
87            "diag.p.predicate_pushdown={}",
88            plan_predicate_pushdown_label(explain.predicate(), explain.access())
89        ));
90        logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
91        logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
92        logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
93
94        FinalizedQueryDiagnostics::new(descriptor, route_diagnostics, logical_diagnostics, reuse)
95    }
96
97    // Assemble one model-only execution descriptor from a previously built
98    // access plan so standalone text/json/verbose explain surfaces do not each
99    // rebuild it.
100    pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
101        &self,
102        plan: &AccessPlannedQuery,
103    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
104        let primary_key_names = model_primary_key_names(self.model());
105        let route_facts = freeze_load_execution_route_facts_for_model_only(
106            self.model().fields(),
107            primary_key_names.as_slice(),
108            plan,
109        )
110        .map_err(QueryError::execute)?;
111
112        Ok(assemble_load_execution_node_descriptor_from_route_facts(
113            plan,
114            &route_facts,
115        ))
116    }
117
118    // Assemble one execution descriptor from accepted executor authority.
119    pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
120        &self,
121        plan: &AccessPlannedQuery,
122        authority: &EntityAuthority,
123    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
124        debug_assert_eq!(self.model().path(), authority.entity_path());
125        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
126            .map_err(QueryError::execute)?;
127
128        Ok(assemble_load_execution_node_descriptor_from_route_facts(
129            plan,
130            &route_facts,
131        ))
132    }
133
134    // Render one standalone model-only verbose execution explain payload from
135    // a single access plan, freezing one immutable diagnostics artifact instead
136    // of returning one wrapper-owned line list that callers still have to
137    // extend locally.
138    fn finalized_execution_diagnostics_from_model_only_plan(
139        &self,
140        plan: &AccessPlannedQuery,
141        reuse: Option<TraceReuseEvent>,
142    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
143        let primary_key_names = model_primary_key_names(self.model());
144        let route_facts = freeze_load_execution_route_facts_for_model_only(
145            self.model().fields(),
146            primary_key_names.as_slice(),
147            plan,
148        )
149        .map_err(QueryError::execute)?;
150
151        Ok(Self::finalized_execution_diagnostics_from_route_facts(
152            plan,
153            &route_facts,
154            reuse,
155        ))
156    }
157
158    /// Freeze one immutable diagnostics artifact through accepted executor
159    /// authority while still allowing one caller-owned descriptor mutation.
160    pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
161        &self,
162        plan: &AccessPlannedQuery,
163        authority: &EntityAuthority,
164        reuse: Option<TraceReuseEvent>,
165        mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
166    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
167        debug_assert_eq!(self.model().path(), authority.entity_path());
168        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
169            .map_err(QueryError::execute)?;
170        let mut diagnostics =
171            Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse);
172        mutate_descriptor(&mut diagnostics.execution);
173
174        Ok(diagnostics)
175    }
176
177    // Render one verbose execution explain payload using only the canonical
178    // diagnostics artifact owned by this executor boundary.
179    fn explain_execution_verbose_from_plan(
180        &self,
181        plan: &AccessPlannedQuery,
182    ) -> Result<String, QueryError> {
183        self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
184            .map(|diagnostics| diagnostics.render_text_verbose())
185    }
186
187    // Freeze one explain-only access-choice snapshot from accepted
188    // planner-visible indexes before building descriptor diagnostics.
189    fn finalize_explain_access_choice_for_visible_indexes(
190        &self,
191        plan: &mut AccessPlannedQuery,
192        visible_indexes: &VisibleIndexes<'_>,
193    ) {
194        if let Some(schema_info) = visible_indexes.accepted_schema_info() {
195            plan.finalize_access_choice_for_model_with_accepted_indexes_and_schema(
196                self.model(),
197                visible_indexes.accepted_field_path_indexes(),
198                visible_indexes.accepted_expression_indexes(),
199                schema_info,
200            );
201            return;
202        }
203
204        plan.finalize_access_choice_for_model_only_with_indexes(
205            self.model(),
206            visible_indexes.generated_model_only_indexes(),
207        );
208    }
209
210    // Freeze one explicit model-only access-choice snapshot for standalone
211    // query explain surfaces that intentionally do not have accepted runtime
212    // schema authority.
213    fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
214        plan.finalize_access_choice_for_model_only_with_indexes(
215            self.model(),
216            self.model().indexes(),
217        );
218    }
219
220    // Build one explicit model-only execution descriptor for standalone query
221    // surfaces that are not bound to a recovered store/accepted schema.
222    fn explain_execution_descriptor_for_model_only(
223        &self,
224    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
225        let mut plan = self.build_plan()?;
226        self.finalize_explain_access_choice_for_model_only(&mut plan);
227
228        self.explain_execution_descriptor_from_model_only_plan(&plan)
229    }
230
231    // Build one execution descriptor using the caller-resolved accepted visible
232    // indexes for runtime/session explain.
233    fn explain_execution_descriptor_for_visible_indexes(
234        &self,
235        visible_indexes: &VisibleIndexes<'_>,
236    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
237        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
238        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
239
240        self.explain_execution_descriptor_from_model_only_plan(&plan)
241    }
242
243    // Render one explicit model-only verbose execution payload for standalone
244    // query surfaces that are not bound to a recovered store/accepted schema.
245    fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
246        let mut plan = self.build_plan()?;
247        self.finalize_explain_access_choice_for_model_only(&mut plan);
248
249        self.explain_execution_verbose_from_plan(&plan)
250    }
251
252    // Render one verbose execution payload using the caller-resolved accepted
253    // visible indexes for runtime/session explain.
254    fn explain_execution_verbose_for_visible_indexes(
255        &self,
256        visible_indexes: &VisibleIndexes<'_>,
257    ) -> Result<String, QueryError> {
258        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
259        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
260
261        self.explain_execution_verbose_from_plan(&plan)
262    }
263
264    /// Explain one model-only load execution shape through the structural query core.
265    #[inline(never)]
266    pub(in crate::db) fn explain_execution_for_model_only(
267        &self,
268    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
269        self.explain_execution_descriptor_for_model_only()
270    }
271
272    /// Explain one load execution shape using a caller-visible index slice.
273    #[inline(never)]
274    pub(in crate::db) fn explain_execution_with_visible_indexes(
275        &self,
276        visible_indexes: &VisibleIndexes<'_>,
277    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
278        self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
279    }
280
281    /// Render one model-only verbose scalar load execution payload through the
282    /// shared structural descriptor and route-diagnostics paths.
283    #[inline(never)]
284    pub(in crate::db) fn explain_execution_verbose_for_model_only(
285        &self,
286    ) -> Result<String, QueryError> {
287        self.render_execution_verbose_for_model_only()
288    }
289
290    /// Render one verbose scalar load execution payload using visible indexes.
291    #[inline(never)]
292    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
293        &self,
294        visible_indexes: &VisibleIndexes<'_>,
295    ) -> Result<String, QueryError> {
296        self.explain_execution_verbose_for_visible_indexes(visible_indexes)
297    }
298
299    /// Explain one aggregate terminal execution route without running it.
300    #[inline(never)]
301    #[cfg(test)]
302    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
303        &self,
304        visible_indexes: &VisibleIndexes<'_>,
305        aggregate: AggregateRouteShape<'_>,
306    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
307        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
308        let query_explain = plan.explain();
309        let terminal = aggregate.kind();
310        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
311
312        Ok(ExplainAggregateTerminalPlan::new(
313            query_explain,
314            terminal,
315            execution,
316        ))
317    }
318}
319
320impl<E> PreparedExecutionPlan<E>
321where
322    E: EntityValue + EntityKind,
323{
324    /// Explain one cached prepared aggregate terminal route without running it.
325    pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
326        &self,
327        strategy: &S,
328    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
329    where
330        S: AggregateExplain,
331    {
332        let Some(kind) = strategy.explain_aggregate_kind() else {
333            return Err(QueryError::invariant());
334        };
335        let aggregate = self
336            .authority()
337            .aggregate_route_shape(kind, strategy.explain_projected_field())
338            .map_err(QueryError::execute)?;
339        let execution =
340            assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
341
342        Ok(ExplainAggregateTerminalPlan::new(
343            self.logical_plan().explain(),
344            kind,
345            execution,
346        ))
347    }
348
349    /// Explain one cached prepared `bytes_by(field)` terminal route without running it.
350    pub(in crate::db) fn explain_bytes_by_terminal(
351        &self,
352        target_field: &str,
353    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
354        let mut descriptor = self
355            .explain_load_execution_node_descriptor()
356            .map_err(QueryError::execute)?;
357        let projection_mode = self.bytes_by_projection_mode(target_field);
358        let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
359
360        descriptor
361            .node_properties
362            .insert("terminal", Value::from("bytes_by"));
363        descriptor
364            .node_properties
365            .insert("terminal_field", Value::from(target_field.to_string()));
366        descriptor.node_properties.insert(
367            "terminal_projection_mode",
368            Value::from(projection_mode_label),
369        );
370        descriptor.node_properties.insert(
371            "terminal_index_only",
372            Value::from(matches!(
373                projection_mode,
374                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
375            )),
376        );
377
378        Ok(descriptor)
379    }
380
381    /// Explain one cached prepared projection terminal route without running it.
382    pub(in crate::db) fn explain_prepared_projection_terminal<S>(
383        &self,
384        strategy: &S,
385    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
386    where
387        S: ProjectionExplain,
388    {
389        let mut descriptor = self
390            .explain_load_execution_node_descriptor()
391            .map_err(QueryError::execute)?;
392        let projection_descriptor = strategy.explain_projection_descriptor();
393
394        descriptor.node_properties.insert(
395            "terminal",
396            Value::from(projection_descriptor.terminal_label()),
397        );
398        descriptor.node_properties.insert(
399            "terminal_field",
400            Value::from(projection_descriptor.field_label().to_string()),
401        );
402        descriptor.node_properties.insert(
403            "terminal_output",
404            Value::from(projection_descriptor.output_label()),
405        );
406
407        Ok(descriptor)
408    }
409}
410
411impl<E> Query<E>
412where
413    E: EntityValue + EntityKind,
414{
415    // Resolve the structural execution descriptor through either the explicit
416    // model-only lane or one caller-provided visible-index slice.
417    fn explain_execution_descriptor_for_model_only_or_visible_indexes(
418        &self,
419        visible_indexes: Option<&VisibleIndexes<'_>>,
420    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
421        match visible_indexes {
422            Some(visible_indexes) => self
423                .structural()
424                .explain_execution_with_visible_indexes(visible_indexes),
425            None => self.structural().explain_execution_for_model_only(),
426        }
427    }
428
429    // Render one descriptor-derived execution surface after resolving the
430    // visibility slice once at the typed query boundary.
431    fn render_execution_descriptor_for_visibility(
432        &self,
433        visible_indexes: Option<&VisibleIndexes<'_>>,
434        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
435    ) -> Result<String, QueryError> {
436        let descriptor =
437            self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
438
439        Ok(render(descriptor))
440    }
441
442    // Render one verbose execution explain payload after choosing the explicit
443    // model-only lane or the accepted visible-index lane once.
444    fn explain_execution_verbose_for_model_only_or_visible_indexes(
445        &self,
446        visible_indexes: Option<&VisibleIndexes<'_>>,
447    ) -> Result<String, QueryError> {
448        match visible_indexes {
449            Some(visible_indexes) => self
450                .structural()
451                .explain_execution_verbose_with_visible_indexes(visible_indexes),
452            None => self.structural().explain_execution_verbose_for_model_only(),
453        }
454    }
455
456    /// Explain executor-selected load execution shape without running it.
457    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
458        self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
459    }
460
461    /// Explain executor-selected load execution shape with caller-visible indexes.
462    #[cfg(test)]
463    pub(in crate::db) fn explain_execution_with_visible_indexes(
464        &self,
465        visible_indexes: &VisibleIndexes<'_>,
466    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
467        self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
468    }
469
470    /// Explain executor-selected load execution shape as deterministic text.
471    pub fn explain_execution_text(&self) -> Result<String, QueryError> {
472        self.render_execution_descriptor_for_visibility(None, |descriptor| {
473            descriptor.render_text_tree()
474        })
475    }
476
477    /// Explain executor-selected load execution shape as canonical JSON.
478    pub fn explain_execution_json(&self) -> Result<String, QueryError> {
479        self.render_execution_descriptor_for_visibility(None, |descriptor| {
480            descriptor.render_json_canonical()
481        })
482    }
483
484    /// Explain executor-selected load execution shape with route diagnostics.
485    #[inline(never)]
486    pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
487        self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
488    }
489
490    /// Explain one aggregate terminal execution route without running it.
491    #[cfg(test)]
492    #[inline(never)]
493    pub(in crate::db) fn explain_aggregate_terminal(
494        &self,
495        aggregate: AggregateExpr,
496    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
497        self.structural()
498            .explain_aggregate_terminal_with_visible_indexes(
499                &VisibleIndexes::generated_model_only(E::MODEL.indexes()),
500                AggregateRouteShape::new_from_fields(
501                    aggregate.kind(),
502                    aggregate.target_field(),
503                    E::MODEL.fields(),
504                    model_primary_key_names(E::MODEL).as_slice(),
505                ),
506            )
507    }
508}
509
510fn model_primary_key_names(model: &EntityModel) -> Vec<&'static str> {
511    model
512        .primary_key_model()
513        .fields()
514        .iter()
515        .map(crate::model::field::FieldModel::name)
516        .collect()
517}
518
519// Render the logical ORDER pushdown label for verbose execution diagnostics.
520fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
521    match order_pushdown {
522        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
523        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
524            format!("eligible(index={index},prefix_len={prefix_len})")
525        }
526        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
527    }
528}
529
530// Render the logical predicate pushdown label for verbose execution diagnostics.
531fn plan_predicate_pushdown_label(
532    predicate: &ExplainPredicate,
533    access: &ExplainAccessPath,
534) -> String {
535    let access_label = explain_access_kind_label(access);
536    if matches!(predicate, ExplainPredicate::None) {
537        return "none".to_string();
538    }
539    if access_label == "full_scan" {
540        if explain_predicate_contains_non_strict_compare(predicate) {
541            return "fallback(non_strict_compare_coercion)".to_string();
542        }
543        if explain_predicate_contains_empty_prefix_starts_with(predicate) {
544            return "fallback(starts_with_empty_prefix)".to_string();
545        }
546        if explain_predicate_contains_is_null(predicate) {
547            return "fallback(is_null_full_scan)".to_string();
548        }
549        if explain_predicate_contains_text_scan_operator(predicate) {
550            return "fallback(text_operator_full_scan)".to_string();
551        }
552
553        return format!("fallback({access_label})");
554    }
555
556    format!("applied({access_label})")
557}
558
559// Detect predicates that force non-strict compare fallback diagnostics.
560fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
561    match predicate {
562        ExplainPredicate::Compare { coercion, .. }
563        | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
564        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
565            .iter()
566            .any(explain_predicate_contains_non_strict_compare),
567        ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
568        ExplainPredicate::None
569        | ExplainPredicate::True
570        | ExplainPredicate::False
571        | ExplainPredicate::IsNull { .. }
572        | ExplainPredicate::IsNotNull { .. }
573        | ExplainPredicate::IsMissing { .. }
574        | ExplainPredicate::IsEmpty { .. }
575        | ExplainPredicate::IsNotEmpty { .. }
576        | ExplainPredicate::TextContains { .. }
577        | ExplainPredicate::TextContainsCi { .. } => false,
578    }
579}
580
581// Detect IS NULL predicates that force full-scan fallback diagnostics.
582fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
583    match predicate {
584        ExplainPredicate::IsNull { .. } => true,
585        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
586            children.iter().any(explain_predicate_contains_is_null)
587        }
588        ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
589        ExplainPredicate::None
590        | ExplainPredicate::True
591        | ExplainPredicate::False
592        | ExplainPredicate::Compare { .. }
593        | ExplainPredicate::CompareFields { .. }
594        | ExplainPredicate::IsNotNull { .. }
595        | ExplainPredicate::IsMissing { .. }
596        | ExplainPredicate::IsEmpty { .. }
597        | ExplainPredicate::IsNotEmpty { .. }
598        | ExplainPredicate::TextContains { .. }
599        | ExplainPredicate::TextContainsCi { .. } => false,
600    }
601}
602
603// Detect empty starts_with predicates that force fallback diagnostics.
604fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
605    match predicate {
606        ExplainPredicate::Compare {
607            op: CompareOp::StartsWith,
608            value: Value::Text(prefix),
609            ..
610        } => prefix.is_empty(),
611        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
612            .iter()
613            .any(explain_predicate_contains_empty_prefix_starts_with),
614        ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
615        ExplainPredicate::None
616        | ExplainPredicate::True
617        | ExplainPredicate::False
618        | ExplainPredicate::Compare { .. }
619        | ExplainPredicate::CompareFields { .. }
620        | ExplainPredicate::IsNull { .. }
621        | ExplainPredicate::IsNotNull { .. }
622        | ExplainPredicate::IsMissing { .. }
623        | ExplainPredicate::IsEmpty { .. }
624        | ExplainPredicate::IsNotEmpty { .. }
625        | ExplainPredicate::TextContains { .. }
626        | ExplainPredicate::TextContainsCi { .. } => false,
627    }
628}
629
630// Detect text scan predicates that force full-scan fallback diagnostics.
631fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
632    match predicate {
633        ExplainPredicate::Compare {
634            op: CompareOp::EndsWith,
635            ..
636        }
637        | ExplainPredicate::TextContains { .. }
638        | ExplainPredicate::TextContainsCi { .. } => true,
639        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
640            .iter()
641            .any(explain_predicate_contains_text_scan_operator),
642        ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
643        ExplainPredicate::Compare { .. }
644        | ExplainPredicate::CompareFields { .. }
645        | ExplainPredicate::None
646        | ExplainPredicate::True
647        | ExplainPredicate::False
648        | ExplainPredicate::IsNull { .. }
649        | ExplainPredicate::IsNotNull { .. }
650        | ExplainPredicate::IsMissing { .. }
651        | ExplainPredicate::IsEmpty { .. }
652        | ExplainPredicate::IsNotEmpty { .. } => false,
653    }
654}