Skip to main content

icydb_core/db/query/explain/
plan.rs

1//! Module: query::explain::plan
2//! Responsibility: deterministic planned-query projection for EXPLAIN,
3//! including logical shape, access shape, and pushdown observability.
4//! Does not own: execution descriptor rendering or access visitor adapters.
5//! Boundary: explain DTOs and plan-side projection logic for query observability.
6
7use crate::{
8    db::KeyValueCodec,
9    db::{
10        access::AccessPlan,
11        predicate::{CoercionSpec, CompareOp, ComparePredicate, MissingRowPolicy, Predicate},
12        query::{
13            builder::scalar_projection::render_scalar_projection_expr_plan_label,
14            explain::{
15                access_projection::write_access_json_detailed, explain_access_plan,
16                writer::JsonWriter,
17            },
18            plan::{
19                AccessChoiceCandidateExplainSummary, AccessChoiceExplainSnapshot,
20                AccessChoiceRejectedIndex, AccessChoiceResidualBurden, AccessPlannedQuery,
21                AggregateKind, DeleteLimitSpec, GroupedPlanAggregateFamily,
22                GroupedPlanFallbackReason, GroupedPlanStrategy, LogicalPlan, OrderDirection,
23                OrderSpec, PageSpec, QueryMode, ScalarPlan, explain_access_strategy_label,
24                expr::Expr, grouped_plan_strategy, render_scalar_filter_expr_plan_label,
25            },
26        },
27    },
28    value::Value,
29};
30use std::{fmt, ops::Bound};
31
32///
33/// ExplainPlan
34///
35/// Stable, deterministic representation of a planned query for observability.
36///
37
38#[derive(Clone, Eq, PartialEq)]
39pub struct ExplainPlan {
40    pub(in crate::db) mode: QueryMode,
41    pub(in crate::db) access: ExplainAccessPath,
42    pub(in crate::db) access_decision: ExplainAccessDecision,
43    pub(in crate::db) filter_expr: Option<String>,
44    filter_expr_model: Option<Expr>,
45    pub(in crate::db) predicate: ExplainPredicate,
46    predicate_model: Option<Predicate>,
47    pub(in crate::db) order_by: ExplainOrderBy,
48    pub(in crate::db) distinct: bool,
49    pub(in crate::db) grouping: ExplainGrouping,
50    pub(in crate::db) order_pushdown: ExplainOrderPushdown,
51    pub(in crate::db) page: ExplainPagination,
52    pub(in crate::db) delete_limit: ExplainDeleteLimit,
53    pub(in crate::db) consistency: MissingRowPolicy,
54}
55
56#[expect(clippy::missing_fields_in_debug)]
57impl fmt::Debug for ExplainPlan {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.debug_struct("ExplainPlan")
60            .field("mode", &self.mode)
61            .field("access", &self.access)
62            .field("filter_expr", &self.filter_expr)
63            .field("filter_expr_model", &self.filter_expr_model)
64            .field("predicate", &self.predicate)
65            .field("predicate_model", &self.predicate_model)
66            .field("order_by", &self.order_by)
67            .field("distinct", &self.distinct)
68            .field("grouping", &self.grouping)
69            .field("order_pushdown", &self.order_pushdown)
70            .field("page", &self.page)
71            .field("delete_limit", &self.delete_limit)
72            .field("consistency", &self.consistency)
73            .finish()
74    }
75}
76
77impl ExplainPlan {
78    /// Return query mode projected by this explain plan.
79    #[must_use]
80    pub const fn mode(&self) -> QueryMode {
81        self.mode
82    }
83
84    /// Borrow projected access-path shape.
85    #[must_use]
86    pub const fn access(&self) -> &ExplainAccessPath {
87        &self.access
88    }
89
90    /// Borrow the structured planner access-decision projection.
91    #[must_use]
92    pub const fn access_decision(&self) -> &ExplainAccessDecision {
93        &self.access_decision
94    }
95
96    /// Borrow projected semantic scalar filter expression when present.
97    #[must_use]
98    pub fn filter_expr(&self) -> Option<&str> {
99        self.filter_expr.as_deref()
100    }
101
102    /// Borrow the canonical scalar filter model used for identity hashing.
103    #[must_use]
104    pub(in crate::db::query) fn filter_expr_model_for_hash(&self) -> Option<&Expr> {
105        if let Some(filter_expr_model) = &self.filter_expr_model {
106            debug_assert_eq!(
107                self.filter_expr(),
108                Some(render_scalar_filter_expr_plan_label(filter_expr_model).as_str()),
109                "explain scalar filter label drifted from canonical filter model"
110            );
111            Some(filter_expr_model)
112        } else {
113            debug_assert!(
114                self.filter_expr.is_none(),
115                "missing canonical filter model requires filter_expr=None"
116            );
117            None
118        }
119    }
120
121    /// Borrow projected predicate shape.
122    #[must_use]
123    pub const fn predicate(&self) -> &ExplainPredicate {
124        &self.predicate
125    }
126
127    /// Borrow projected ORDER BY shape.
128    #[must_use]
129    pub const fn order_by(&self) -> &ExplainOrderBy {
130        &self.order_by
131    }
132
133    /// Return whether DISTINCT is enabled.
134    #[must_use]
135    pub const fn distinct(&self) -> bool {
136        self.distinct
137    }
138
139    /// Borrow projected grouped-shape metadata.
140    #[must_use]
141    pub const fn grouping(&self) -> &ExplainGrouping {
142        &self.grouping
143    }
144
145    /// Borrow projected ORDER pushdown status.
146    #[must_use]
147    pub const fn order_pushdown(&self) -> &ExplainOrderPushdown {
148        &self.order_pushdown
149    }
150
151    /// Borrow projected pagination status.
152    #[must_use]
153    pub const fn page(&self) -> &ExplainPagination {
154        &self.page
155    }
156
157    /// Borrow projected delete-limit status.
158    #[must_use]
159    pub const fn delete_limit(&self) -> &ExplainDeleteLimit {
160        &self.delete_limit
161    }
162
163    /// Return missing-row consistency policy.
164    #[must_use]
165    pub const fn consistency(&self) -> MissingRowPolicy {
166        self.consistency
167    }
168}
169
170impl ExplainPlan {
171    /// Return the canonical predicate model used as the fallback hash surface.
172    ///
173    /// When a semantic scalar `filter_expr` exists, hashing now prefers that
174    /// canonical filter surface instead. The explain predicate projection must
175    /// still remain a faithful rendering of this fallback model.
176    #[must_use]
177    pub(in crate::db::query) fn predicate_model_for_hash(&self) -> Option<&Predicate> {
178        if let Some(predicate) = &self.predicate_model {
179            debug_assert_eq!(
180                self.predicate,
181                ExplainPredicate::from_predicate(predicate),
182                "explain predicate surface drifted from canonical predicate model"
183            );
184            Some(predicate)
185        } else {
186            debug_assert!(
187                matches!(self.predicate, ExplainPredicate::None),
188                "missing canonical predicate model requires ExplainPredicate::None"
189            );
190            None
191        }
192    }
193
194    /// Render this logical explain plan as deterministic canonical text.
195    ///
196    /// This surface is frontend-facing and intentionally stable for SQL/CLI
197    /// explain output and snapshot-style diagnostics.
198    #[must_use]
199    pub fn render_text_canonical(&self) -> String {
200        format!(
201            concat!(
202                "mode={:?}\n",
203                "access={:?}\n",
204                "access_decision={}\n",
205                "filter_expr={:?}\n",
206                "predicate={:?}\n",
207                "order_by={:?}\n",
208                "distinct={}\n",
209                "grouping={:?}\n",
210                "order_pushdown={:?}\n",
211                "page={:?}\n",
212                "delete_limit={:?}\n",
213                "consistency={:?}",
214            ),
215            self.mode(),
216            self.access(),
217            self.access_decision().render_compact_summary(),
218            self.filter_expr(),
219            self.predicate(),
220            self.order_by(),
221            self.distinct(),
222            self.grouping(),
223            self.order_pushdown(),
224            self.page(),
225            self.delete_limit(),
226            self.consistency(),
227        )
228    }
229
230    /// Render this logical explain plan as canonical JSON.
231    #[must_use]
232    pub fn render_json_canonical(&self) -> String {
233        let mut out = String::new();
234        write_logical_explain_json(self, &mut out);
235
236        out
237    }
238}
239
240///
241/// ExplainGrouping
242///
243/// Grouped-shape annotation for deterministic explain/fingerprint surfaces.
244///
245
246#[derive(Clone, Debug, Eq, PartialEq)]
247pub enum ExplainGrouping {
248    None,
249    Grouped {
250        strategy: &'static str,
251        fallback_reason: Option<&'static str>,
252        group_fields: Vec<ExplainGroupField>,
253        aggregates: Vec<ExplainGroupAggregate>,
254        having: Option<ExplainGroupHaving>,
255        max_groups: u64,
256        max_group_bytes: u64,
257    },
258}
259
260///
261/// ExplainGroupField
262///
263/// Stable grouped-key field identity carried by explain/hash surfaces.
264///
265
266#[derive(Clone, Debug, Eq, PartialEq)]
267pub struct ExplainGroupField {
268    pub(in crate::db) slot_index: usize,
269    pub(in crate::db) field: String,
270}
271
272impl ExplainGroupField {
273    /// Return grouped slot index.
274    #[must_use]
275    pub const fn slot_index(&self) -> usize {
276        self.slot_index
277    }
278
279    /// Borrow grouped field name.
280    #[must_use]
281    pub const fn field(&self) -> &str {
282        self.field.as_str()
283    }
284}
285
286///
287/// ExplainGroupAggregate
288///
289/// Stable explain-surface projection of one grouped aggregate terminal.
290///
291
292#[derive(Clone, Debug, Eq, PartialEq)]
293pub struct ExplainGroupAggregate {
294    pub(in crate::db) kind: AggregateKind,
295    pub(in crate::db) target_field: Option<String>,
296    pub(in crate::db) input_expr: Option<String>,
297    pub(in crate::db) filter_expr: Option<String>,
298    pub(in crate::db) distinct: bool,
299}
300
301impl ExplainGroupAggregate {
302    /// Return grouped aggregate kind.
303    #[must_use]
304    pub const fn kind(&self) -> AggregateKind {
305        self.kind
306    }
307
308    /// Borrow optional grouped aggregate target field.
309    #[must_use]
310    pub fn target_field(&self) -> Option<&str> {
311        self.target_field.as_deref()
312    }
313
314    /// Borrow optional grouped aggregate input expression label.
315    #[must_use]
316    pub fn input_expr(&self) -> Option<&str> {
317        self.input_expr.as_deref()
318    }
319
320    /// Borrow optional grouped aggregate filter expression label.
321    #[must_use]
322    pub fn filter_expr(&self) -> Option<&str> {
323        self.filter_expr.as_deref()
324    }
325
326    /// Return whether grouped aggregate uses DISTINCT input semantics.
327    #[must_use]
328    pub const fn distinct(&self) -> bool {
329        self.distinct
330    }
331}
332
333///
334/// ExplainGroupHaving
335///
336/// Deterministic explain projection of grouped HAVING clauses.
337/// This surface now carries the shared planner-owned post-aggregate expression
338/// directly so explain no longer keeps a second grouped HAVING AST.
339///
340
341#[derive(Clone, Debug, Eq, PartialEq)]
342pub struct ExplainGroupHaving {
343    pub(in crate::db) expr: Expr,
344}
345
346impl ExplainGroupHaving {
347    /// Borrow grouped HAVING expression.
348    #[must_use]
349    pub(in crate::db) const fn expr(&self) -> &Expr {
350        &self.expr
351    }
352}
353
354///
355/// ExplainOrderPushdown
356///
357/// Deterministic ORDER BY pushdown eligibility reported by explain.
358///
359
360#[derive(Clone, Debug, Eq, PartialEq)]
361pub enum ExplainOrderPushdown {
362    MissingModelContext,
363    EligibleSecondaryIndex { index: String, prefix_len: usize },
364    Rejected(SecondaryOrderPushdownRejection),
365}
366
367///
368/// SecondaryOrderPushdownRejection
369///
370/// Stable explain-surface reason why secondary-index ORDER BY pushdown was
371/// rejected. Executor route planning converts its runtime route reasons into
372/// this neutral query DTO before rendering explain payloads.
373///
374#[derive(Clone, Debug, Eq, PartialEq)]
375pub enum SecondaryOrderPushdownRejection {
376    NoOrderBy,
377    AccessPathNotSingleIndexPrefix,
378    AccessPathIndexRangeUnsupported {
379        index: String,
380        prefix_len: usize,
381    },
382    InvalidIndexPrefixBounds {
383        prefix_len: usize,
384        index_field_len: usize,
385    },
386    MissingPrimaryKeyTieBreak {
387        field: String,
388    },
389    PrimaryKeyDirectionNotAscending {
390        field: String,
391    },
392    MixedDirectionNotEligible {
393        field: String,
394    },
395    OrderFieldsDoNotMatchIndex {
396        index: String,
397        prefix_len: usize,
398        expected_suffix: Vec<String>,
399        expected_full: Vec<String>,
400        actual: Vec<String>,
401    },
402    VariablePrefixSuffixOrderUnsupported {
403        index: String,
404        prefix_len: usize,
405        expected_full: Vec<String>,
406        actual: Vec<String>,
407    },
408}
409
410///
411/// ExplainAccessPath
412///
413/// Deterministic projection of logical access path shape for diagnostics.
414/// Mirrors planner-selected structural paths without runtime cursor state.
415///
416
417#[derive(Clone, Debug, Eq, PartialEq)]
418pub enum ExplainAccessPath {
419    ByKey {
420        key: Value,
421    },
422    ByKeys {
423        keys: Vec<Value>,
424    },
425    KeyRange {
426        start: Value,
427        end: Value,
428    },
429    IndexPrefix {
430        name: String,
431        fields: Vec<String>,
432        prefix_len: usize,
433        values: Vec<Value>,
434    },
435    IndexMultiLookup {
436        name: String,
437        fields: Vec<String>,
438        values: Vec<Value>,
439    },
440    IndexBranchSet {
441        name: String,
442        fields: Vec<String>,
443        fixed_values: Vec<Value>,
444        branch_values: Vec<Value>,
445        branch_field: Option<String>,
446        ordered_suffix: String,
447    },
448    IndexRange {
449        name: String,
450        fields: Vec<String>,
451        prefix_len: usize,
452        prefix: Vec<Value>,
453        lower: Bound<Value>,
454        upper: Bound<Value>,
455    },
456    FullScan,
457    Union(Vec<Self>),
458    Intersection(Vec<Self>),
459}
460
461/// Stable JSON-facing access-decision projection for logical EXPLAIN.
462///
463/// This DTO is derived from the planner-owned access-choice snapshot and the
464/// selected explain access path. It is not an optimizer model and does not
465/// participate in access selection.
466#[derive(Clone, Debug, Eq, PartialEq)]
467pub struct ExplainAccessDecision {
468    /// Selected access path summary.
469    pub selected: ExplainSelectedAccess,
470    /// Planner candidate summaries recorded for the selected access family.
471    pub candidates: Vec<ExplainAccessCandidate>,
472    /// Eligible alternatives not selected by the planner.
473    pub alternatives: Vec<ExplainEligibleAlternative>,
474    /// Rejected index candidates and planner-owned reason strings.
475    pub rejections: Vec<ExplainRejectedIndex>,
476    /// Residual-work summary for the selected route when available.
477    pub residual: ExplainResidualSummary,
478}
479
480impl ExplainAccessDecision {
481    fn from_snapshot(
482        selected_access: &ExplainAccessPath,
483        snapshot: &AccessChoiceExplainSnapshot,
484    ) -> Self {
485        let selected_label = explain_access_strategy_label(selected_access);
486        let selected_candidate =
487            selected_candidate_summary(selected_index_name(selected_access), &snapshot.candidates);
488
489        Self {
490            selected: ExplainSelectedAccess {
491                kind: ExplainAccessDecisionKind::from_access_path(selected_access),
492                index_name: selected_index_name(selected_access).map(ToOwned::to_owned),
493                label: selected_label,
494                reason: snapshot.chosen_reason().code(),
495            },
496            candidates: snapshot
497                .candidates
498                .iter()
499                .map(ExplainAccessCandidate::from_candidate)
500                .collect(),
501            alternatives: snapshot
502                .alternatives
503                .iter()
504                .map(|index_name| ExplainEligibleAlternative {
505                    index_name: index_name.clone(),
506                })
507                .collect(),
508            rejections: snapshot
509                .rejected
510                .iter()
511                .map(ExplainRejectedIndex::from_rejection)
512                .collect(),
513            residual: ExplainResidualSummary::from_selected_access_and_candidate(
514                selected_access,
515                selected_candidate,
516            ),
517        }
518    }
519
520    fn render_compact_summary(&self) -> String {
521        let index = self
522            .selected
523            .index_name
524            .as_deref()
525            .map_or("none", |index| index);
526
527        format!(
528            "kind={} index={} reason={} residual={} candidates={} alternatives={} rejections={}",
529            self.selected.kind.code(),
530            index,
531            self.selected.reason,
532            self.residual.burden_class,
533            self.candidates.len(),
534            self.alternatives.len(),
535            self.rejections.len(),
536        )
537    }
538}
539
540/// Selected access path summary inside an access-decision explain payload.
541#[derive(Clone, Debug, Eq, PartialEq)]
542pub struct ExplainSelectedAccess {
543    /// Selected access kind.
544    pub kind: ExplainAccessDecisionKind,
545    /// Selected semantic index name, when the selected route is index-backed.
546    pub index_name: Option<String>,
547    /// Planner access label used for candidate matching and diagnostics.
548    pub label: String,
549    /// Planner-owned selected reason code.
550    pub reason: &'static str,
551}
552
553/// Stable access-kind code used by the access-decision explain payload.
554#[derive(Clone, Copy, Debug, Eq, PartialEq)]
555pub enum ExplainAccessDecisionKind {
556    /// Direct primary-key lookup.
557    ByKey,
558    /// Multiple primary-key lookup.
559    ByKeys,
560    /// Primary-key range lookup.
561    KeyRange,
562    /// Secondary-index equality prefix lookup.
563    IndexPrefix,
564    /// Secondary-index multi-value lookup.
565    IndexMultiLookup,
566    /// Branch-aware secondary-index composite prefix lookup.
567    IndexBranchSet,
568    /// Secondary-index range lookup.
569    IndexRange,
570    /// Full entity scan.
571    FullScan,
572    /// Union access route.
573    Union,
574    /// Intersection access route.
575    Intersection,
576}
577
578impl ExplainAccessDecisionKind {
579    const fn from_access_path(access: &ExplainAccessPath) -> Self {
580        match access {
581            ExplainAccessPath::ByKey { .. } => Self::ByKey,
582            ExplainAccessPath::ByKeys { .. } => Self::ByKeys,
583            ExplainAccessPath::KeyRange { .. } => Self::KeyRange,
584            ExplainAccessPath::IndexPrefix { .. } => Self::IndexPrefix,
585            ExplainAccessPath::IndexMultiLookup { .. } => Self::IndexMultiLookup,
586            ExplainAccessPath::IndexBranchSet { .. } => Self::IndexBranchSet,
587            ExplainAccessPath::IndexRange { .. } => Self::IndexRange,
588            ExplainAccessPath::FullScan => Self::FullScan,
589            ExplainAccessPath::Union(_) => Self::Union,
590            ExplainAccessPath::Intersection(_) => Self::Intersection,
591        }
592    }
593
594    const fn code(self) -> &'static str {
595        match self {
596            Self::ByKey => "ByKey",
597            Self::ByKeys => "ByKeys",
598            Self::KeyRange => "KeyRange",
599            Self::IndexPrefix => "IndexPrefix",
600            Self::IndexMultiLookup => "IndexMultiLookup",
601            Self::IndexBranchSet => "IndexBranchSet",
602            Self::IndexRange => "IndexRange",
603            Self::FullScan => "FullScan",
604            Self::Union => "Union",
605            Self::Intersection => "Intersection",
606        }
607    }
608}
609
610/// Candidate summary recorded by the planner access-choice snapshot.
611#[derive(Clone, Debug, Eq, PartialEq)]
612pub struct ExplainAccessCandidate {
613    /// Planner access label for the candidate route.
614    pub label: String,
615    /// Whether the candidate structurally satisfied all usable predicates.
616    pub exact: bool,
617    /// Whether the candidate uses a filtered index contract.
618    pub filtered: bool,
619    /// Number of range-bound fields recorded by the planner scorer.
620    pub range_bound_count: usize,
621    /// Whether candidate ordering is compatible with query ordering.
622    pub order_compatible: bool,
623    /// Residual burden class recorded by the planner.
624    pub residual_burden: &'static str,
625    /// Number of residual predicate terms recorded by the planner.
626    pub residual_predicate_terms: usize,
627}
628
629impl ExplainAccessCandidate {
630    fn from_candidate(candidate: &AccessChoiceCandidateExplainSummary) -> Self {
631        Self {
632            label: candidate.label(),
633            exact: candidate.exact,
634            filtered: candidate.filtered,
635            range_bound_count: candidate.range_bound_count,
636            order_compatible: candidate.order_compatible,
637            residual_burden: candidate.residual_burden.label(),
638            residual_predicate_terms: candidate.residual_predicate_terms,
639        }
640    }
641}
642
643/// Eligible alternative index name recorded by the planner.
644#[derive(Clone, Debug, Eq, PartialEq)]
645pub struct ExplainEligibleAlternative {
646    /// Semantic index name of the eligible alternative.
647    pub index_name: String,
648}
649
650/// Rejected index candidate summary recorded by the planner.
651#[derive(Clone, Debug, Eq, PartialEq)]
652pub struct ExplainRejectedIndex {
653    /// Semantic index name carried by the planner rejection.
654    pub index_name: Option<String>,
655    /// Planner-owned rejection reason code.
656    pub reason: Option<String>,
657    /// Stable rendered planner rejection label.
658    pub label: String,
659}
660
661impl ExplainRejectedIndex {
662    fn from_rejection(rejection: &AccessChoiceRejectedIndex) -> Self {
663        Self {
664            index_name: Some(rejection.index_name().to_string()),
665            reason: Some(rejection.reason_code().to_string()),
666            label: rejection.label(),
667        }
668    }
669}
670
671/// Residual-work summary for the selected access route.
672#[derive(Clone, Debug, Eq, PartialEq)]
673pub struct ExplainResidualSummary {
674    /// Residual burden class for the selected access route.
675    pub burden_class: &'static str,
676    /// Whether any residual scalar filter expression survives access planning.
677    pub has_residual_filter: bool,
678    /// Whether any residual predicate model survives access planning.
679    pub has_residual_predicate: bool,
680    /// Number of predicate-like constraints structurally consumed by access.
681    pub access_bound_predicate_count: usize,
682    /// Number of residual predicate terms for the selected access route.
683    pub residual_predicate_count: usize,
684}
685
686impl ExplainResidualSummary {
687    fn from_selected_access_and_candidate(
688        selected_access: &ExplainAccessPath,
689        selected_candidate: Option<&AccessChoiceCandidateExplainSummary>,
690    ) -> Self {
691        match selected_candidate {
692            Some(candidate) => Self {
693                burden_class: candidate.residual_burden.label(),
694                has_residual_filter: matches!(
695                    candidate.residual_burden,
696                    AccessChoiceResidualBurden::ScalarExpression
697                ),
698                has_residual_predicate: candidate.residual_predicate_terms > 0,
699                access_bound_predicate_count: access_bound_predicate_count(selected_access),
700                residual_predicate_count: candidate.residual_predicate_terms,
701            },
702            None => Self {
703                burden_class: AccessChoiceResidualBurden::None.label(),
704                has_residual_filter: false,
705                has_residual_predicate: false,
706                access_bound_predicate_count: access_bound_predicate_count(selected_access),
707                residual_predicate_count: 0,
708            },
709        }
710    }
711}
712
713///
714/// ExplainPredicate
715///
716/// Deterministic projection of canonical predicate structure for explain output.
717/// This preserves normalized predicate shape used by hashing/fingerprints.
718///
719
720#[derive(Clone, Debug, Eq, PartialEq)]
721pub enum ExplainPredicate {
722    None,
723    True,
724    False,
725    And(Vec<Self>),
726    Or(Vec<Self>),
727    Not(Box<Self>),
728    Compare {
729        field: String,
730        op: CompareOp,
731        value: Value,
732        coercion: CoercionSpec,
733    },
734    CompareFields {
735        left_field: String,
736        op: CompareOp,
737        right_field: String,
738        coercion: CoercionSpec,
739    },
740    IsNull {
741        field: String,
742    },
743    IsNotNull {
744        field: String,
745    },
746    IsMissing {
747        field: String,
748    },
749    IsEmpty {
750        field: String,
751    },
752    IsNotEmpty {
753        field: String,
754    },
755    TextContains {
756        field: String,
757        value: Value,
758    },
759    TextContainsCi {
760        field: String,
761        value: Value,
762    },
763}
764
765///
766/// ExplainOrderBy
767///
768/// Deterministic projection of canonical ORDER BY shape.
769///
770
771#[derive(Clone, Debug, Eq, PartialEq)]
772pub enum ExplainOrderBy {
773    None,
774    Fields(Vec<ExplainOrder>),
775}
776
777///
778/// ExplainOrder
779///
780/// One canonical ORDER BY field + direction pair.
781///
782
783#[derive(Clone, Debug, Eq, PartialEq)]
784pub struct ExplainOrder {
785    pub(in crate::db) field: String,
786    pub(in crate::db) direction: OrderDirection,
787}
788
789impl ExplainOrder {
790    /// Borrow ORDER BY field name.
791    #[must_use]
792    pub const fn field(&self) -> &str {
793        self.field.as_str()
794    }
795
796    /// Return ORDER BY direction.
797    #[must_use]
798    pub const fn direction(&self) -> OrderDirection {
799        self.direction
800    }
801}
802
803///
804/// ExplainPagination
805///
806/// Explain-surface projection of pagination window configuration.
807///
808
809#[derive(Clone, Debug, Eq, PartialEq)]
810pub enum ExplainPagination {
811    None,
812    Page { limit: Option<u32>, offset: u32 },
813}
814
815///
816/// ExplainDeleteLimit
817///
818/// Explain-surface projection of delete-limit configuration.
819///
820
821#[derive(Clone, Debug, Eq, PartialEq)]
822pub enum ExplainDeleteLimit {
823    None,
824    Limit { max_rows: u32 },
825    Window { limit: Option<u32>, offset: u32 },
826}
827
828impl AccessPlannedQuery {
829    /// Produce a stable, deterministic explanation of this logical plan.
830    #[must_use]
831    pub(in crate::db) fn explain(&self) -> ExplainPlan {
832        self.explain_inner()
833    }
834
835    fn explain_inner(&self) -> ExplainPlan {
836        // Phase 1: project logical plan variant into scalar core + grouped metadata.
837        let (logical, grouping) = match &self.logical {
838            LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
839            LogicalPlan::Grouped(logical) => {
840                let grouped_strategy = grouped_plan_strategy(self).unwrap_or_else(|| {
841                    debug_assert!(
842                        grouped_plan_strategy(self).is_some(),
843                        "grouped logical explain projection requires planner-owned grouped strategy",
844                    );
845                    GroupedPlanStrategy::hash_group_with_aggregate_family(
846                        GroupedPlanFallbackReason::GroupKeyOrderUnavailable,
847                        GroupedPlanAggregateFamily::from_grouped_aggregates(
848                            logical.group.aggregates.as_slice(),
849                        ),
850                    )
851                });
852
853                (
854                    &logical.scalar,
855                    ExplainGrouping::Grouped {
856                        strategy: grouped_strategy.code(),
857                        fallback_reason: grouped_strategy
858                            .fallback_reason()
859                            .map(GroupedPlanFallbackReason::code),
860                        group_fields: logical
861                            .group
862                            .group_fields
863                            .iter()
864                            .map(|field_slot| ExplainGroupField {
865                                slot_index: field_slot.index(),
866                                field: field_slot.field().to_string(),
867                            })
868                            .collect(),
869                        aggregates: logical
870                            .group
871                            .aggregates
872                            .iter()
873                            .map(|aggregate| ExplainGroupAggregate {
874                                kind: aggregate.kind,
875                                target_field: aggregate.target_field().map(str::to_string),
876                                input_expr: aggregate
877                                    .input_expr()
878                                    .map(render_scalar_projection_expr_plan_label),
879                                filter_expr: aggregate
880                                    .filter_expr()
881                                    .map(render_scalar_projection_expr_plan_label),
882                                distinct: aggregate.distinct,
883                            })
884                            .collect(),
885                        having: explain_group_having(logical),
886                        max_groups: logical.group.execution.max_groups(),
887                        max_group_bytes: logical.group.execution.max_group_bytes(),
888                    },
889                )
890            }
891        };
892
893        // Phase 2: project scalar plan + access path into deterministic explain surface.
894        explain_scalar_inner(logical, grouping, &self.access, self.access_choice())
895    }
896}
897
898fn explain_group_having(logical: &crate::db::query::plan::GroupPlan) -> Option<ExplainGroupHaving> {
899    let expr = logical.effective_having_expr()?;
900
901    Some(ExplainGroupHaving {
902        expr: expr.into_owned(),
903    })
904}
905
906fn explain_scalar_inner<K>(
907    logical: &ScalarPlan,
908    grouping: ExplainGrouping,
909    access: &AccessPlan<K>,
910    access_choice: &AccessChoiceExplainSnapshot,
911) -> ExplainPlan
912where
913    K: KeyValueCodec,
914{
915    // Phase 1: consume canonical predicate model from planner-owned scalar semantics.
916    let filter_expr = logical
917        .filter_expr
918        .as_ref()
919        .map(render_scalar_filter_expr_plan_label);
920    let filter_expr_model = logical.filter_expr.clone();
921    let predicate_model = logical.predicate.clone();
922    let predicate = match &predicate_model {
923        Some(predicate) => ExplainPredicate::from_predicate(predicate),
924        None => ExplainPredicate::None,
925    };
926
927    // Phase 2: project scalar-plan fields into explain-specific enums.
928    let order_by = explain_order(logical.order.as_ref());
929    let order_pushdown = explain_order_pushdown();
930    let page = explain_page(logical.page.as_ref());
931    let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
932
933    // Phase 3: assemble one stable explain payload.
934    let access = explain_access_plan(access);
935    let access_decision = ExplainAccessDecision::from_snapshot(&access, access_choice);
936
937    ExplainPlan {
938        mode: logical.mode,
939        access,
940        access_decision,
941        filter_expr,
942        filter_expr_model,
943        predicate,
944        predicate_model,
945        order_by,
946        distinct: logical.distinct,
947        grouping,
948        order_pushdown,
949        page,
950        delete_limit,
951        consistency: logical.consistency,
952    }
953}
954
955fn selected_candidate_summary<'a>(
956    selected_index_name: Option<&str>,
957    candidates: &'a [AccessChoiceCandidateExplainSummary],
958) -> Option<&'a AccessChoiceCandidateExplainSummary> {
959    let selected_index_name = selected_index_name?;
960
961    candidates
962        .iter()
963        .find(|candidate| candidate.index_name() == selected_index_name)
964}
965
966const fn selected_index_name(access: &ExplainAccessPath) -> Option<&str> {
967    match access {
968        ExplainAccessPath::IndexPrefix { name, .. }
969        | ExplainAccessPath::IndexMultiLookup { name, .. }
970        | ExplainAccessPath::IndexBranchSet { name, .. }
971        | ExplainAccessPath::IndexRange { name, .. } => Some(name.as_str()),
972        ExplainAccessPath::ByKey { .. }
973        | ExplainAccessPath::ByKeys { .. }
974        | ExplainAccessPath::KeyRange { .. }
975        | ExplainAccessPath::FullScan
976        | ExplainAccessPath::Union(_)
977        | ExplainAccessPath::Intersection(_) => None,
978    }
979}
980
981fn access_bound_predicate_count(access: &ExplainAccessPath) -> usize {
982    match access {
983        ExplainAccessPath::ByKey { .. }
984        | ExplainAccessPath::ByKeys { .. }
985        | ExplainAccessPath::IndexMultiLookup { .. } => 1,
986        ExplainAccessPath::IndexBranchSet {
987            fixed_values,
988            branch_values,
989            ..
990        } => fixed_values.len() + usize::from(!branch_values.is_empty()),
991        ExplainAccessPath::KeyRange { .. } => 2,
992        ExplainAccessPath::IndexPrefix { prefix_len, .. } => *prefix_len,
993        ExplainAccessPath::IndexRange {
994            prefix_len,
995            lower,
996            upper,
997            ..
998        } => *prefix_len + bound_constraint_count(lower) + bound_constraint_count(upper),
999        ExplainAccessPath::FullScan => 0,
1000        ExplainAccessPath::Union(children) | ExplainAccessPath::Intersection(children) => {
1001            children.iter().map(access_bound_predicate_count).sum()
1002        }
1003    }
1004}
1005
1006const fn bound_constraint_count(bound: &Bound<Value>) -> usize {
1007    match bound {
1008        Bound::Included(_) | Bound::Excluded(_) => 1,
1009        Bound::Unbounded => 0,
1010    }
1011}
1012
1013const fn explain_order_pushdown() -> ExplainOrderPushdown {
1014    // Query explain does not own physical pushdown feasibility routing.
1015    ExplainOrderPushdown::MissingModelContext
1016}
1017
1018impl ExplainPredicate {
1019    pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
1020        match predicate {
1021            Predicate::True => Self::True,
1022            Predicate::False => Self::False,
1023            Predicate::And(children) => {
1024                Self::And(children.iter().map(Self::from_predicate).collect())
1025            }
1026            Predicate::Or(children) => {
1027                Self::Or(children.iter().map(Self::from_predicate).collect())
1028            }
1029            Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
1030            Predicate::Compare(compare) => Self::from_compare(compare),
1031            Predicate::CompareFields(compare) => Self::CompareFields {
1032                left_field: compare.left_field().to_string(),
1033                op: compare.op(),
1034                right_field: compare.right_field().to_string(),
1035                coercion: compare.coercion().clone(),
1036            },
1037            Predicate::IsNull { field } => Self::IsNull {
1038                field: field.clone(),
1039            },
1040            Predicate::IsNotNull { field } => Self::IsNotNull {
1041                field: field.clone(),
1042            },
1043            Predicate::IsMissing { field } => Self::IsMissing {
1044                field: field.clone(),
1045            },
1046            Predicate::IsEmpty { field } => Self::IsEmpty {
1047                field: field.clone(),
1048            },
1049            Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
1050                field: field.clone(),
1051            },
1052            Predicate::TextContains { field, value } => Self::TextContains {
1053                field: field.clone(),
1054                value: value.clone(),
1055            },
1056            Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
1057                field: field.clone(),
1058                value: value.clone(),
1059            },
1060        }
1061    }
1062
1063    fn from_compare(compare: &ComparePredicate) -> Self {
1064        Self::Compare {
1065            field: compare.field.clone(),
1066            op: compare.op,
1067            value: compare.value.clone(),
1068            coercion: compare.coercion.clone(),
1069        }
1070    }
1071}
1072
1073fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
1074    let Some(order) = order else {
1075        return ExplainOrderBy::None;
1076    };
1077
1078    if order.fields.is_empty() {
1079        return ExplainOrderBy::None;
1080    }
1081
1082    ExplainOrderBy::Fields(
1083        order
1084            .fields
1085            .iter()
1086            .map(|term| ExplainOrder {
1087                field: term.rendered_label(),
1088                direction: term.direction(),
1089            })
1090            .collect(),
1091    )
1092}
1093
1094const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
1095    match page {
1096        Some(page) => ExplainPagination::Page {
1097            limit: page.limit,
1098            offset: page.offset,
1099        },
1100        None => ExplainPagination::None,
1101    }
1102}
1103
1104const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
1105    match limit {
1106        Some(limit) if limit.offset == 0 => match limit.limit {
1107            Some(max_rows) => ExplainDeleteLimit::Limit { max_rows },
1108            None => ExplainDeleteLimit::Window {
1109                limit: None,
1110                offset: 0,
1111            },
1112        },
1113        Some(limit) => ExplainDeleteLimit::Window {
1114            limit: limit.limit,
1115            offset: limit.offset,
1116        },
1117        None => ExplainDeleteLimit::None,
1118    }
1119}
1120
1121fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
1122    let mut object = JsonWriter::begin_object(out);
1123    object.field_with("mode", |out| {
1124        let mut object = JsonWriter::begin_object(out);
1125        match explain.mode() {
1126            QueryMode::Load(spec) => {
1127                object.field_str("type", "Load");
1128                match spec.limit() {
1129                    Some(limit) => object.field_u64("limit", u64::from(limit)),
1130                    None => object.field_null("limit"),
1131                }
1132                object.field_u64("offset", u64::from(spec.offset()));
1133            }
1134            QueryMode::Delete(spec) => {
1135                object.field_str("type", "Delete");
1136                match spec.limit() {
1137                    Some(limit) => object.field_u64("limit", u64::from(limit)),
1138                    None => object.field_null("limit"),
1139                }
1140            }
1141        }
1142        object.finish();
1143    });
1144    object.field_with("access", |out| {
1145        write_access_json_detailed(explain.access(), out);
1146    });
1147    object.field_with("access_decision", |out| {
1148        write_access_decision_json(explain.access_decision(), out);
1149    });
1150    match explain.filter_expr() {
1151        Some(filter_expr) => object.field_str("filter_expr", filter_expr),
1152        None => object.field_null("filter_expr"),
1153    }
1154    object.field_value_debug("predicate", explain.predicate());
1155    object.field_value_debug("order_by", explain.order_by());
1156    object.field_bool("distinct", explain.distinct());
1157    object.field_value_debug("grouping", explain.grouping());
1158    object.field_value_debug("order_pushdown", explain.order_pushdown());
1159    object.field_with("page", |out| {
1160        let mut object = JsonWriter::begin_object(out);
1161        match explain.page() {
1162            ExplainPagination::None => {
1163                object.field_str("type", "None");
1164            }
1165            ExplainPagination::Page { limit, offset } => {
1166                object.field_str("type", "Page");
1167                match limit {
1168                    Some(limit) => object.field_u64("limit", u64::from(*limit)),
1169                    None => object.field_null("limit"),
1170                }
1171                object.field_u64("offset", u64::from(*offset));
1172            }
1173        }
1174        object.finish();
1175    });
1176    object.field_with("delete_limit", |out| {
1177        let mut object = JsonWriter::begin_object(out);
1178        match explain.delete_limit() {
1179            ExplainDeleteLimit::None => {
1180                object.field_str("type", "None");
1181            }
1182            ExplainDeleteLimit::Limit { max_rows } => {
1183                object.field_str("type", "Limit");
1184                object.field_u64("max_rows", u64::from(*max_rows));
1185            }
1186            ExplainDeleteLimit::Window { limit, offset } => {
1187                object.field_str("type", "Window");
1188                object.field_with("limit", |out| match limit {
1189                    Some(limit) => out.push_str(&limit.to_string()),
1190                    None => out.push_str("null"),
1191                });
1192                object.field_u64("offset", u64::from(*offset));
1193            }
1194        }
1195        object.finish();
1196    });
1197    object.field_value_debug("consistency", &explain.consistency());
1198    object.finish();
1199}
1200
1201fn write_access_decision_json(decision: &ExplainAccessDecision, out: &mut String) {
1202    let mut object = JsonWriter::begin_object(out);
1203    object.field_with("selected", |out| {
1204        let mut selected = JsonWriter::begin_object(out);
1205        selected.field_str("kind", decision.selected.kind.code());
1206        match decision.selected.index_name.as_deref() {
1207            Some(index_name) => selected.field_str("index_name", index_name),
1208            None => selected.field_null("index_name"),
1209        }
1210        selected.field_str("label", decision.selected.label.as_str());
1211        selected.field_str("reason", decision.selected.reason);
1212        selected.finish();
1213    });
1214    object.field_with("candidates", |out| {
1215        out.push('[');
1216        for (index, candidate) in decision.candidates.iter().enumerate() {
1217            if index > 0 {
1218                out.push(',');
1219            }
1220            write_access_candidate_json(candidate, out);
1221        }
1222        out.push(']');
1223    });
1224    object.field_with("alternatives", |out| {
1225        out.push('[');
1226        for (index, alternative) in decision.alternatives.iter().enumerate() {
1227            if index > 0 {
1228                out.push(',');
1229            }
1230            let mut object = JsonWriter::begin_object(out);
1231            object.field_str("index_name", alternative.index_name.as_str());
1232            object.finish();
1233        }
1234        out.push(']');
1235    });
1236    object.field_with("rejections", |out| {
1237        out.push('[');
1238        for (index, rejection) in decision.rejections.iter().enumerate() {
1239            if index > 0 {
1240                out.push(',');
1241            }
1242            let mut object = JsonWriter::begin_object(out);
1243            match rejection.index_name.as_deref() {
1244                Some(index_name) => object.field_str("index_name", index_name),
1245                None => object.field_null("index_name"),
1246            }
1247            match rejection.reason.as_deref() {
1248                Some(reason) => object.field_str("reason", reason),
1249                None => object.field_null("reason"),
1250            }
1251            object.field_str("label", rejection.label.as_str());
1252            object.finish();
1253        }
1254        out.push(']');
1255    });
1256    object.field_with("residual", |out| {
1257        let mut residual = JsonWriter::begin_object(out);
1258        residual.field_str("burden_class", decision.residual.burden_class);
1259        residual.field_bool("has_residual_filter", decision.residual.has_residual_filter);
1260        residual.field_bool(
1261            "has_residual_predicate",
1262            decision.residual.has_residual_predicate,
1263        );
1264        residual.field_u64(
1265            "access_bound_predicate_count",
1266            decision.residual.access_bound_predicate_count as u64,
1267        );
1268        residual.field_u64(
1269            "residual_predicate_count",
1270            decision.residual.residual_predicate_count as u64,
1271        );
1272        residual.finish();
1273    });
1274    object.finish();
1275}
1276
1277fn write_access_candidate_json(candidate: &ExplainAccessCandidate, out: &mut String) {
1278    let mut object = JsonWriter::begin_object(out);
1279    object.field_str("label", candidate.label.as_str());
1280    object.field_bool("exact", candidate.exact);
1281    object.field_bool("filtered", candidate.filtered);
1282    object.field_u64("range_bound_count", candidate.range_bound_count as u64);
1283    object.field_bool("order_compatible", candidate.order_compatible);
1284    object.field_str("residual_burden", candidate.residual_burden);
1285    object.field_u64(
1286        "residual_predicate_terms",
1287        candidate.residual_predicate_terms as u64,
1288    );
1289    object.finish();
1290}