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_semantic_indexes_and_schema(
196                self.model(),
197                visible_indexes.accepted_semantic_index_contracts(),
198                schema_info,
199            );
200            return;
201        }
202
203        plan.finalize_access_choice_for_model_only_with_indexes(
204            self.model(),
205            visible_indexes.generated_model_only_indexes(),
206        );
207    }
208
209    // Freeze one explicit model-only access-choice snapshot for standalone
210    // query explain surfaces that intentionally do not have accepted runtime
211    // schema authority.
212    fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
213        plan.finalize_access_choice_for_model_only_with_indexes(
214            self.model(),
215            self.model().indexes(),
216        );
217    }
218
219    // Build one explicit model-only execution descriptor for standalone query
220    // surfaces that are not bound to a recovered store/accepted schema.
221    fn explain_execution_descriptor_for_model_only(
222        &self,
223    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
224        let mut plan = self.build_plan()?;
225        self.finalize_explain_access_choice_for_model_only(&mut plan);
226
227        self.explain_execution_descriptor_from_model_only_plan(&plan)
228    }
229
230    // Build one execution descriptor using the caller-resolved accepted visible
231    // indexes for runtime/session explain.
232    fn explain_execution_descriptor_for_visible_indexes(
233        &self,
234        visible_indexes: &VisibleIndexes<'_>,
235    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
236        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
237        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
238
239        self.explain_execution_descriptor_from_model_only_plan(&plan)
240    }
241
242    // Render one explicit model-only verbose execution payload for standalone
243    // query surfaces that are not bound to a recovered store/accepted schema.
244    fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
245        let mut plan = self.build_plan()?;
246        self.finalize_explain_access_choice_for_model_only(&mut plan);
247
248        self.explain_execution_verbose_from_plan(&plan)
249    }
250
251    // Render one verbose execution payload using the caller-resolved accepted
252    // visible indexes for runtime/session explain.
253    fn explain_execution_verbose_for_visible_indexes(
254        &self,
255        visible_indexes: &VisibleIndexes<'_>,
256    ) -> Result<String, QueryError> {
257        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
258        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
259
260        self.explain_execution_verbose_from_plan(&plan)
261    }
262
263    /// Explain one model-only load execution shape through the structural query core.
264    #[inline(never)]
265    pub(in crate::db) fn explain_execution_for_model_only(
266        &self,
267    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
268        self.explain_execution_descriptor_for_model_only()
269    }
270
271    /// Explain one load execution shape using a caller-visible index slice.
272    #[inline(never)]
273    pub(in crate::db) fn explain_execution_with_visible_indexes(
274        &self,
275        visible_indexes: &VisibleIndexes<'_>,
276    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
277        self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
278    }
279
280    /// Render one model-only verbose scalar load execution payload through the
281    /// shared structural descriptor and route-diagnostics paths.
282    #[inline(never)]
283    pub(in crate::db) fn explain_execution_verbose_for_model_only(
284        &self,
285    ) -> Result<String, QueryError> {
286        self.render_execution_verbose_for_model_only()
287    }
288
289    /// Render one verbose scalar load execution payload using visible indexes.
290    #[inline(never)]
291    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
292        &self,
293        visible_indexes: &VisibleIndexes<'_>,
294    ) -> Result<String, QueryError> {
295        self.explain_execution_verbose_for_visible_indexes(visible_indexes)
296    }
297
298    /// Explain one aggregate terminal execution route without running it.
299    #[inline(never)]
300    #[cfg(test)]
301    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
302        &self,
303        visible_indexes: &VisibleIndexes<'_>,
304        aggregate: AggregateRouteShape<'_>,
305    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
306        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
307        let query_explain = plan.explain();
308        let terminal = aggregate.kind();
309        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
310
311        Ok(ExplainAggregateTerminalPlan::new(
312            query_explain,
313            terminal,
314            execution,
315        ))
316    }
317}
318
319impl<E> PreparedExecutionPlan<E>
320where
321    E: EntityValue + EntityKind,
322{
323    /// Explain one cached prepared aggregate terminal route without running it.
324    pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
325        &self,
326        strategy: &S,
327    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
328    where
329        S: AggregateExplain,
330    {
331        let Some(kind) = strategy.explain_aggregate_kind() else {
332            return Err(QueryError::invariant());
333        };
334        let aggregate = self
335            .authority()
336            .aggregate_route_shape(kind, strategy.explain_projected_field())
337            .map_err(QueryError::execute)?;
338        let execution =
339            assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
340
341        Ok(ExplainAggregateTerminalPlan::new(
342            self.logical_plan().explain(),
343            kind,
344            execution,
345        ))
346    }
347
348    /// Explain one cached prepared `bytes_by(field)` terminal route without running it.
349    pub(in crate::db) fn explain_bytes_by_terminal(
350        &self,
351        target_field: &str,
352    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
353        let mut descriptor = self
354            .explain_load_execution_node_descriptor()
355            .map_err(QueryError::execute)?;
356        let projection_mode = self.bytes_by_projection_mode(target_field);
357        let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
358
359        descriptor
360            .node_properties
361            .insert("terminal", Value::from("bytes_by"));
362        descriptor
363            .node_properties
364            .insert("terminal_field", Value::from(target_field.to_string()));
365        descriptor.node_properties.insert(
366            "terminal_projection_mode",
367            Value::from(projection_mode_label),
368        );
369        descriptor.node_properties.insert(
370            "terminal_index_only",
371            Value::from(matches!(
372                projection_mode,
373                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
374            )),
375        );
376
377        Ok(descriptor)
378    }
379
380    /// Explain one cached prepared projection terminal route without running it.
381    pub(in crate::db) fn explain_prepared_projection_terminal<S>(
382        &self,
383        strategy: &S,
384    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
385    where
386        S: ProjectionExplain,
387    {
388        let mut descriptor = self
389            .explain_load_execution_node_descriptor()
390            .map_err(QueryError::execute)?;
391        let projection_descriptor = strategy.explain_projection_descriptor();
392
393        descriptor.node_properties.insert(
394            "terminal",
395            Value::from(projection_descriptor.terminal_label()),
396        );
397        descriptor.node_properties.insert(
398            "terminal_field",
399            Value::from(projection_descriptor.field_label().to_string()),
400        );
401        descriptor.node_properties.insert(
402            "terminal_output",
403            Value::from(projection_descriptor.output_label()),
404        );
405
406        Ok(descriptor)
407    }
408}
409
410impl<E> Query<E>
411where
412    E: EntityValue + EntityKind,
413{
414    // Resolve the structural execution descriptor through either the explicit
415    // model-only lane or one caller-provided visible-index slice.
416    fn explain_execution_descriptor_for_model_only_or_visible_indexes(
417        &self,
418        visible_indexes: Option<&VisibleIndexes<'_>>,
419    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
420        match visible_indexes {
421            Some(visible_indexes) => self
422                .structural()
423                .explain_execution_with_visible_indexes(visible_indexes),
424            None => self.structural().explain_execution_for_model_only(),
425        }
426    }
427
428    // Render one descriptor-derived execution surface after resolving the
429    // visibility slice once at the typed query boundary.
430    fn render_execution_descriptor_for_visibility(
431        &self,
432        visible_indexes: Option<&VisibleIndexes<'_>>,
433        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
434    ) -> Result<String, QueryError> {
435        let descriptor =
436            self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
437
438        Ok(render(descriptor))
439    }
440
441    // Render one verbose execution explain payload after choosing the explicit
442    // model-only lane or the accepted visible-index lane once.
443    fn explain_execution_verbose_for_model_only_or_visible_indexes(
444        &self,
445        visible_indexes: Option<&VisibleIndexes<'_>>,
446    ) -> Result<String, QueryError> {
447        match visible_indexes {
448            Some(visible_indexes) => self
449                .structural()
450                .explain_execution_verbose_with_visible_indexes(visible_indexes),
451            None => self.structural().explain_execution_verbose_for_model_only(),
452        }
453    }
454
455    /// Explain executor-selected load execution shape without running it.
456    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
457        self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
458    }
459
460    /// Explain executor-selected load execution shape with caller-visible indexes.
461    #[cfg(test)]
462    pub(in crate::db) fn explain_execution_with_visible_indexes(
463        &self,
464        visible_indexes: &VisibleIndexes<'_>,
465    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
466        self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
467    }
468
469    /// Explain executor-selected load execution shape as deterministic text.
470    pub fn explain_execution_text(&self) -> Result<String, QueryError> {
471        self.render_execution_descriptor_for_visibility(None, |descriptor| {
472            descriptor.render_text_tree()
473        })
474    }
475
476    /// Explain executor-selected load execution shape as canonical JSON.
477    pub fn explain_execution_json(&self) -> Result<String, QueryError> {
478        self.render_execution_descriptor_for_visibility(None, |descriptor| {
479            descriptor.render_json_canonical()
480        })
481    }
482
483    /// Explain executor-selected load execution shape with route diagnostics.
484    #[inline(never)]
485    pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
486        self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
487    }
488
489    /// Explain one aggregate terminal execution route without running it.
490    #[cfg(test)]
491    #[inline(never)]
492    pub(in crate::db) fn explain_aggregate_terminal(
493        &self,
494        aggregate: AggregateExpr,
495    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
496        self.structural()
497            .explain_aggregate_terminal_with_visible_indexes(
498                &VisibleIndexes::generated_model_only(E::MODEL.indexes()),
499                AggregateRouteShape::new_from_fields(
500                    aggregate.kind(),
501                    aggregate.target_field(),
502                    E::MODEL.fields(),
503                    model_primary_key_names(E::MODEL).as_slice(),
504                ),
505            )
506    }
507}
508
509fn model_primary_key_names(model: &EntityModel) -> Vec<&'static str> {
510    model
511        .primary_key_model()
512        .fields()
513        .iter()
514        .map(crate::model::field::FieldModel::name)
515        .collect()
516}
517
518// Render the logical ORDER pushdown label for verbose execution diagnostics.
519fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
520    match order_pushdown {
521        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
522        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
523            format!("eligible(index={index},prefix_len={prefix_len})")
524        }
525        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
526    }
527}
528
529// Render the logical predicate pushdown label for verbose execution diagnostics.
530fn plan_predicate_pushdown_label(
531    predicate: &ExplainPredicate,
532    access: &ExplainAccessPath,
533) -> String {
534    let access_label = explain_access_kind_label(access);
535    if matches!(predicate, ExplainPredicate::None) {
536        return "none".to_string();
537    }
538    if access_label == "full_scan" {
539        if explain_predicate_contains_non_strict_compare(predicate) {
540            return "fallback(non_strict_compare_coercion)".to_string();
541        }
542        if explain_predicate_contains_empty_prefix_starts_with(predicate) {
543            return "fallback(starts_with_empty_prefix)".to_string();
544        }
545        if explain_predicate_contains_is_null(predicate) {
546            return "fallback(is_null_full_scan)".to_string();
547        }
548        if explain_predicate_contains_text_scan_operator(predicate) {
549            return "fallback(text_operator_full_scan)".to_string();
550        }
551
552        return format!("fallback({access_label})");
553    }
554
555    format!("applied({access_label})")
556}
557
558// Detect predicates that force non-strict compare fallback diagnostics.
559fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
560    match predicate {
561        ExplainPredicate::Compare { coercion, .. }
562        | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
563        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
564            .iter()
565            .any(explain_predicate_contains_non_strict_compare),
566        ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
567        ExplainPredicate::None
568        | ExplainPredicate::True
569        | ExplainPredicate::False
570        | ExplainPredicate::IsNull { .. }
571        | ExplainPredicate::IsNotNull { .. }
572        | ExplainPredicate::IsMissing { .. }
573        | ExplainPredicate::IsEmpty { .. }
574        | ExplainPredicate::IsNotEmpty { .. }
575        | ExplainPredicate::TextContains { .. }
576        | ExplainPredicate::TextContainsCi { .. } => false,
577    }
578}
579
580// Detect IS NULL predicates that force full-scan fallback diagnostics.
581fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
582    match predicate {
583        ExplainPredicate::IsNull { .. } => true,
584        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
585            children.iter().any(explain_predicate_contains_is_null)
586        }
587        ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
588        ExplainPredicate::None
589        | ExplainPredicate::True
590        | ExplainPredicate::False
591        | ExplainPredicate::Compare { .. }
592        | ExplainPredicate::CompareFields { .. }
593        | ExplainPredicate::IsNotNull { .. }
594        | ExplainPredicate::IsMissing { .. }
595        | ExplainPredicate::IsEmpty { .. }
596        | ExplainPredicate::IsNotEmpty { .. }
597        | ExplainPredicate::TextContains { .. }
598        | ExplainPredicate::TextContainsCi { .. } => false,
599    }
600}
601
602// Detect empty starts_with predicates that force fallback diagnostics.
603fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
604    match predicate {
605        ExplainPredicate::Compare {
606            op: CompareOp::StartsWith,
607            value: Value::Text(prefix),
608            ..
609        } => prefix.is_empty(),
610        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
611            .iter()
612            .any(explain_predicate_contains_empty_prefix_starts_with),
613        ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
614        ExplainPredicate::None
615        | ExplainPredicate::True
616        | ExplainPredicate::False
617        | ExplainPredicate::Compare { .. }
618        | ExplainPredicate::CompareFields { .. }
619        | ExplainPredicate::IsNull { .. }
620        | ExplainPredicate::IsNotNull { .. }
621        | ExplainPredicate::IsMissing { .. }
622        | ExplainPredicate::IsEmpty { .. }
623        | ExplainPredicate::IsNotEmpty { .. }
624        | ExplainPredicate::TextContains { .. }
625        | ExplainPredicate::TextContainsCi { .. } => false,
626    }
627}
628
629// Detect text scan predicates that force full-scan fallback diagnostics.
630fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
631    match predicate {
632        ExplainPredicate::Compare {
633            op: CompareOp::EndsWith,
634            ..
635        }
636        | ExplainPredicate::TextContains { .. }
637        | ExplainPredicate::TextContainsCi { .. } => true,
638        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
639            .iter()
640            .any(explain_predicate_contains_text_scan_operator),
641        ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
642        ExplainPredicate::Compare { .. }
643        | ExplainPredicate::CompareFields { .. }
644        | ExplainPredicate::None
645        | ExplainPredicate::True
646        | ExplainPredicate::False
647        | ExplainPredicate::IsNull { .. }
648        | ExplainPredicate::IsNotNull { .. }
649        | ExplainPredicate::IsMissing { .. }
650        | ExplainPredicate::IsEmpty { .. }
651        | ExplainPredicate::IsNotEmpty { .. } => false,
652    }
653}