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