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