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        query::{
17            builder::{AggregateExplain, ProjectionExplain},
18            explain::{
19                ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
20                ExplainExecutionNodeType, ExplainOrderPushdown, FinalizedQueryDiagnostics,
21            },
22            intent::{QueryError, StructuralQuery},
23            plan::{AccessPlannedQuery, VisibleIndexes},
24        },
25    },
26    model::entity::EntityModel,
27    traits::{EntityKind, EntityValue},
28    value::Value,
29};
30
31#[cfg(test)]
32pub(in crate::db) use descriptor::assemble_load_execution_node_descriptor;
33use descriptor::assemble_load_execution_verbose_diagnostics_from_route_facts;
34#[cfg(feature = "sql")]
35#[cfg(feature = "sql")]
36pub(in crate::db) use descriptor::assemble_scalar_aggregate_execution_descriptor_with_projection;
37pub(in crate::db) use descriptor::{
38    assemble_aggregate_terminal_execution_descriptor,
39    assemble_load_execution_node_descriptor_for_authority,
40    assemble_load_execution_node_descriptor_from_route_facts,
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()
87        ));
88        logical_diagnostics.push(format!(
89            "diag.p.predicate_pushdown_outcome={}",
90            plan.predicate_pushdown_outcome_label()
91        ));
92        logical_diagnostics.push(format!(
93            "diag.p.predicate_pushdown_reason={}",
94            plan.predicate_pushdown_reason_label()
95        ));
96        logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
97        logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
98        logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
99
100        FinalizedQueryDiagnostics::new(descriptor, route_diagnostics, logical_diagnostics, reuse)
101    }
102
103    // Assemble one model-only execution descriptor from a previously built
104    // access plan so standalone text/json/verbose explain surfaces do not each
105    // rebuild it.
106    pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
107        &self,
108        plan: &AccessPlannedQuery,
109    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
110        let primary_key_names = model_primary_key_names(self.model());
111        let route_facts = freeze_load_execution_route_facts_for_model_only(
112            self.model().fields(),
113            primary_key_names.as_slice(),
114            plan,
115        )
116        .map_err(QueryError::execute)?;
117
118        Ok(assemble_load_execution_node_descriptor_from_route_facts(
119            plan,
120            &route_facts,
121        ))
122    }
123
124    // Assemble one execution descriptor from accepted executor authority.
125    pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
126        &self,
127        plan: &AccessPlannedQuery,
128        authority: &EntityAuthority,
129    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
130        debug_assert_eq!(self.model().path(), authority.entity_path());
131        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
132            .map_err(QueryError::execute)?;
133
134        Ok(assemble_load_execution_node_descriptor_from_route_facts(
135            plan,
136            &route_facts,
137        ))
138    }
139
140    // Render one standalone model-only verbose execution explain payload from
141    // a single access plan, freezing one immutable diagnostics artifact instead
142    // of returning one wrapper-owned line list that callers still have to
143    // extend locally.
144    fn finalized_execution_diagnostics_from_model_only_plan(
145        &self,
146        plan: &AccessPlannedQuery,
147        reuse: Option<TraceReuseEvent>,
148    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
149        let primary_key_names = model_primary_key_names(self.model());
150        let route_facts = freeze_load_execution_route_facts_for_model_only(
151            self.model().fields(),
152            primary_key_names.as_slice(),
153            plan,
154        )
155        .map_err(QueryError::execute)?;
156
157        Ok(Self::finalized_execution_diagnostics_from_route_facts(
158            plan,
159            &route_facts,
160            reuse,
161        ))
162    }
163
164    /// Freeze one immutable diagnostics artifact through accepted executor
165    /// authority while still allowing one caller-owned descriptor mutation.
166    pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
167        &self,
168        plan: &AccessPlannedQuery,
169        authority: &EntityAuthority,
170        reuse: Option<TraceReuseEvent>,
171        mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
172    ) -> Result<FinalizedQueryDiagnostics, QueryError> {
173        debug_assert_eq!(self.model().path(), authority.entity_path());
174        let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
175            .map_err(QueryError::execute)?;
176        let mut diagnostics =
177            Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse);
178        mutate_descriptor(&mut diagnostics.execution);
179
180        Ok(diagnostics)
181    }
182
183    // Render one verbose execution explain payload using only the canonical
184    // diagnostics artifact owned by this executor boundary.
185    fn explain_execution_verbose_from_plan(
186        &self,
187        plan: &AccessPlannedQuery,
188    ) -> Result<String, QueryError> {
189        self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
190            .map(|diagnostics| diagnostics.render_text_verbose())
191    }
192
193    // Freeze one explain-only access-choice snapshot from accepted
194    // planner-visible indexes before building descriptor diagnostics.
195    fn finalize_explain_access_choice_for_visible_indexes(
196        &self,
197        plan: &mut AccessPlannedQuery,
198        visible_indexes: &VisibleIndexes<'_>,
199    ) {
200        if let Some(schema_info) = visible_indexes.accepted_schema_info() {
201            plan.finalize_access_choice_for_model_with_semantic_indexes_and_schema(
202                self.model(),
203                visible_indexes.accepted_semantic_index_contracts(),
204                schema_info,
205            );
206            return;
207        }
208
209        plan.finalize_access_choice_for_model_only_with_indexes(
210            self.model(),
211            visible_indexes.generated_model_only_indexes(),
212        );
213    }
214
215    // Freeze one explicit model-only access-choice snapshot for standalone
216    // query explain surfaces that intentionally do not have accepted runtime
217    // schema authority.
218    fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
219        plan.finalize_access_choice_for_model_only_with_indexes(
220            self.model(),
221            self.model().indexes(),
222        );
223    }
224
225    // Build one explicit model-only execution descriptor for standalone query
226    // surfaces that are not bound to a recovered store/accepted schema.
227    fn explain_execution_descriptor_for_model_only(
228        &self,
229    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
230        let mut plan = self.build_plan()?;
231        self.finalize_explain_access_choice_for_model_only(&mut plan);
232
233        self.explain_execution_descriptor_from_model_only_plan(&plan)
234    }
235
236    // Build one execution descriptor using the caller-resolved accepted visible
237    // indexes for runtime/session explain.
238    fn explain_execution_descriptor_for_visible_indexes(
239        &self,
240        visible_indexes: &VisibleIndexes<'_>,
241    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
242        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
243        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
244
245        self.explain_execution_descriptor_from_model_only_plan(&plan)
246    }
247
248    // Render one explicit model-only verbose execution payload for standalone
249    // query surfaces that are not bound to a recovered store/accepted schema.
250    fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
251        let mut plan = self.build_plan()?;
252        self.finalize_explain_access_choice_for_model_only(&mut plan);
253
254        self.explain_execution_verbose_from_plan(&plan)
255    }
256
257    // Render one verbose execution payload using the caller-resolved accepted
258    // visible indexes for runtime/session explain.
259    fn explain_execution_verbose_for_visible_indexes(
260        &self,
261        visible_indexes: &VisibleIndexes<'_>,
262    ) -> Result<String, QueryError> {
263        let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
264        self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
265
266        self.explain_execution_verbose_from_plan(&plan)
267    }
268
269    /// Explain one model-only load execution shape through the structural query core.
270    #[inline(never)]
271    pub(in crate::db) fn explain_execution_for_model_only(
272        &self,
273    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
274        self.explain_execution_descriptor_for_model_only()
275    }
276
277    /// Explain one load execution shape using a caller-visible index slice.
278    #[inline(never)]
279    pub(in crate::db) fn explain_execution_with_visible_indexes(
280        &self,
281        visible_indexes: &VisibleIndexes<'_>,
282    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
283        self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
284    }
285
286    /// Render one model-only verbose scalar load execution payload through the
287    /// shared structural descriptor and route-diagnostics paths.
288    #[inline(never)]
289    pub(in crate::db) fn explain_execution_verbose_for_model_only(
290        &self,
291    ) -> Result<String, QueryError> {
292        self.render_execution_verbose_for_model_only()
293    }
294
295    /// Render one verbose scalar load execution payload using visible indexes.
296    #[inline(never)]
297    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
298        &self,
299        visible_indexes: &VisibleIndexes<'_>,
300    ) -> Result<String, QueryError> {
301        self.explain_execution_verbose_for_visible_indexes(visible_indexes)
302    }
303
304    /// Explain one aggregate terminal execution route without running it.
305    #[inline(never)]
306    #[cfg(test)]
307    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
308        &self,
309        visible_indexes: &VisibleIndexes<'_>,
310        aggregate: AggregateRouteShape<'_>,
311    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
312        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
313        let query_explain = plan.explain();
314        let terminal = aggregate.kind();
315        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
316
317        Ok(ExplainAggregateTerminalPlan::new(
318            query_explain,
319            terminal,
320            execution,
321        ))
322    }
323}
324
325impl<E> PreparedExecutionPlan<E>
326where
327    E: EntityValue + EntityKind,
328{
329    /// Explain one cached prepared aggregate terminal route without running it.
330    pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
331        &self,
332        strategy: &S,
333    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
334    where
335        S: AggregateExplain,
336    {
337        let Some(kind) = strategy.explain_aggregate_kind() else {
338            return Err(QueryError::invariant());
339        };
340        let aggregate = self
341            .authority()
342            .aggregate_route_shape(kind, strategy.explain_projected_field())
343            .map_err(QueryError::execute)?;
344        let execution =
345            assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
346
347        Ok(ExplainAggregateTerminalPlan::new(
348            self.logical_plan().explain(),
349            kind,
350            execution,
351        ))
352    }
353
354    /// Explain one cached prepared `bytes_by(field)` terminal route without running it.
355    pub(in crate::db) fn explain_bytes_by_terminal(
356        &self,
357        target_field: &str,
358    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
359        let mut descriptor = self
360            .explain_load_execution_node_descriptor()
361            .map_err(QueryError::execute)?;
362        let projection_mode = self.bytes_by_projection_mode(target_field);
363        let projection_mode_label = Self::bytes_by_projection_mode_label(projection_mode);
364
365        descriptor
366            .node_properties
367            .insert("terminal", Value::from("bytes_by"));
368        descriptor
369            .node_properties
370            .insert("terminal_field", Value::from(target_field.to_string()));
371        descriptor.node_properties.insert(
372            "terminal_projection_mode",
373            Value::from(projection_mode_label),
374        );
375        descriptor.node_properties.insert(
376            "terminal_index_only",
377            Value::from(matches!(
378                projection_mode,
379                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
380            )),
381        );
382
383        Ok(descriptor)
384    }
385
386    /// Explain one cached prepared projection terminal route without running it.
387    pub(in crate::db) fn explain_prepared_projection_terminal<S>(
388        &self,
389        strategy: &S,
390    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
391    where
392        S: ProjectionExplain,
393    {
394        let mut descriptor = self
395            .explain_load_execution_node_descriptor()
396            .map_err(QueryError::execute)?;
397        let projection_descriptor = strategy.explain_projection_descriptor();
398
399        descriptor.node_properties.insert(
400            "terminal",
401            Value::from(projection_descriptor.terminal_label()),
402        );
403        descriptor.node_properties.insert(
404            "terminal_field",
405            Value::from(projection_descriptor.field_label().to_string()),
406        );
407        descriptor.node_properties.insert(
408            "terminal_output",
409            Value::from(projection_descriptor.output_label()),
410        );
411
412        Ok(descriptor)
413    }
414}
415
416impl<E> Query<E>
417where
418    E: EntityValue + EntityKind,
419{
420    // Resolve the structural execution descriptor through either the explicit
421    // model-only lane or one caller-provided visible-index slice.
422    fn explain_execution_descriptor_for_model_only_or_visible_indexes(
423        &self,
424        visible_indexes: Option<&VisibleIndexes<'_>>,
425    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
426        match visible_indexes {
427            Some(visible_indexes) => self
428                .structural()
429                .explain_execution_with_visible_indexes(visible_indexes),
430            None => self.structural().explain_execution_for_model_only(),
431        }
432    }
433
434    // Render one descriptor-derived execution surface after resolving the
435    // visibility slice once at the typed query boundary.
436    fn render_execution_descriptor_for_visibility(
437        &self,
438        visible_indexes: Option<&VisibleIndexes<'_>>,
439        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
440    ) -> Result<String, QueryError> {
441        let descriptor =
442            self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
443
444        Ok(render(descriptor))
445    }
446
447    // Render one verbose execution explain payload after choosing the explicit
448    // model-only lane or the accepted visible-index lane once.
449    fn explain_execution_verbose_for_model_only_or_visible_indexes(
450        &self,
451        visible_indexes: Option<&VisibleIndexes<'_>>,
452    ) -> Result<String, QueryError> {
453        match visible_indexes {
454            Some(visible_indexes) => self
455                .structural()
456                .explain_execution_verbose_with_visible_indexes(visible_indexes),
457            None => self.structural().explain_execution_verbose_for_model_only(),
458        }
459    }
460
461    /// Explain executor-selected load execution shape without running it.
462    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
463        self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
464    }
465
466    /// Explain executor-selected load execution shape with caller-visible indexes.
467    #[cfg(test)]
468    pub(in crate::db) fn explain_execution_with_visible_indexes(
469        &self,
470        visible_indexes: &VisibleIndexes<'_>,
471    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
472        self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
473    }
474
475    /// Explain executor-selected load execution shape as deterministic text.
476    pub fn explain_execution_text(&self) -> Result<String, QueryError> {
477        self.render_execution_descriptor_for_visibility(None, |descriptor| {
478            descriptor.render_text_tree()
479        })
480    }
481
482    /// Explain executor-selected load execution shape as canonical JSON.
483    pub fn explain_execution_json(&self) -> Result<String, QueryError> {
484        self.render_execution_descriptor_for_visibility(None, |descriptor| {
485            descriptor.render_json_canonical()
486        })
487    }
488
489    /// Explain executor-selected load execution shape with route diagnostics.
490    #[inline(never)]
491    pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
492        self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
493    }
494
495    /// Explain one aggregate terminal execution route without running it.
496    #[cfg(test)]
497    #[inline(never)]
498    pub(in crate::db) fn explain_aggregate_terminal(
499        &self,
500        aggregate: AggregateExpr,
501    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
502        self.structural()
503            .explain_aggregate_terminal_with_visible_indexes(
504                &VisibleIndexes::generated_model_only(E::MODEL.indexes()),
505                AggregateRouteShape::new_from_fields(
506                    aggregate.kind(),
507                    aggregate.target_field(),
508                    E::MODEL.fields(),
509                    model_primary_key_names(E::MODEL).as_slice(),
510                ),
511            )
512    }
513}
514
515fn model_primary_key_names(model: &EntityModel) -> Vec<&'static str> {
516    model
517        .primary_key_model()
518        .fields()
519        .iter()
520        .map(crate::model::field::FieldModel::name)
521        .collect()
522}
523
524// Render the logical ORDER pushdown label for verbose execution diagnostics.
525fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
526    match order_pushdown {
527        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
528        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
529            format!("eligible(index={index},prefix_len={prefix_len})")
530        }
531        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
532    }
533}