Skip to main content

icydb_core/db/session/query/
explain.rs

1//! Module: db::session::query::explain
2//! Responsibility: read-only query explain, trace, and plan-hash surfaces.
3//! Does not own: execution, cursor decoding, fluent terminal execution, or diagnostics attribution.
4//! Boundary: maps cached session-visible plans into query-facing diagnostic DTOs.
5
6use crate::{
7    db::{
8        DbSession, Query, QueryError, QueryTracePlan, TraceExecutionFamily,
9        access::summarize_executable_access_plan,
10        executor::{EntityAuthority, ExecutionFamily},
11        query::builder::{AggregateExplain, ProjectionExplain},
12        query::explain::{
13            ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor, ExplainPlan,
14        },
15        query::plan::{AccessPlannedQuery, QueryMode, VisibleIndexes},
16        session::query::{QueryPlanCacheAttribution, query_plan_cache_reuse_event},
17    },
18    traits::{CanisterKind, EntityKind, EntityValue},
19};
20
21// Translate executor route-family selection into the query-owned trace label
22// at the session boundary so trace DTOs do not depend on executor types.
23const fn trace_execution_family_from_executor(family: ExecutionFamily) -> TraceExecutionFamily {
24    match family {
25        ExecutionFamily::PrimaryKey => TraceExecutionFamily::PrimaryKey,
26        ExecutionFamily::Ordered => TraceExecutionFamily::Ordered,
27        ExecutionFamily::Grouped => TraceExecutionFamily::Grouped,
28    }
29}
30
31impl<C: CanisterKind> DbSession<C> {
32    // Borrow the cached logical plan for read-only query diagnostics so explain
33    // and hash surfaces do not clone the full access-planned query.
34    fn try_map_cached_logical_query_plan<E, T>(
35        &self,
36        query: &Query<E>,
37        map: impl FnOnce(&AccessPlannedQuery) -> Result<T, QueryError>,
38    ) -> Result<T, QueryError>
39    where
40        E: EntityKind<Canister = C>,
41    {
42        self.try_map_cached_shared_query_plan_ref_for_entity::<E, T>(query, |prepared_plan| {
43            map(prepared_plan.logical_plan())
44        })
45    }
46
47    // Reuse the same cached logical plan as execution explain, then freeze the
48    // explain-only access-choice facts for the effective session-visible index
49    // slice before route facts are assembled.
50    fn cached_execution_explain_plan<E>(
51        &self,
52        query: &Query<E>,
53        visible_indexes: &VisibleIndexes<'_>,
54    ) -> Result<
55        (
56            AccessPlannedQuery,
57            EntityAuthority,
58            QueryPlanCacheAttribution,
59        ),
60        QueryError,
61    >
62    where
63        E: EntityKind<Canister = C>,
64    {
65        let (prepared_plan, cache_attribution) =
66            self.cached_shared_query_plan_for_entity::<E>(query)?;
67        let mut plan = prepared_plan.logical_plan().clone();
68        let authority = prepared_plan.authority();
69        let schema_info = authority
70            .accepted_schema_info()
71            .ok_or_else(QueryError::invariant)?;
72
73        plan.finalize_access_choice_for_model_with_accepted_indexes_and_schema(
74            query.structural().model(),
75            visible_indexes.accepted_field_path_indexes(),
76            visible_indexes.accepted_expression_indexes(),
77            schema_info,
78        );
79
80        Ok((plan, authority, cache_attribution))
81    }
82
83    // Project one logical explain payload using only planner-visible indexes.
84    pub(in crate::db) fn explain_query_with_visible_indexes<E>(
85        &self,
86        query: &Query<E>,
87    ) -> Result<ExplainPlan, QueryError>
88    where
89        E: EntityKind<Canister = C>,
90    {
91        self.with_query_visible_indexes(query, |query, visible_indexes| {
92            self.try_map_cached_logical_query_plan(query, |plan| {
93                let mut plan = plan.clone();
94                let schema_info = visible_indexes
95                    .accepted_schema_info()
96                    .ok_or_else(QueryError::invariant)?;
97                plan.finalize_access_choice_for_model_with_accepted_indexes_and_schema(
98                    query.structural().model(),
99                    visible_indexes.accepted_field_path_indexes(),
100                    visible_indexes.accepted_expression_indexes(),
101                    schema_info,
102                );
103
104                Ok(plan.explain())
105            })
106        })
107    }
108
109    // Hash one typed query plan using only the indexes currently visible for
110    // the query's recovered store.
111    pub(in crate::db) fn query_plan_hash_hex_with_visible_indexes<E>(
112        &self,
113        query: &Query<E>,
114    ) -> Result<String, QueryError>
115    where
116        E: EntityKind<Canister = C>,
117    {
118        self.try_map_cached_logical_query_plan(query, |plan| Ok(plan.fingerprint().to_string()))
119    }
120
121    // Explain one load execution shape using only planner-visible
122    // indexes from the recovered store state.
123    pub(in crate::db) fn explain_query_execution_with_visible_indexes<E>(
124        &self,
125        query: &Query<E>,
126    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
127    where
128        E: EntityValue + EntityKind<Canister = C>,
129    {
130        self.with_query_visible_indexes(query, |query, visible_indexes| {
131            let (plan, authority, _) =
132                self.cached_execution_explain_plan::<E>(query, visible_indexes)?;
133
134            query
135                .structural()
136                .explain_execution_descriptor_from_plan_with_authority(&plan, &authority)
137        })
138    }
139
140    // Render one load execution descriptor plus route diagnostics using
141    // only planner-visible indexes from the recovered store state.
142    pub(in crate::db) fn explain_query_execution_verbose_with_visible_indexes<E>(
143        &self,
144        query: &Query<E>,
145    ) -> Result<String, QueryError>
146    where
147        E: EntityValue + EntityKind<Canister = C>,
148    {
149        self.with_query_visible_indexes(query, |query, visible_indexes| {
150            let (plan, authority, cache_attribution) =
151                self.cached_execution_explain_plan::<E>(query, visible_indexes)?;
152
153            query
154                .structural()
155                .finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
156                    &plan,
157                    &authority,
158                    Some(query_plan_cache_reuse_event(cache_attribution)),
159                    |_| {},
160                )
161                .map(|diagnostics| diagnostics.render_text_verbose())
162        })
163    }
164
165    // Explain one prepared fluent aggregate terminal from the same cached
166    // prepared plan used by execution.
167    pub(in crate::db) fn explain_query_prepared_aggregate_terminal_with_visible_indexes<E, S>(
168        &self,
169        query: &Query<E>,
170        strategy: &S,
171    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
172    where
173        E: EntityValue + EntityKind<Canister = C>,
174        S: AggregateExplain,
175    {
176        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
177
178        plan.explain_prepared_aggregate_terminal(strategy)
179    }
180
181    // Explain one `bytes_by(field)` terminal from the same cached prepared
182    // plan used by execution.
183    pub(in crate::db) fn explain_query_bytes_by_with_visible_indexes<E>(
184        &self,
185        query: &Query<E>,
186        target_field: &str,
187    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
188    where
189        E: EntityValue + EntityKind<Canister = C>,
190    {
191        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
192
193        plan.explain_bytes_by_terminal(target_field)
194    }
195
196    // Explain one prepared fluent projection terminal from the same cached
197    // prepared plan used by execution.
198    pub(in crate::db) fn explain_query_prepared_projection_terminal_with_visible_indexes<E, S>(
199        &self,
200        query: &Query<E>,
201        strategy: &S,
202    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
203    where
204        E: EntityValue + EntityKind<Canister = C>,
205        S: ProjectionExplain,
206    {
207        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
208
209        plan.explain_prepared_projection_terminal(strategy)
210    }
211
212    /// Build one trace payload for a query without executing it.
213    ///
214    /// This lightweight surface is intended for developer diagnostics:
215    /// plan hash, access strategy summary, and planner/executor route shape.
216    pub fn trace_query<E>(&self, query: &Query<E>) -> Result<QueryTracePlan, QueryError>
217    where
218        E: EntityKind<Canister = C>,
219    {
220        let (prepared_plan, cache_attribution) =
221            self.cached_prepared_query_plan_for_entity::<E>(query)?;
222        let logical_plan = prepared_plan.logical_plan();
223        let explain = logical_plan.explain();
224        let plan_hash = logical_plan.fingerprint().to_string();
225        let executable_access = prepared_plan.access().executable_contract();
226        let access_strategy = summarize_executable_access_plan(&executable_access);
227        let execution_family = match prepared_plan.mode() {
228            QueryMode::Load(_) => Some(trace_execution_family_from_executor(
229                prepared_plan
230                    .execution_family()
231                    .map_err(QueryError::execute)?,
232            )),
233            QueryMode::Delete(_) => None,
234        };
235        let reuse = query_plan_cache_reuse_event(cache_attribution);
236
237        Ok(QueryTracePlan::new(
238            plan_hash,
239            access_strategy,
240            execution_family,
241            reuse,
242            explain,
243        ))
244    }
245}