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