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, ProjectionStrategy},
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
32pub(in crate::db) use descriptor::{
33    assemble_aggregate_terminal_execution_descriptor, assemble_load_execution_node_descriptor,
34    assemble_load_execution_node_descriptor_from_route_facts,
35    assemble_load_execution_verbose_diagnostics_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    #[allow(dead_code)]
201    pub(in crate::db) fn explain_execution_with_visible_indexes(
202        &self,
203        visible_indexes: &VisibleIndexes<'_>,
204    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
205        self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
206    }
207
208    /// Render one verbose scalar load execution payload through the shared
209    /// structural descriptor and route-diagnostics paths.
210    #[inline(never)]
211    pub(in crate::db) fn explain_execution_verbose(&self) -> Result<String, QueryError> {
212        self.explain_execution_verbose_for_visibility(None)
213    }
214
215    /// Render one verbose scalar load execution payload using visible indexes.
216    #[inline(never)]
217    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
218        &self,
219        visible_indexes: &VisibleIndexes<'_>,
220    ) -> Result<String, QueryError> {
221        self.explain_execution_verbose_for_visibility(Some(visible_indexes))
222    }
223
224    /// Explain one aggregate terminal execution route without running it.
225    #[inline(never)]
226    #[cfg(test)]
227    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
228        &self,
229        visible_indexes: &VisibleIndexes<'_>,
230        aggregate: AggregateRouteShape<'_>,
231    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
232        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
233        let query_explain = plan.explain();
234        let terminal = aggregate.kind();
235        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
236
237        Ok(ExplainAggregateTerminalPlan::new(
238            query_explain,
239            terminal,
240            execution,
241        ))
242    }
243}
244
245impl<E> PreparedExecutionPlan<E>
246where
247    E: EntityValue + EntityKind,
248{
249    /// Explain one cached prepared aggregate terminal route without running it.
250    pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
251        &self,
252        strategy: &S,
253    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
254    where
255        S: AggregateExplain,
256    {
257        let Some(kind) = strategy.explain_aggregate_kind() else {
258            return Err(QueryError::invariant(
259                "prepared fluent aggregate explain requires an explain-visible aggregate kind",
260            ));
261        };
262        let aggregate = AggregateRouteShape::new_from_fields(
263            kind,
264            strategy.explain_projected_field(),
265            E::MODEL.fields(),
266            E::MODEL.primary_key().name(),
267        );
268        let execution =
269            assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
270
271        Ok(ExplainAggregateTerminalPlan::new(
272            self.logical_plan().explain(),
273            kind,
274            execution,
275        ))
276    }
277
278    /// Explain one cached prepared `bytes_by(field)` terminal route without running it.
279    pub(in crate::db) fn explain_bytes_by_terminal(
280        &self,
281        target_field: &str,
282    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
283        let mut descriptor = self
284            .explain_load_execution_node_descriptor()
285            .map_err(QueryError::execute)?;
286        let projection_mode = self.bytes_by_projection_mode(target_field);
287        let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
288
289        descriptor
290            .node_properties
291            .insert("terminal", Value::from("bytes_by"));
292        descriptor
293            .node_properties
294            .insert("terminal_field", Value::from(target_field.to_string()));
295        descriptor.node_properties.insert(
296            "terminal_projection_mode",
297            Value::from(projection_mode_label),
298        );
299        descriptor.node_properties.insert(
300            "terminal_index_only",
301            Value::from(matches!(
302                projection_mode,
303                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
304            )),
305        );
306
307        Ok(descriptor)
308    }
309
310    /// Explain one cached prepared projection terminal route without running it.
311    pub(in crate::db) fn explain_prepared_projection_terminal(
312        &self,
313        strategy: &ProjectionStrategy,
314    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
315        let mut descriptor = self
316            .explain_load_execution_node_descriptor()
317            .map_err(QueryError::execute)?;
318        let projection_descriptor = strategy.explain_descriptor();
319
320        descriptor.node_properties.insert(
321            "terminal",
322            Value::from(projection_descriptor.terminal_label()),
323        );
324        descriptor.node_properties.insert(
325            "terminal_field",
326            Value::from(projection_descriptor.field_label().to_string()),
327        );
328        descriptor.node_properties.insert(
329            "terminal_output",
330            Value::from(projection_descriptor.output_label()),
331        );
332
333        Ok(descriptor)
334    }
335}
336
337impl<E> Query<E>
338where
339    E: EntityValue + EntityKind,
340{
341    // Resolve the structural execution descriptor through either the default
342    // schema-owned visibility lane or one caller-provided visible-index slice.
343    fn explain_execution_descriptor_for_visibility(
344        &self,
345        visible_indexes: Option<&VisibleIndexes<'_>>,
346    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
347        match visible_indexes {
348            Some(visible_indexes) => self
349                .structural()
350                .explain_execution_with_visible_indexes(visible_indexes),
351            None => self.structural().explain_execution(),
352        }
353    }
354
355    // Render one descriptor-derived execution surface after resolving the
356    // visibility slice once at the typed query boundary.
357    fn render_execution_descriptor_for_visibility(
358        &self,
359        visible_indexes: Option<&VisibleIndexes<'_>>,
360        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
361    ) -> Result<String, QueryError> {
362        let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
363
364        Ok(render(descriptor))
365    }
366
367    // Render one verbose execution explain payload after choosing the
368    // appropriate structural visibility lane once.
369    fn explain_execution_verbose_for_visibility(
370        &self,
371        visible_indexes: Option<&VisibleIndexes<'_>>,
372    ) -> Result<String, QueryError> {
373        match visible_indexes {
374            Some(visible_indexes) => self
375                .structural()
376                .explain_execution_verbose_with_visible_indexes(visible_indexes),
377            None => self.structural().explain_execution_verbose(),
378        }
379    }
380
381    /// Explain executor-selected load execution shape without running it.
382    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
383        self.explain_execution_descriptor_for_visibility(None)
384    }
385
386    /// Explain executor-selected load execution shape with caller-visible indexes.
387    #[allow(dead_code)]
388    pub(in crate::db) fn explain_execution_with_visible_indexes(
389        &self,
390        visible_indexes: &VisibleIndexes<'_>,
391    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
392        self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
393    }
394
395    /// Explain executor-selected load execution shape as deterministic text.
396    pub fn explain_execution_text(&self) -> Result<String, QueryError> {
397        self.render_execution_descriptor_for_visibility(None, |descriptor| {
398            descriptor.render_text_tree()
399        })
400    }
401
402    /// Explain executor-selected load execution shape as canonical JSON.
403    pub fn explain_execution_json(&self) -> Result<String, QueryError> {
404        self.render_execution_descriptor_for_visibility(None, |descriptor| {
405            descriptor.render_json_canonical()
406        })
407    }
408
409    /// Explain executor-selected load execution shape with route diagnostics.
410    #[inline(never)]
411    pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
412        self.explain_execution_verbose_for_visibility(None)
413    }
414
415    /// Explain one aggregate terminal execution route without running it.
416    #[cfg(test)]
417    #[inline(never)]
418    pub(in crate::db) fn explain_aggregate_terminal(
419        &self,
420        aggregate: AggregateExpr,
421    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
422        self.structural()
423            .explain_aggregate_terminal_with_visible_indexes(
424                &VisibleIndexes::schema_owned(E::MODEL.indexes()),
425                AggregateRouteShape::new_from_fields(
426                    aggregate.kind(),
427                    aggregate.target_field(),
428                    E::MODEL.fields(),
429                    E::MODEL.primary_key().name(),
430                ),
431            )
432    }
433}
434
435// Render the logical ORDER pushdown label for verbose execution diagnostics.
436fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
437    match order_pushdown {
438        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
439        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
440            format!("eligible(index={index},prefix_len={prefix_len})")
441        }
442        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
443    }
444}
445
446// Render the logical predicate pushdown label for verbose execution diagnostics.
447fn plan_predicate_pushdown_label(
448    predicate: &ExplainPredicate,
449    access: &ExplainAccessPath,
450) -> String {
451    let access_label = explain_access_kind_label(access);
452    if matches!(predicate, ExplainPredicate::None) {
453        return "none".to_string();
454    }
455    if access_label == "full_scan" {
456        if explain_predicate_contains_non_strict_compare(predicate) {
457            return "fallback(non_strict_compare_coercion)".to_string();
458        }
459        if explain_predicate_contains_empty_prefix_starts_with(predicate) {
460            return "fallback(starts_with_empty_prefix)".to_string();
461        }
462        if explain_predicate_contains_is_null(predicate) {
463            return "fallback(is_null_full_scan)".to_string();
464        }
465        if explain_predicate_contains_text_scan_operator(predicate) {
466            return "fallback(text_operator_full_scan)".to_string();
467        }
468
469        return format!("fallback({access_label})");
470    }
471
472    format!("applied({access_label})")
473}
474
475// Detect predicates that force non-strict compare fallback diagnostics.
476fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
477    match predicate {
478        ExplainPredicate::Compare { coercion, .. }
479        | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
480        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
481            .iter()
482            .any(explain_predicate_contains_non_strict_compare),
483        ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
484        ExplainPredicate::None
485        | ExplainPredicate::True
486        | ExplainPredicate::False
487        | ExplainPredicate::IsNull { .. }
488        | ExplainPredicate::IsNotNull { .. }
489        | ExplainPredicate::IsMissing { .. }
490        | ExplainPredicate::IsEmpty { .. }
491        | ExplainPredicate::IsNotEmpty { .. }
492        | ExplainPredicate::TextContains { .. }
493        | ExplainPredicate::TextContainsCi { .. } => false,
494    }
495}
496
497// Detect IS NULL predicates that force full-scan fallback diagnostics.
498fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
499    match predicate {
500        ExplainPredicate::IsNull { .. } => true,
501        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
502            children.iter().any(explain_predicate_contains_is_null)
503        }
504        ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
505        ExplainPredicate::None
506        | ExplainPredicate::True
507        | ExplainPredicate::False
508        | ExplainPredicate::Compare { .. }
509        | ExplainPredicate::CompareFields { .. }
510        | ExplainPredicate::IsNotNull { .. }
511        | ExplainPredicate::IsMissing { .. }
512        | ExplainPredicate::IsEmpty { .. }
513        | ExplainPredicate::IsNotEmpty { .. }
514        | ExplainPredicate::TextContains { .. }
515        | ExplainPredicate::TextContainsCi { .. } => false,
516    }
517}
518
519// Detect empty starts_with predicates that force fallback diagnostics.
520fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
521    match predicate {
522        ExplainPredicate::Compare {
523            op: CompareOp::StartsWith,
524            value: Value::Text(prefix),
525            ..
526        } => prefix.is_empty(),
527        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
528            .iter()
529            .any(explain_predicate_contains_empty_prefix_starts_with),
530        ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
531        ExplainPredicate::None
532        | ExplainPredicate::True
533        | ExplainPredicate::False
534        | ExplainPredicate::Compare { .. }
535        | ExplainPredicate::CompareFields { .. }
536        | ExplainPredicate::IsNull { .. }
537        | ExplainPredicate::IsNotNull { .. }
538        | ExplainPredicate::IsMissing { .. }
539        | ExplainPredicate::IsEmpty { .. }
540        | ExplainPredicate::IsNotEmpty { .. }
541        | ExplainPredicate::TextContains { .. }
542        | ExplainPredicate::TextContainsCi { .. } => false,
543    }
544}
545
546// Detect text scan predicates that force full-scan fallback diagnostics.
547fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
548    match predicate {
549        ExplainPredicate::Compare {
550            op: CompareOp::EndsWith,
551            ..
552        }
553        | ExplainPredicate::TextContains { .. }
554        | ExplainPredicate::TextContainsCi { .. } => true,
555        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
556            .iter()
557            .any(explain_predicate_contains_text_scan_operator),
558        ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
559        ExplainPredicate::Compare { .. }
560        | ExplainPredicate::CompareFields { .. }
561        | ExplainPredicate::None
562        | ExplainPredicate::True
563        | ExplainPredicate::False
564        | ExplainPredicate::IsNull { .. }
565        | ExplainPredicate::IsNotNull { .. }
566        | ExplainPredicate::IsMissing { .. }
567        | ExplainPredicate::IsEmpty { .. }
568        | ExplainPredicate::IsNotEmpty { .. } => false,
569    }
570}