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, AccessChoiceSelectedReason,
21                AccessPlannedQuery, 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    },
447    IndexRange {
448        name: String,
449        fields: Vec<String>,
450        prefix_len: usize,
451        prefix: Vec<Value>,
452        lower: Bound<Value>,
453        upper: Bound<Value>,
454    },
455    FullScan,
456    Union(Vec<Self>),
457    Intersection(Vec<Self>),
458}
459
460/// Stable JSON-facing access-decision projection for logical EXPLAIN.
461///
462/// This DTO is derived from the planner-owned access-choice snapshot and the
463/// selected explain access path. It is not an optimizer model and does not
464/// participate in access selection.
465#[derive(Clone, Debug, Eq, PartialEq)]
466pub struct ExplainAccessDecision {
467    /// Selected access path summary.
468    pub selected: ExplainSelectedAccess,
469    /// Planner candidate summaries recorded for the selected access family.
470    pub candidates: Vec<ExplainAccessCandidate>,
471    /// Eligible alternatives not selected by the planner.
472    pub alternatives: Vec<ExplainEligibleAlternative>,
473    /// Rejected index candidates and planner-owned reason strings.
474    pub rejections: Vec<ExplainRejectedIndex>,
475    /// Residual-work summary for the selected route when available.
476    pub residual: ExplainResidualSummary,
477}
478
479impl ExplainAccessDecision {
480    fn from_snapshot(
481        selected_access: &ExplainAccessPath,
482        snapshot: &AccessChoiceExplainSnapshot,
483    ) -> Self {
484        let selected_label = explain_access_strategy_label(selected_access);
485        let selected_candidate =
486            selected_candidate_summary(selected_index_name(selected_access), &snapshot.candidates);
487
488        Self {
489            selected: ExplainSelectedAccess {
490                kind: ExplainAccessDecisionKind::from_access_path(selected_access),
491                index_name: selected_index_name(selected_access).map(ToOwned::to_owned),
492                label: selected_label,
493                reason: snapshot.chosen_reason().code(),
494            },
495            candidates: snapshot
496                .candidates
497                .iter()
498                .map(ExplainAccessCandidate::from_candidate)
499                .collect(),
500            alternatives: snapshot
501                .alternatives
502                .iter()
503                .map(|index_name| ExplainEligibleAlternative {
504                    index_name: index_name.clone(),
505                })
506                .collect(),
507            rejections: snapshot
508                .rejected
509                .iter()
510                .map(ExplainRejectedIndex::from_rejection)
511                .collect(),
512            residual: ExplainResidualSummary::from_selected_access_and_candidate(
513                selected_access,
514                selected_candidate,
515                snapshot.chosen_reason(),
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        selected_reason: AccessChoiceSelectedReason,
691    ) -> Self {
692        if let Some(candidate) = selected_candidate {
693            Self {
694                burden_class: candidate.residual_burden.label(),
695                has_residual_filter: matches!(
696                    candidate.residual_burden,
697                    AccessChoiceResidualBurden::ScalarExpression
698                ),
699                has_residual_predicate: candidate.residual_predicate_terms > 0,
700                access_bound_predicate_count: access_bound_predicate_count(selected_access),
701                residual_predicate_count: candidate.residual_predicate_terms,
702            }
703        } else {
704            let access_bound_predicate_count = access_bound_predicate_count(selected_access);
705            if matches!(
706                selected_reason,
707                AccessChoiceSelectedReason::PlannerExactIndexIntersection
708            ) {
709                Self {
710                    burden_class: AccessChoiceResidualBurden::PredicateOnly.label(),
711                    has_residual_filter: false,
712                    has_residual_predicate: true,
713                    access_bound_predicate_count,
714                    residual_predicate_count: access_bound_predicate_count,
715                }
716            } else {
717                Self {
718                    burden_class: AccessChoiceResidualBurden::None.label(),
719                    has_residual_filter: false,
720                    has_residual_predicate: false,
721                    access_bound_predicate_count,
722                    residual_predicate_count: 0,
723                }
724            }
725        }
726    }
727}
728
729///
730/// ExplainPredicate
731///
732/// Deterministic projection of canonical predicate structure for explain output.
733/// This preserves normalized predicate shape used by hashing/fingerprints.
734///
735
736#[derive(Clone, Debug, Eq, PartialEq)]
737pub enum ExplainPredicate {
738    None,
739    True,
740    False,
741    And(Vec<Self>),
742    Or(Vec<Self>),
743    Not(Box<Self>),
744    Compare {
745        field: String,
746        op: CompareOp,
747        value: Value,
748        coercion: CoercionSpec,
749    },
750    CompareFields {
751        left_field: String,
752        op: CompareOp,
753        right_field: String,
754        coercion: CoercionSpec,
755    },
756    IsNull {
757        field: String,
758    },
759    IsNotNull {
760        field: String,
761    },
762    IsMissing {
763        field: String,
764    },
765    IsEmpty {
766        field: String,
767    },
768    IsNotEmpty {
769        field: String,
770    },
771    TextContains {
772        field: String,
773        value: Value,
774    },
775    TextContainsCi {
776        field: String,
777        value: Value,
778    },
779}
780
781///
782/// ExplainOrderBy
783///
784/// Deterministic projection of canonical ORDER BY shape.
785///
786
787#[derive(Clone, Debug, Eq, PartialEq)]
788pub enum ExplainOrderBy {
789    None,
790    Fields(Vec<ExplainOrder>),
791}
792
793///
794/// ExplainOrder
795///
796/// One canonical ORDER BY field + direction pair.
797///
798
799#[derive(Clone, Debug, Eq, PartialEq)]
800pub struct ExplainOrder {
801    pub(in crate::db) field: String,
802    pub(in crate::db) direction: OrderDirection,
803}
804
805impl ExplainOrder {
806    /// Borrow ORDER BY field name.
807    #[must_use]
808    pub const fn field(&self) -> &str {
809        self.field.as_str()
810    }
811
812    /// Return ORDER BY direction.
813    #[must_use]
814    pub const fn direction(&self) -> OrderDirection {
815        self.direction
816    }
817}
818
819///
820/// ExplainPagination
821///
822/// Explain-surface projection of pagination window configuration.
823///
824
825#[derive(Clone, Debug, Eq, PartialEq)]
826pub enum ExplainPagination {
827    None,
828    Page { limit: Option<u32>, offset: u32 },
829}
830
831///
832/// ExplainDeleteLimit
833///
834/// Explain-surface projection of delete-limit configuration.
835///
836
837#[derive(Clone, Debug, Eq, PartialEq)]
838pub enum ExplainDeleteLimit {
839    None,
840    Limit { max_rows: u32 },
841    Window { limit: Option<u32>, offset: u32 },
842}
843
844impl AccessPlannedQuery {
845    /// Produce a stable, deterministic explanation of this logical plan.
846    #[must_use]
847    pub(in crate::db) fn explain(&self) -> ExplainPlan {
848        self.explain_inner()
849    }
850
851    fn explain_inner(&self) -> ExplainPlan {
852        // Phase 1: project logical plan variant into scalar core + grouped metadata.
853        let (logical, grouping) = match &self.logical {
854            LogicalPlan::Scalar(logical) => (logical, ExplainGrouping::None),
855            LogicalPlan::Grouped(logical) => {
856                let grouped_strategy = grouped_plan_strategy(self).unwrap_or_else(|| {
857                    debug_assert!(
858                        grouped_plan_strategy(self).is_some(),
859                        "grouped logical explain projection requires planner-owned grouped strategy",
860                    );
861                    GroupedPlanStrategy::hash_group_with_aggregate_family(
862                        GroupedPlanFallbackReason::GroupKeyOrderUnavailable,
863                        GroupedPlanAggregateFamily::from_grouped_aggregates(
864                            logical.group.aggregates.as_slice(),
865                        ),
866                    )
867                });
868
869                (
870                    &logical.scalar,
871                    ExplainGrouping::Grouped {
872                        strategy: grouped_strategy.code(),
873                        fallback_reason: grouped_strategy
874                            .fallback_reason()
875                            .map(GroupedPlanFallbackReason::code),
876                        group_fields: logical
877                            .group
878                            .group_fields
879                            .iter()
880                            .map(|field_slot| ExplainGroupField {
881                                slot_index: field_slot.index(),
882                                field: field_slot.field().to_string(),
883                            })
884                            .collect(),
885                        aggregates: logical
886                            .group
887                            .aggregates
888                            .iter()
889                            .map(|aggregate| ExplainGroupAggregate {
890                                kind: aggregate.kind(),
891                                target_field: aggregate.target_field().map(str::to_string),
892                                input_expr: aggregate
893                                    .input_expr()
894                                    .map(render_scalar_projection_expr_plan_label),
895                                filter_expr: aggregate
896                                    .filter_expr()
897                                    .map(render_scalar_projection_expr_plan_label),
898                                distinct: aggregate.raw_distinct(),
899                            })
900                            .collect(),
901                        having: explain_group_having(logical),
902                        max_groups: logical.group.execution.max_groups(),
903                        max_group_bytes: logical.group.execution.max_group_bytes(),
904                    },
905                )
906            }
907        };
908
909        // Phase 2: project scalar plan + access path into deterministic explain surface.
910        explain_scalar_inner(logical, grouping, &self.access, self.access_choice())
911    }
912}
913
914fn explain_group_having(logical: &crate::db::query::plan::GroupPlan) -> Option<ExplainGroupHaving> {
915    let expr = logical.effective_having_expr()?;
916
917    Some(ExplainGroupHaving {
918        expr: expr.into_owned(),
919    })
920}
921
922fn explain_scalar_inner<K>(
923    logical: &ScalarPlan,
924    grouping: ExplainGrouping,
925    access: &AccessPlan<K>,
926    access_choice: &AccessChoiceExplainSnapshot,
927) -> ExplainPlan
928where
929    K: KeyValueCodec,
930{
931    // Phase 1: consume canonical predicate model from planner-owned scalar semantics.
932    let filter_expr = logical
933        .filter_expr
934        .as_ref()
935        .map(render_scalar_filter_expr_plan_label);
936    let filter_expr_model = logical.filter_expr.clone();
937    let predicate_model = logical.predicate.clone();
938    let predicate = match &predicate_model {
939        Some(predicate) => ExplainPredicate::from_predicate(predicate),
940        None => ExplainPredicate::None,
941    };
942
943    // Phase 2: project scalar-plan fields into explain-specific enums.
944    let order_by = explain_order(logical.order.as_ref());
945    let order_pushdown = explain_order_pushdown();
946    let page = explain_page(logical.page.as_ref());
947    let delete_limit = explain_delete_limit(logical.delete_limit.as_ref());
948
949    // Phase 3: assemble one stable explain payload.
950    let access = explain_access_plan(access);
951    let access_decision = ExplainAccessDecision::from_snapshot(&access, access_choice);
952
953    ExplainPlan {
954        mode: logical.mode,
955        access,
956        access_decision,
957        filter_expr,
958        filter_expr_model,
959        predicate,
960        predicate_model,
961        order_by,
962        distinct: logical.distinct,
963        grouping,
964        order_pushdown,
965        page,
966        delete_limit,
967        consistency: logical.consistency,
968    }
969}
970
971fn selected_candidate_summary<'a>(
972    selected_index_name: Option<&str>,
973    candidates: &'a [AccessChoiceCandidateExplainSummary],
974) -> Option<&'a AccessChoiceCandidateExplainSummary> {
975    let selected_index_name = selected_index_name?;
976
977    candidates
978        .iter()
979        .find(|candidate| candidate.index_name() == selected_index_name)
980}
981
982const fn selected_index_name(access: &ExplainAccessPath) -> Option<&str> {
983    match access {
984        ExplainAccessPath::IndexPrefix { name, .. }
985        | ExplainAccessPath::IndexMultiLookup { name, .. }
986        | ExplainAccessPath::IndexBranchSet { name, .. }
987        | ExplainAccessPath::IndexRange { name, .. } => Some(name.as_str()),
988        ExplainAccessPath::ByKey { .. }
989        | ExplainAccessPath::ByKeys { .. }
990        | ExplainAccessPath::KeyRange { .. }
991        | ExplainAccessPath::FullScan
992        | ExplainAccessPath::Union(_)
993        | ExplainAccessPath::Intersection(_) => None,
994    }
995}
996
997fn access_bound_predicate_count(access: &ExplainAccessPath) -> usize {
998    match access {
999        ExplainAccessPath::ByKey { .. }
1000        | ExplainAccessPath::ByKeys { .. }
1001        | ExplainAccessPath::IndexMultiLookup { .. } => 1,
1002        ExplainAccessPath::IndexBranchSet {
1003            fixed_values,
1004            branch_values,
1005            ..
1006        } => fixed_values.len() + usize::from(!branch_values.is_empty()),
1007        ExplainAccessPath::KeyRange { .. } => 2,
1008        ExplainAccessPath::IndexPrefix { prefix_len, .. } => *prefix_len,
1009        ExplainAccessPath::IndexRange {
1010            prefix_len,
1011            lower,
1012            upper,
1013            ..
1014        } => *prefix_len + bound_constraint_count(lower) + bound_constraint_count(upper),
1015        ExplainAccessPath::FullScan => 0,
1016        ExplainAccessPath::Union(children) | ExplainAccessPath::Intersection(children) => {
1017            children.iter().map(access_bound_predicate_count).sum()
1018        }
1019    }
1020}
1021
1022const fn bound_constraint_count(bound: &Bound<Value>) -> usize {
1023    match bound {
1024        Bound::Included(_) | Bound::Excluded(_) => 1,
1025        Bound::Unbounded => 0,
1026    }
1027}
1028
1029const fn explain_order_pushdown() -> ExplainOrderPushdown {
1030    // Query explain does not own physical pushdown feasibility routing.
1031    ExplainOrderPushdown::MissingModelContext
1032}
1033
1034impl ExplainPredicate {
1035    pub(in crate::db) fn from_predicate(predicate: &Predicate) -> Self {
1036        match predicate {
1037            Predicate::True => Self::True,
1038            Predicate::False => Self::False,
1039            Predicate::And(children) => {
1040                Self::And(children.iter().map(Self::from_predicate).collect())
1041            }
1042            Predicate::Or(children) => {
1043                Self::Or(children.iter().map(Self::from_predicate).collect())
1044            }
1045            Predicate::Not(inner) => Self::Not(Box::new(Self::from_predicate(inner))),
1046            Predicate::Compare(compare) => Self::from_compare(compare),
1047            Predicate::CompareFields(compare) => Self::CompareFields {
1048                left_field: compare.left_field().to_string(),
1049                op: compare.op(),
1050                right_field: compare.right_field().to_string(),
1051                coercion: compare.coercion().clone(),
1052            },
1053            Predicate::IsNull { field } => Self::IsNull {
1054                field: field.clone(),
1055            },
1056            Predicate::IsNotNull { field } => Self::IsNotNull {
1057                field: field.clone(),
1058            },
1059            Predicate::IsMissing { field } => Self::IsMissing {
1060                field: field.clone(),
1061            },
1062            Predicate::IsEmpty { field } => Self::IsEmpty {
1063                field: field.clone(),
1064            },
1065            Predicate::IsNotEmpty { field } => Self::IsNotEmpty {
1066                field: field.clone(),
1067            },
1068            Predicate::TextContains { field, value } => Self::TextContains {
1069                field: field.clone(),
1070                value: value.clone(),
1071            },
1072            Predicate::TextContainsCi { field, value } => Self::TextContainsCi {
1073                field: field.clone(),
1074                value: value.clone(),
1075            },
1076        }
1077    }
1078
1079    fn from_compare(compare: &ComparePredicate) -> Self {
1080        Self::Compare {
1081            field: compare.field.clone(),
1082            op: compare.op,
1083            value: compare.value.clone(),
1084            coercion: compare.coercion.clone(),
1085        }
1086    }
1087}
1088
1089fn explain_order(order: Option<&OrderSpec>) -> ExplainOrderBy {
1090    let Some(order) = order else {
1091        return ExplainOrderBy::None;
1092    };
1093
1094    if order.fields.is_empty() {
1095        return ExplainOrderBy::None;
1096    }
1097
1098    ExplainOrderBy::Fields(
1099        order
1100            .fields
1101            .iter()
1102            .map(|term| ExplainOrder {
1103                field: term.rendered_label(),
1104                direction: term.direction(),
1105            })
1106            .collect(),
1107    )
1108}
1109
1110const fn explain_page(page: Option<&PageSpec>) -> ExplainPagination {
1111    match page {
1112        Some(page) => ExplainPagination::Page {
1113            limit: page.limit,
1114            offset: page.offset,
1115        },
1116        None => ExplainPagination::None,
1117    }
1118}
1119
1120const fn explain_delete_limit(limit: Option<&DeleteLimitSpec>) -> ExplainDeleteLimit {
1121    match limit {
1122        Some(limit) if limit.offset == 0 => match limit.limit {
1123            Some(max_rows) => ExplainDeleteLimit::Limit { max_rows },
1124            None => ExplainDeleteLimit::Window {
1125                limit: None,
1126                offset: 0,
1127            },
1128        },
1129        Some(limit) => ExplainDeleteLimit::Window {
1130            limit: limit.limit,
1131            offset: limit.offset,
1132        },
1133        None => ExplainDeleteLimit::None,
1134    }
1135}
1136
1137fn write_logical_explain_json(explain: &ExplainPlan, out: &mut String) {
1138    let mut object = JsonWriter::begin_object(out);
1139    object.field_with("mode", |out| {
1140        let mut object = JsonWriter::begin_object(out);
1141        match explain.mode() {
1142            QueryMode::Load(spec) => {
1143                object.field_str("type", "Load");
1144                match spec.limit() {
1145                    Some(limit) => object.field_u64("limit", u64::from(limit)),
1146                    None => object.field_null("limit"),
1147                }
1148                object.field_u64("offset", u64::from(spec.offset()));
1149            }
1150            QueryMode::Delete(spec) => {
1151                object.field_str("type", "Delete");
1152                match spec.limit() {
1153                    Some(limit) => object.field_u64("limit", u64::from(limit)),
1154                    None => object.field_null("limit"),
1155                }
1156            }
1157        }
1158        object.finish();
1159    });
1160    object.field_with("access", |out| {
1161        write_access_json_detailed(explain.access(), out);
1162    });
1163    object.field_with("access_decision", |out| {
1164        write_access_decision_json(explain.access_decision(), out);
1165    });
1166    match explain.filter_expr() {
1167        Some(filter_expr) => object.field_str("filter_expr", filter_expr),
1168        None => object.field_null("filter_expr"),
1169    }
1170    object.field_value_debug("predicate", explain.predicate());
1171    object.field_value_debug("order_by", explain.order_by());
1172    object.field_bool("distinct", explain.distinct());
1173    object.field_value_debug("grouping", explain.grouping());
1174    object.field_value_debug("order_pushdown", explain.order_pushdown());
1175    object.field_with("page", |out| {
1176        let mut object = JsonWriter::begin_object(out);
1177        match explain.page() {
1178            ExplainPagination::None => {
1179                object.field_str("type", "None");
1180            }
1181            ExplainPagination::Page { limit, offset } => {
1182                object.field_str("type", "Page");
1183                match limit {
1184                    Some(limit) => object.field_u64("limit", u64::from(*limit)),
1185                    None => object.field_null("limit"),
1186                }
1187                object.field_u64("offset", u64::from(*offset));
1188            }
1189        }
1190        object.finish();
1191    });
1192    object.field_with("delete_limit", |out| {
1193        let mut object = JsonWriter::begin_object(out);
1194        match explain.delete_limit() {
1195            ExplainDeleteLimit::None => {
1196                object.field_str("type", "None");
1197            }
1198            ExplainDeleteLimit::Limit { max_rows } => {
1199                object.field_str("type", "Limit");
1200                object.field_u64("max_rows", u64::from(*max_rows));
1201            }
1202            ExplainDeleteLimit::Window { limit, offset } => {
1203                object.field_str("type", "Window");
1204                object.field_with("limit", |out| match limit {
1205                    Some(limit) => out.push_str(&limit.to_string()),
1206                    None => out.push_str("null"),
1207                });
1208                object.field_u64("offset", u64::from(*offset));
1209            }
1210        }
1211        object.finish();
1212    });
1213    object.field_value_debug("consistency", &explain.consistency());
1214    object.finish();
1215}
1216
1217fn write_access_decision_json(decision: &ExplainAccessDecision, out: &mut String) {
1218    let mut object = JsonWriter::begin_object(out);
1219    object.field_with("selected", |out| {
1220        let mut selected = JsonWriter::begin_object(out);
1221        selected.field_str("kind", decision.selected.kind.code());
1222        match decision.selected.index_name.as_deref() {
1223            Some(index_name) => selected.field_str("index_name", index_name),
1224            None => selected.field_null("index_name"),
1225        }
1226        selected.field_str("label", decision.selected.label.as_str());
1227        selected.field_str("reason", decision.selected.reason);
1228        selected.finish();
1229    });
1230    object.field_with("candidates", |out| {
1231        out.push('[');
1232        for (index, candidate) in decision.candidates.iter().enumerate() {
1233            if index > 0 {
1234                out.push(',');
1235            }
1236            write_access_candidate_json(candidate, out);
1237        }
1238        out.push(']');
1239    });
1240    object.field_with("alternatives", |out| {
1241        out.push('[');
1242        for (index, alternative) in decision.alternatives.iter().enumerate() {
1243            if index > 0 {
1244                out.push(',');
1245            }
1246            let mut object = JsonWriter::begin_object(out);
1247            object.field_str("index_name", alternative.index_name.as_str());
1248            object.finish();
1249        }
1250        out.push(']');
1251    });
1252    object.field_with("rejections", |out| {
1253        out.push('[');
1254        for (index, rejection) in decision.rejections.iter().enumerate() {
1255            if index > 0 {
1256                out.push(',');
1257            }
1258            let mut object = JsonWriter::begin_object(out);
1259            match rejection.index_name.as_deref() {
1260                Some(index_name) => object.field_str("index_name", index_name),
1261                None => object.field_null("index_name"),
1262            }
1263            match rejection.reason.as_deref() {
1264                Some(reason) => object.field_str("reason", reason),
1265                None => object.field_null("reason"),
1266            }
1267            object.field_str("label", rejection.label.as_str());
1268            object.finish();
1269        }
1270        out.push(']');
1271    });
1272    object.field_with("residual", |out| {
1273        let mut residual = JsonWriter::begin_object(out);
1274        residual.field_str("burden_class", decision.residual.burden_class);
1275        residual.field_bool("has_residual_filter", decision.residual.has_residual_filter);
1276        residual.field_bool(
1277            "has_residual_predicate",
1278            decision.residual.has_residual_predicate,
1279        );
1280        residual.field_u64(
1281            "access_bound_predicate_count",
1282            decision.residual.access_bound_predicate_count as u64,
1283        );
1284        residual.field_u64(
1285            "residual_predicate_count",
1286            decision.residual.residual_predicate_count as u64,
1287        );
1288        residual.finish();
1289    });
1290    object.finish();
1291}
1292
1293fn write_access_candidate_json(candidate: &ExplainAccessCandidate, out: &mut String) {
1294    let mut object = JsonWriter::begin_object(out);
1295    object.field_str("label", candidate.label.as_str());
1296    object.field_bool("exact", candidate.exact);
1297    object.field_bool("filtered", candidate.filtered);
1298    object.field_u64("range_bound_count", candidate.range_bound_count as u64);
1299    object.field_bool("order_compatible", candidate.order_compatible);
1300    object.field_str("residual_burden", candidate.residual_burden);
1301    object.field_u64(
1302        "residual_predicate_terms",
1303        candidate.residual_predicate_terms as u64,
1304    );
1305    object.finish();
1306}