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;
36pub(in crate::db) use descriptor::{
37    assemble_aggregate_terminal_execution_descriptor,
38    assemble_load_execution_node_descriptor_for_authority,
39    assemble_load_execution_node_descriptor_from_route_facts,
40    assemble_scalar_aggregate_execution_descriptor_with_projection,
41    freeze_load_execution_route_facts_for_authority,
42    freeze_load_execution_route_facts_for_model_only,
43};
44
45impl StructuralQuery {
46    // Assemble one finalized diagnostics artifact from route facts that were
47    // already frozen by the caller-selected schema authority.
48    fn finalized_execution_diagnostics_from_route_facts(
49        plan: &AccessPlannedQuery,
50        route_facts: &crate::db::executor::explain::descriptor::LoadExecutionRouteFacts,
51        reuse: Option<TraceReuseEvent>,
52    ) -> FinalizedQueryDiagnostics {
53        let descriptor =
54            assemble_load_execution_node_descriptor_from_route_facts(plan, route_facts);
55        let route_diagnostics =
56            assemble_load_execution_verbose_diagnostics_from_route_facts(plan, route_facts);
57        let explain = plan.explain();
58
59        // Phase 1: add descriptor-stage summaries for key execution operators.
60        let mut logical_diagnostics = Vec::new();
61        logical_diagnostics.push(format!(
62            "diag.d.has_top_n_seek={}",
63            descriptor.contains_type(ExplainExecutionNodeType::TopNSeek)
64        ));
65        logical_diagnostics.push(format!(
66            "diag.d.has_index_range_limit_pushdown={}",
67            descriptor.contains_type(ExplainExecutionNodeType::IndexRangeLimitPushdown)
68        ));
69        logical_diagnostics.push(format!(
70            "diag.d.has_index_predicate_prefilter={}",
71            descriptor.contains_type(ExplainExecutionNodeType::IndexPredicatePrefilter)
72        ));
73        logical_diagnostics.push(format!(
74            "diag.d.has_residual_filter={}",
75            descriptor.contains_type(ExplainExecutionNodeType::ResidualFilter)
76        ));
77
78        // Phase 2: append logical-plan diagnostics relevant to verbose explain.
79        logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
80        logical_diagnostics.push(format!(
81            "diag.p.order_pushdown={}",
82            plan_order_pushdown_label(explain.order_pushdown())
83        ));
84        logical_diagnostics.push(format!(
85            "diag.p.predicate_pushdown={}",
86            plan_predicate_pushdown_label(explain.predicate(), explain.access())
87        ));
88        logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
89        logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
90        logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
91
92        FinalizedQueryDiagnostics::new(descriptor, route_diagnostics, logical_diagnostics, reuse)
93    }
94
95    // Assemble one model-only execution descriptor from a previously built
96    // access plan so standalone text/json/verbose explain surfaces do not each
97    // rebuild it.
98    pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
99        &self,
100        plan: &AccessPlannedQuery,
101    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
102        let primary_key_names = model_primary_key_names(self.model());
103        let route_facts = freeze_load_execution_route_facts_for_model_only(
104            self.model().fields(),
105            primary_key_names.as_slice(),
106            plan,
107        )
108        .map_err(QueryError::execute)?;
109
110        Ok(assemble_load_execution_node_descriptor_from_route_facts(
111            plan,
112            &route_facts,
113        ))
114    }
115
116    // Assemble one execution descriptor from accepted executor authority.
117    pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
118        &self,
119        plan: &AccessPlannedQuery,
120        authority: &EntityAuthority,
121    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
122        debug_assert_eq!(self.model().path(), authority.entity_path());
123        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
124            .map_err(QueryError::execute)?;
125
126        Ok(assemble_load_execution_node_descriptor_from_route_facts(
127            plan,
128            &route_facts,
129        ))
130    }
131
132    // Render one standalone model-only verbose execution explain payload from
133    // a single access plan, freezing one immutable diagnostics artifact instead
134    // of returning one wrapper-owned line list that callers still have to
135    // extend locally.
136    fn finalized_execution_diagnostics_from_model_only_plan(
137        &self,
138        plan: &AccessPlannedQuery,
139        reuse: Option<TraceReuseEvent>,
140    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
141        let primary_key_names = model_primary_key_names(self.model());
142        let route_facts = freeze_load_execution_route_facts_for_model_only(
143            self.model().fields(),
144            primary_key_names.as_slice(),
145            plan,
146        )
147        .map_err(QueryError::execute)?;
148
149        Ok(Self::finalized_execution_diagnostics_from_route_facts(
150            plan,
151            &route_facts,
152            reuse,
153        ))
154    }
155
156    /// Freeze one immutable diagnostics artifact through accepted executor
157    /// authority while still allowing one caller-owned descriptor mutation.
158    pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
159        &self,
160        plan: &AccessPlannedQuery,
161        authority: &EntityAuthority,
162        reuse: Option<TraceReuseEvent>,
163        mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
164    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
165        debug_assert_eq!(self.model().path(), authority.entity_path());
166        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
167            .map_err(QueryError::execute)?;
168        let mut diagnostics =
169            Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse);
170        mutate_descriptor(&mut diagnostics.execution);
171
172        Ok(diagnostics)
173    }
174
175    // Render one verbose execution explain payload using only the canonical
176    // diagnostics artifact owned by this executor boundary.
177    fn explain_execution_verbose_from_plan(
178        &self,
179        plan: &AccessPlannedQuery,
180    ) -> Result<String, QueryError> {
181        self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
182            .map(|diagnostics| diagnostics.render_text_verbose())
183    }
184
185    // Freeze one explain-only access-choice snapshot from accepted
186    // planner-visible indexes before building descriptor diagnostics.
187    fn finalize_explain_access_choice_for_visible_indexes(
188        &self,
189        plan: &mut AccessPlannedQuery,
190        visible_indexes: &VisibleIndexes<'_>,
191    ) {
192        if let Some(schema_info) = visible_indexes.accepted_schema_info() {
193            plan.finalize_access_choice_for_model_with_accepted_indexes_and_schema(
194                self.model(),
195                visible_indexes.accepted_field_path_indexes(),
196                visible_indexes.accepted_expression_indexes(),
197                schema_info,
198            );
199            return;
200        }
201
202        plan.finalize_access_choice_for_model_only_with_indexes(
203            self.model(),
204            visible_indexes.generated_model_only_indexes(),
205        );
206    }
207
208    // Freeze one explicit model-only access-choice snapshot for standalone
209    // query explain surfaces that intentionally do not have accepted runtime
210    // schema authority.
211    fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
212        plan.finalize_access_choice_for_model_only_with_indexes(
213            self.model(),
214            self.model().indexes(),
215        );
216    }
217
218    // Build one explicit model-only execution descriptor for standalone query
219    // surfaces that are not bound to a recovered store/accepted schema.
220    fn explain_execution_descriptor_for_model_only(
221        &self,
222    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
223        let mut plan = self.build_plan()?;
224        self.finalize_explain_access_choice_for_model_only(&mut plan);
225
226        self.explain_execution_descriptor_from_model_only_plan(&plan)
227    }
228
229    // Build one execution descriptor using the caller-resolved accepted visible
230    // indexes for runtime/session explain.
231    fn explain_execution_descriptor_for_visible_indexes(
232        &self,
233        visible_indexes: &VisibleIndexes<'_>,
234    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
235        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
236        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
237
238        self.explain_execution_descriptor_from_model_only_plan(&plan)
239    }
240
241    // Render one explicit model-only verbose execution payload for standalone
242    // query surfaces that are not bound to a recovered store/accepted schema.
243    fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
244        let mut plan = self.build_plan()?;
245        self.finalize_explain_access_choice_for_model_only(&mut plan);
246
247        self.explain_execution_verbose_from_plan(&plan)
248    }
249
250    // Render one verbose execution payload using the caller-resolved accepted
251    // visible indexes for runtime/session explain.
252    fn explain_execution_verbose_for_visible_indexes(
253        &self,
254        visible_indexes: &VisibleIndexes<'_>,
255    ) -> Result<String, QueryError> {
256        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
257        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
258
259        self.explain_execution_verbose_from_plan(&plan)
260    }
261
262    /// Explain one model-only load execution shape through the structural query core.
263    #[inline(never)]
264    pub(in crate::db) fn explain_execution_for_model_only(
265        &self,
266    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
267        self.explain_execution_descriptor_for_model_only()
268    }
269
270    /// Explain one load execution shape using a caller-visible index slice.
271    #[inline(never)]
272    pub(in crate::db) fn explain_execution_with_visible_indexes(
273        &self,
274        visible_indexes: &VisibleIndexes<'_>,
275    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
276        self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
277    }
278
279    /// Render one model-only verbose scalar load execution payload through the
280    /// shared structural descriptor and route-diagnostics paths.
281    #[inline(never)]
282    pub(in crate::db) fn explain_execution_verbose_for_model_only(
283        &self,
284    ) -> Result<String, QueryError> {
285        self.render_execution_verbose_for_model_only()
286    }
287
288    /// Render one verbose scalar load execution payload using visible indexes.
289    #[inline(never)]
290    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
291        &self,
292        visible_indexes: &VisibleIndexes<'_>,
293    ) -> Result<String, QueryError> {
294        self.explain_execution_verbose_for_visible_indexes(visible_indexes)
295    }
296
297    /// Explain one aggregate terminal execution route without running it.
298    #[inline(never)]
299    #[cfg(test)]
300    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
301        &self,
302        visible_indexes: &VisibleIndexes<'_>,
303        aggregate: AggregateRouteShape<'_>,
304    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
305        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
306        let query_explain = plan.explain();
307        let terminal = aggregate.kind();
308        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
309
310        Ok(ExplainAggregateTerminalPlan::new(
311            query_explain,
312            terminal,
313            execution,
314        ))
315    }
316}
317
318impl<E> PreparedExecutionPlan<E>
319where
320    E: EntityValue + EntityKind,
321{
322    /// Explain one cached prepared aggregate terminal route without running it.
323    pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
324        &self,
325        strategy: &S,
326    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
327    where
328        S: AggregateExplain,
329    {
330        let Some(kind) = strategy.explain_aggregate_kind() else {
331            return Err(QueryError::invariant(
332                "prepared fluent aggregate explain requires an explain-visible aggregate kind",
333            ));
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}