Skip to main content

icydb_core/db/query/explain/
plan.rs

1//! Module: query::explain::plan
2//! Responsibility: deterministic logical-plan projection for EXPLAIN.
3//! Does not own: execution descriptor rendering or access visitor adapters.
4//! Boundary: logical explain DTOs and plan-side projection logic.
5
6use crate::{
7    db::{
8        access::{
9            AccessPlan, PushdownSurfaceEligibility, SecondaryOrderPushdownEligibility,
10            SecondaryOrderPushdownRejection,
11        },
12        predicate::{CoercionSpec, CompareOp, ComparePredicate, MissingRowPolicy, Predicate},
13        query::{
14            explain::{access_projection::write_access_json, writer::JsonWriter},
15            plan::{
16                AccessPlannedQuery, AggregateKind, DeleteLimitSpec, GroupHavingClause,
17                GroupHavingSpec, GroupHavingSymbol, GroupedPlanFallbackReason, LogicalPlan,
18                OrderDirection, OrderSpec, PageSpec, QueryMode, ScalarPlan, grouped_plan_strategy,
19            },
20        },
21    },
22    model::entity::EntityModel,
23    traits::FieldValue,
24    value::Value,
25};
26use std::ops::Bound;
27
28///
29/// ExplainPlan
30///
31/// Stable, deterministic representation of a planned query for observability.
32///
33
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct ExplainPlan {
36    pub(crate) mode: QueryMode,
37    pub(crate) access: ExplainAccessPath,
38    pub(crate) predicate: ExplainPredicate,
39    predicate_model: Option<Predicate>,
40    pub(crate) order_by: ExplainOrderBy,
41    pub(crate) distinct: bool,
42    pub(crate) grouping: ExplainGrouping,
43    pub(crate) order_pushdown: ExplainOrderPushdown,
44    pub(crate) page: ExplainPagination,
45    pub(crate) delete_limit: ExplainDeleteLimit,
46    pub(crate) consistency: MissingRowPolicy,
47}
48
49impl ExplainPlan {
50    /// Return query mode projected by this explain plan.
51    #[must_use]
52    pub const fn mode(&self) -> QueryMode {
53        self.mode
54    }
55
56    /// Borrow projected access-path shape.
57    #[must_use]
58    pub const fn access(&self) -> &ExplainAccessPath {
59        &self.access
60    }
61
62    /// Borrow projected predicate shape.
63    #[must_use]
64    pub const fn predicate(&self) -> &ExplainPredicate {
65        &self.predicate
66    }
67
68    /// Borrow projected ORDER BY shape.
69    #[must_use]
70    pub const fn order_by(&self) -> &ExplainOrderBy {
71        &self.order_by
72    }
73
74    /// Return whether DISTINCT is enabled.
75    #[must_use]
76    pub const fn distinct(&self) -> bool {
77        self.distinct
78    }
79
80    /// Borrow projected grouped-shape metadata.
81    #[must_use]
82    pub const fn grouping(&self) -> &ExplainGrouping {
83        &self.grouping
84    }
85
86    /// Borrow projected ORDER pushdown status.
87    #[must_use]
88    pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
89        &self.order_pushdown
90    }
91
92    /// Borrow projected pagination status.
93    #[must_use]
94    pub const fn page(&self) -> &ExplainPagination {
95        &self.page
96    }
97
98    /// Borrow projected delete-limit status.
99    #[must_use]
100    pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
101        &self.delete_limit
102    }
103
104    /// Return missing-row consistency policy.
105    #[must_use]
106    pub const fn consistency(&self) -> MissingRowPolicy {
107        self.consistency
108    }
109}
110
111impl ExplainPlan {
112    /// Return the canonical predicate model used for hashing/fingerprints.
113    ///
114    /// The explain projection must remain a faithful rendering of this model.
115    #[must_use]
116    pub(crate) fn predicate_model_for_hash(&self) -> Option<&Predicate> {
117        if let Some(predicate) = &self.predicate_model {
118            debug_assert_eq!(
119                self.predicate,
120                ExplainPredicate::from_predicate(predicate),
121                "explain predicate surface drifted from canonical predicate model"
122            );
123            Some(predicate)
124        } else {
125            debug_assert!(
126                matches!(self.predicate, ExplainPredicate::None),
127                "missing canonical predicate model requires ExplainPredicate::None"
128            );
129            None
130        }
131    }
132
133    /// Render this logical explain plan as deterministic canonical text.
134    ///
135    /// This surface is frontend-facing and intentionally stable for SQL/CLI
136    /// explain output and snapshot-style diagnostics.
137    #[must_use]
138    pub fn render_text_canonical(&self) -> String {
139        format!(
140            concat!(
141                "mode={:?}\n",
142                "access={:?}\n",
143                "predicate={:?}\n",
144                "order_by={:?}\n",
145                "distinct={}\n",
146                "grouping={:?}\n",
147                "order_pushdown={:?}\n",
148                "page={:?}\n",
149                "delete_limit={:?}\n",
150                "consistency={:?}",
151            ),
152            self.mode(),
153            self.access(),
154            self.predicate(),
155            self.order_by(),
156            self.distinct(),
157            self.grouping(),
158            self.order_pushdown(),
159            self.page(),
160            self.delete_limit(),
161            self.consistency(),
162        )
163    }
164
165    /// Render this logical explain plan as canonical JSON.
166    #[must_use]
167    pub fn render_json_canonical(&self) -> String {
168        let mut out = String::new();
169        write_logical_explain_json(self, &mut out);
170
171        out
172    }
173}
174
175///
176/// ExplainGrouping
177///
178/// Grouped-shape annotation for deterministic explain/fingerprint surfaces.
179///
180
181#[derive(Clone, Debug, Eq, PartialEq)]
182pub enum ExplainGrouping {
183    None,
184    Grouped {
185        strategy: &'static str,
186        fallback_reason: Option<&'static str>,
187        group_fields: Vec<ExplainGroupField>,
188        aggregates: Vec<ExplainGroupAggregate>,
189        having: Option<ExplainGroupHaving>,
190        max_groups: u64,
191        max_group_bytes: u64,
192    },
193}
194
195///
196/// ExplainGroupField
197///
198/// Stable grouped-key field identity carried by explain/hash surfaces.
199///
200
201#[derive(Clone, Debug, Eq, PartialEq)]
202pub struct ExplainGroupField {
203    pub(crate) slot_index: usize,
204    pub(crate) field: String,
205}
206
207impl ExplainGroupField {
208    /// Return grouped slot index.
209    #[must_use]
210    pub const fn slot_index(&self) -> usize {
211        self.slot_index
212    }
213
214    /// Borrow grouped field name.
215    #[must_use]
216    pub const fn field(&self) -> &str {
217        self.field.as_str()
218    }
219}
220
221///
222/// ExplainGroupAggregate
223///
224/// Stable explain-surface projection of one grouped aggregate terminal.
225///
226
227#[derive(Clone, Debug, Eq, PartialEq)]
228pub struct ExplainGroupAggregate {
229    pub(crate) kind: AggregateKind,
230    pub(crate) target_field: Option<String>,
231    pub(crate) distinct: bool,
232}
233
234impl ExplainGroupAggregate {
235    /// Return grouped aggregate kind.
236    #[must_use]
237    pub const fn kind(&self) -> AggregateKind {
238        self.kind
239    }
240
241    /// Borrow optional grouped aggregate target field.
242    #[must_use]
243    pub fn target_field(&self) -> Option<&str> {
244        self.target_field.as_deref()
245    }
246
247    /// Return whether grouped aggregate uses DISTINCT input semantics.
248    #[must_use]
249    pub const fn distinct(&self) -> bool {
250        self.distinct
251    }
252}
253
254///
255/// ExplainGroupHaving
256///
257/// Deterministic explain projection of grouped HAVING clauses.
258///
259
260#[derive(Clone, Debug, Eq, PartialEq)]
261pub struct ExplainGroupHaving {
262    pub(crate) clauses: Vec<ExplainGroupHavingClause>,
263}
264
265impl ExplainGroupHaving {
266    /// Borrow grouped HAVING clauses.
267    #[must_use]
268    pub const fn clauses(&self) -> &[ExplainGroupHavingClause] {
269        self.clauses.as_slice()
270    }
271}
272
273///
274/// ExplainGroupHavingClause
275///
276/// Stable explain-surface projection for one grouped HAVING clause.
277///
278
279#[derive(Clone, Debug, Eq, PartialEq)]
280pub struct ExplainGroupHavingClause {
281    pub(crate) symbol: ExplainGroupHavingSymbol,
282    pub(crate) op: CompareOp,
283    pub(crate) value: Value,
284}
285
286impl ExplainGroupHavingClause {
287    /// Borrow grouped HAVING symbol.
288    #[must_use]
289    pub const fn symbol(&self) -> &ExplainGroupHavingSymbol {
290        &self.symbol
291    }
292
293    /// Return grouped HAVING comparison operator.
294    #[must_use]
295    pub const fn op(&self) -> CompareOp {
296        self.op
297    }
298
299    /// Borrow grouped HAVING literal value.
300    #[must_use]
301    pub const fn value(&self) -> &Value {
302        &self.value
303    }
304}
305
306///
307/// ExplainGroupHavingSymbol
308///
309/// Stable explain-surface identity for grouped HAVING symbols.
310///
311
312#[derive(Clone, Debug, Eq, PartialEq)]
313pub enum ExplainGroupHavingSymbol {
314    GroupField { slot_index: usize, field: String },
315    AggregateIndex { index: usize },
316}
317
318///
319/// ExplainOrderPushdown
320///
321/// Deterministic ORDER BY pushdown eligibility reported by explain.
322///
323
324#[derive(Clone, Debug, Eq, PartialEq)]
325pub enum ExplainOrderPushdown {
326    MissingModelContext,
327    EligibleSecondaryIndex {
328        index: &'static str,
329        prefix_len: usize,
330    },
331    Rejected(SecondaryOrderPushdownRejection),
332}
333
334///
335/// ExplainAccessPath
336///
337/// Deterministic projection of logical access path shape for diagnostics.
338/// Mirrors planner-selected structural paths without runtime cursor state.
339///
340
341#[derive(Clone, Debug, Eq, PartialEq)]
342pub enum ExplainAccessPath {
343    ByKey {
344        key: Value,
345    },
346    ByKeys {
347        keys: Vec<Value>,
348    },
349    KeyRange {
350        start: Value,
351        end: Value,
352    },
353    IndexPrefix {
354        name: &'static str,
355        fields: Vec<&'static str>,
356        prefix_len: usize,
357        values: Vec<Value>,
358    },
359    IndexMultiLookup {
360        name: &'static str,
361        fields: Vec<&'static str>,
362        values: Vec<Value>,
363    },
364    IndexRange {
365        name: &'static str,
366        fields: Vec<&'static str>,
367        prefix_len: usize,
368        prefix: Vec<Value>,
369        lower: Bound<Value>,
370        upper: Bound<Value>,
371    },
372    FullScan,
373    Union(Vec<Self>),
374    Intersection(Vec<Self>),
375}
376
377///
378/// ExplainPredicate
379///
380/// Deterministic projection of canonical predicate structure for explain output.
381/// This preserves normalized predicate shape used by hashing/fingerprints.
382///
383
384#[derive(Clone, Debug, Eq, PartialEq)]
385pub enum ExplainPredicate {
386    None,
387    True,
388    False,
389    And(Vec<Self>),
390    Or(Vec<Self>),
391    Not(Box<Self>),
392    Compare {
393        field: String,
394        op: CompareOp,
395        value: Value,
396        coercion: CoercionSpec,
397    },
398    IsNull {
399        field: String,
400    },
401    IsNotNull {
402        field: String,
403    },
404    IsMissing {
405        field: String,
406    },
407    IsEmpty {
408        field: String,
409    },
410    IsNotEmpty {
411        field: String,
412    },
413    TextContains {
414        field: String,
415        value: Value,
416    },
417    TextContainsCi {
418        field: String,
419        value: Value,
420    },
421}
422
423///
424/// ExplainOrderBy
425///
426/// Deterministic projection of canonical ORDER BY shape.
427///
428
429#[derive(Clone, Debug, Eq, PartialEq)]
430pub enum ExplainOrderBy {
431    None,
432    Fields(Vec<ExplainOrder>),
433}
434
435///
436/// ExplainOrder
437///
438/// One canonical ORDER BY field + direction pair.
439///
440
441#[derive(Clone, Debug, Eq, PartialEq)]
442pub struct ExplainOrder {
443    pub(crate) field: String,
444    pub(crate) direction: OrderDirection,
445}
446
447impl ExplainOrder {
448    /// Borrow ORDER BY field name.
449    #[must_use]
450    pub const fn field(&self) -> &str {
451        self.field.as_str()
452    }
453
454    /// Return ORDER BY direction.
455    #[must_use]
456    pub const fn direction(&self) -> OrderDirection {
457        self.direction
458    }
459}
460
461///
462/// ExplainPagination
463///
464/// Explain-surface projection of pagination window configuration.
465///
466
467#[derive(Clone, Debug, Eq, PartialEq)]
468pub enum ExplainPagination {
469    None,
470    Page { limit: Option<u32>, offset: u32 },
471}
472
473///
474/// ExplainDeleteLimit
475///
476/// Explain-surface projection of delete-limit configuration.
477///
478
479#[derive(Clone, Debug, Eq, PartialEq)]
480pub enum ExplainDeleteLimit {
481    None,
482    Limit { max_rows: u32 },
483}
484
485impl AccessPlannedQuery {
486    /// Produce a stable, deterministic explanation of this logical plan.
487    #[must_use]
488    #[cfg(test)]
489    pub(crate) fn explain(&self) -> ExplainPlan {
490        self.explain_inner(None)
491    }
492
493    /// Produce a stable, deterministic explanation of this logical plan
494    /// with optional model context for query-layer projections.
495    ///
496    /// Query explain intentionally does not evaluate executor route pushdown
497    /// feasibility to keep query-layer dependencies executor-agnostic.
498    #[must_use]
499    pub(crate) fn explain_with_model(&self, model: &EntityModel) -> ExplainPlan {
500        self.explain_inner(Some(model))
501    }
502
503    pub(in crate::db::query::explain) fn explain_inner(
504        &self,
505        model: Option<&EntityModel>,
506    ) -> ExplainPlan {
507        // Phase 1: project logical plan variant into scalar core + grouped metadata.
508        let (logical, grouping) = match &self.logical {
509            LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
510            LogicalPlan::Grouped(logical) => {
511                let grouped_strategy = grouped_plan_strategy(self).expect(
512                    "grouped logical explain projection requires planner-owned grouped strategy",
513                );
514
515                (
516                    &logical.scalar,
517                    ExplainGrouping::Grouped {
518                        strategy: grouped_strategy.code(),
519                        fallback_reason: grouped_strategy
520                            .fallback_reason()
521                            .map(GroupedPlanFallbackReason::code),
522                        group_fields: logical
523                            .group
524                            .group_fields
525                            .iter()
526                            .map(|field_slot| ExplainGroupField {
527                                slot_index: field_slot.index(),
528                                field: field_slot.field().to_string(),
529                            })
530                            .collect(),
531                        aggregates: logical
532                            .group
533                            .aggregates
534                            .iter()
535                            .map(|aggregate| ExplainGroupAggregate {
536                                kind: aggregate.kind,
537                                target_field: aggregate.target_field.clone(),
538                                distinct: aggregate.distinct,
539                            })
540                            .collect(),
541                        having: explain_group_having(logical.having.as_ref()),
542                        max_groups: logical.group.execution.max_groups(),
543                        max_group_bytes: logical.group.execution.max_group_bytes(),
544                    },
545                )
546            }
547        };
548
549        // Phase 2: project scalar plan + access path into deterministic explain surface.
550        explain_scalar_inner(logical, grouping, model, &self.access)
551    }
552}
553
554fn explain_group_having(having: Option<&GroupHavingSpec>) -> Option<ExplainGroupHaving> {
555    let having = having?;
556
557    Some(ExplainGroupHaving {
558        clauses: having
559            .clauses()
560            .iter()
561            .map(explain_group_having_clause)
562            .collect(),
563    })
564}
565
566fn explain_group_having_clause(clause: &GroupHavingClause) -> ExplainGroupHavingClause {
567    ExplainGroupHavingClause {
568        symbol: explain_group_having_symbol(clause.symbol()),
569        op: clause.op(),
570        value: clause.value().clone(),
571    }
572}
573
574fn explain_group_having_symbol(symbol: &GroupHavingSymbol) -> ExplainGroupHavingSymbol {
575    match symbol {
576        GroupHavingSymbol::GroupField(field_slot) => ExplainGroupHavingSymbol::GroupField {
577            slot_index: field_slot.index(),
578            field: field_slot.field().to_string(),
579        },
580        GroupHavingSymbol::AggregateIndex(index) => {
581            ExplainGroupHavingSymbol::AggregateIndex { index: *index }
582        }
583    }
584}
585
586fn explain_scalar_inner<K>(
587    logical: &ScalarPlan,
588    grouping: ExplainGrouping,
589    model: Option<&EntityModel>,
590    access: &AccessPlan<K>,
591) -> ExplainPlan
592where
593    K: FieldValue,
594{
595    // Phase 1: consume canonical predicate model from planner-owned scalar semantics.
596    let predicate_model = logical.predicate.clone();
597    let predicate = match &predicate_model {
598        Some(predicate) => ExplainPredicate::from_predicate(predicate),
599        None => ExplainPredicate::None,
600    };
601
602    // Phase 2: project scalar-plan fields into explain-specific enums.
603    let order_by = explain_order(logical.order.as_ref());
604    let order_pushdown = explain_order_pushdown(model);
605    let page = explain_page(logical.page.as_ref());
606    let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
607
608    // Phase 3: assemble one stable explain payload.
609    ExplainPlan {
610        mode: logical.mode,
611        access: ExplainAccessPath::from_access_plan(access),
612        predicate,
613        predicate_model,
614        order_by,
615        distinct: logical.distinct,
616        grouping,
617        order_pushdown,
618        page,
619        delete_limit,
620        consistency: logical.consistency,
621    }
622}
623
624const fn explain_order_pushdown(model: Option<&EntityModel>) -> ExplainOrderPushdown {
625    let _ = model;
626
627    // Query explain does not own physical pushdown feasibility routing.
628    ExplainOrderPushdown::MissingModelContext
629}
630
631impl From<SecondaryOrderPushdownEligibility> for ExplainOrderPushdown {
632    fn from(value: SecondaryOrderPushdownEligibility) -> Self {
633        Self::from(PushdownSurfaceEligibility::from(&value))
634    }
635}
636
637impl From<PushdownSurfaceEligibility<'_>> for ExplainOrderPushdown {
638    fn from(value: PushdownSurfaceEligibility<'_>) -> Self {
639        match value {
640            PushdownSurfaceEligibility::EligibleSecondaryIndex { index, prefix_len } => {
641                Self::EligibleSecondaryIndex { index, prefix_len }
642            }
643            PushdownSurfaceEligibility::Rejected { reason } => Self::Rejected(reason.clone()),
644        }
645    }
646}
647
648impl ExplainPredicate {
649    pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
650        match predicate {
651            Predicate::True => Self::True,
652            Predicate::False => Self::False,
653            Predicate::And(children) => {
654                Self::And(children.iter().map(Self::from_predicate).collect())
655            }
656            Predicate::Or(children) => {
657                Self::Or(children.iter().map(Self::from_predicate).collect())
658            }
659            Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
660            Predicate::Compare(compare) => Self::from_compare(compare),
661            Predicate::IsNull { field } => Self::IsNull {
662                field: field.clone(),
663            },
664            Predicate::IsNotNull { field } => Self::IsNotNull {
665                field: field.clone(),
666            },
667            Predicate::IsMissing { field } => Self::IsMissing {
668                field: field.clone(),
669            },
670            Predicate::IsEmpty { field } => Self::IsEmpty {
671                field: field.clone(),
672            },
673            Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
674                field: field.clone(),
675            },
676            Predicate::TextContains { field, value } => Self::TextContains {
677                field: field.clone(),
678                value: value.clone(),
679            },
680            Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
681                field: field.clone(),
682                value: value.clone(),
683            },
684        }
685    }
686
687    fn from_compare(compare: &ComparePredicate) -> Self {
688        Self::Compare {
689            field: compare.field.clone(),
690            op: compare.op,
691            value: compare.value.clone(),
692            coercion: compare.coercion.clone(),
693        }
694    }
695}
696
697fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
698    let Some(order) = order else {
699        return ExplainOrderBy::None;
700    };
701
702    if order.fields.is_empty() {
703        return ExplainOrderBy::None;
704    }
705
706    ExplainOrderBy::Fields(
707        order
708            .fields
709            .iter()
710            .map(|(field, direction)| ExplainOrder {
711                field: field.clone(),
712                direction: *direction,
713            })
714            .collect(),
715    )
716}
717
718const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
719    match page {
720        Some(page) => ExplainPagination::Page {
721            limit: page.limit,
722            offset: page.offset,
723        },
724        None => ExplainPagination::None,
725    }
726}
727
728const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
729    match limit {
730        Some(limit) => ExplainDeleteLimit::Limit {
731            max_rows: limit.max_rows,
732        },
733        None => ExplainDeleteLimit::None,
734    }
735}
736
737fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
738    let mut object = JsonWriter::begin_object(out);
739    object.field_with("mode", |out| write_query_mode_json(explain.mode(), out));
740    object.field_with("access", |out| write_access_json(explain.access(), out));
741    object.field_value_debug("predicate", explain.predicate());
742    object.field_value_debug("order_by", explain.order_by());
743    object.field_bool("distinct", explain.distinct());
744    object.field_value_debug("grouping", explain.grouping());
745    object.field_value_debug("order_pushdown", explain.order_pushdown());
746    object.field_with("page", |out| write_pagination_json(explain.page(), out));
747    object.field_with("delete_limit", |out| {
748        write_delete_limit_json(explain.delete_limit(), out);
749    });
750    object.field_value_debug("consistency", &explain.consistency());
751    object.finish();
752}
753
754fn write_query_mode_json(mode: QueryMode, out: &mut String) {
755    let mut object = JsonWriter::begin_object(out);
756    match mode {
757        QueryMode::Load(spec) => {
758            object.field_str("type", "Load");
759            match spec.limit() {
760                Some(limit) => object.field_u64("limit", u64::from(limit)),
761                None => object.field_null("limit"),
762            }
763            object.field_u64("offset", u64::from(spec.offset()));
764        }
765        QueryMode::Delete(spec) => {
766            object.field_str("type", "Delete");
767            match spec.limit() {
768                Some(limit) => object.field_u64("limit", u64::from(limit)),
769                None => object.field_null("limit"),
770            }
771        }
772    }
773    object.finish();
774}
775
776fn write_pagination_json(page: &ExplainPagination, out: &mut String) {
777    let mut object = JsonWriter::begin_object(out);
778    match page {
779        ExplainPagination::None => {
780            object.field_str("type", "None");
781        }
782        ExplainPagination::Page { limit, offset } => {
783            object.field_str("type", "Page");
784            match limit {
785                Some(limit) => object.field_u64("limit", u64::from(*limit)),
786                None => object.field_null("limit"),
787            }
788            object.field_u64("offset", u64::from(*offset));
789        }
790    }
791    object.finish();
792}
793
794fn write_delete_limit_json(limit: &ExplainDeleteLimit, out: &mut String) {
795    let mut object = JsonWriter::begin_object(out);
796    match limit {
797        ExplainDeleteLimit::None => {
798            object.field_str("type", "None");
799        }
800        ExplainDeleteLimit::Limit { max_rows } => {
801            object.field_str("type", "Limit");
802            object.field_u64("max_rows", u64::from(*max_rows));
803        }
804    }
805    object.finish();
806}