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(
73            query.structural().model(),
74            &accepted_schema,
75        );
76
77        plan.finalize_access_choice_for_model_with_indexes_and_schema(
78            query.structural().model(),
79            visible_indexes.as_slice(),
80            &schema_info,
81        );
82        let authority = Self::accepted_entity_authority_for_schema::<E>(&accepted_schema)
83            .map_err(QueryError::execute)?;
84
85        Ok((plan, authority, cache_attribution))
86    }
87
88    // Project one logical explain payload using only planner-visible indexes.
89    pub(in crate::db) fn explain_query_with_visible_indexes<E>(
90        &self,
91        query: &Query<E>,
92    ) -> Result<ExplainPlan, QueryError>
93    where
94        E: EntityKind<Canister = C>,
95    {
96        self.try_map_cached_logical_query_plan(query, |plan| Ok(plan.explain()))
97    }
98
99    // Hash one typed query plan using only the indexes currently visible for
100    // the query's recovered store.
101    pub(in crate::db) fn query_plan_hash_hex_with_visible_indexes<E>(
102        &self,
103        query: &Query<E>,
104    ) -> Result<String, QueryError>
105    where
106        E: EntityKind<Canister = C>,
107    {
108        self.try_map_cached_logical_query_plan(query, |plan| Ok(plan.fingerprint().to_string()))
109    }
110
111    // Explain one load execution shape using only planner-visible
112    // indexes from the recovered store state.
113    pub(in crate::db) fn explain_query_execution_with_visible_indexes<E>(
114        &self,
115        query: &Query<E>,
116    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
117    where
118        E: EntityValue + EntityKind<Canister = C>,
119    {
120        self.with_query_visible_indexes(query, |query, visible_indexes| {
121            let (plan, authority, _) =
122                self.cached_execution_explain_plan::<E>(query, visible_indexes)?;
123
124            query
125                .structural()
126                .explain_execution_descriptor_from_plan_with_authority(&plan, &authority)
127        })
128    }
129
130    // Render one load execution descriptor plus route diagnostics using
131    // only planner-visible indexes from the recovered store state.
132    pub(in crate::db) fn explain_query_execution_verbose_with_visible_indexes<E>(
133        &self,
134        query: &Query<E>,
135    ) -> Result<String, QueryError>
136    where
137        E: EntityValue + EntityKind<Canister = C>,
138    {
139        self.with_query_visible_indexes(query, |query, visible_indexes| {
140            let (plan, authority, cache_attribution) =
141                self.cached_execution_explain_plan::<E>(query, visible_indexes)?;
142
143            query
144                .structural()
145                .finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
146                    &plan,
147                    &authority,
148                    Some(query_plan_cache_reuse_event(cache_attribution)),
149                    |_| {},
150                )
151                .map(|diagnostics| diagnostics.render_text_verbose())
152        })
153    }
154
155    // Explain one prepared fluent aggregate terminal from the same cached
156    // prepared plan used by execution.
157    pub(in crate::db) fn explain_query_prepared_aggregate_terminal_with_visible_indexes<E, S>(
158        &self,
159        query: &Query<E>,
160        strategy: &S,
161    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
162    where
163        E: EntityValue + EntityKind<Canister = C>,
164        S: AggregateExplain,
165    {
166        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
167
168        plan.explain_prepared_aggregate_terminal(strategy)
169    }
170
171    // Explain one `bytes_by(field)` terminal from the same cached prepared
172    // plan used by execution.
173    pub(in crate::db) fn explain_query_bytes_by_with_visible_indexes<E>(
174        &self,
175        query: &Query<E>,
176        target_field: &str,
177    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
178    where
179        E: EntityValue + EntityKind<Canister = C>,
180    {
181        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
182
183        plan.explain_bytes_by_terminal(target_field)
184    }
185
186    // Explain one prepared fluent projection terminal from the same cached
187    // prepared plan used by execution.
188    pub(in crate::db) fn explain_query_prepared_projection_terminal_with_visible_indexes<E, S>(
189        &self,
190        query: &Query<E>,
191        strategy: &S,
192    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
193    where
194        E: EntityValue + EntityKind<Canister = C>,
195        S: ProjectionExplain,
196    {
197        let (plan, _) = self.cached_prepared_query_plan_for_entity::<E>(query)?;
198
199        plan.explain_prepared_projection_terminal(strategy)
200    }
201
202    /// Build one trace payload for a query without executing it.
203    ///
204    /// This lightweight surface is intended for developer diagnostics:
205    /// plan hash, access strategy summary, and planner/executor route shape.
206    pub fn trace_query<E>(&self, query: &Query<E>) -> Result<QueryTracePlan, QueryError>
207    where
208        E: EntityKind<Canister = C>,
209    {
210        let (prepared_plan, cache_attribution) =
211            self.cached_prepared_query_plan_for_entity::<E>(query)?;
212        let logical_plan = prepared_plan.logical_plan();
213        let explain = logical_plan.explain();
214        let plan_hash = logical_plan.fingerprint().to_string();
215        let executable_access = prepared_plan.access().executable_contract();
216        let access_strategy = summarize_executable_access_plan(&executable_access);
217        let execution_family = match prepared_plan.mode() {
218            QueryMode::Load(_) => Some(trace_execution_family_from_executor(
219                prepared_plan
220                    .execution_family()
221                    .map_err(QueryError::execute)?,
222            )),
223            QueryMode::Delete(_) => None,
224        };
225        let reuse = query_plan_cache_reuse_event(cache_attribution);
226
227        Ok(QueryTracePlan::new(
228            plan_hash,
229            access_strategy,
230            execution_family,
231            reuse,
232            explain,
233        ))
234    }
235}