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