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    // Reuse one cached logical plan, then freeze the explain-only
33    // access-choice facts for the effective session-visible index slice before
34    // descriptor or route facts are assembled.
35    fn cached_finalized_explain_plan<E>(
36        &self,
37        query: &Query<E>,
38        visible_indexes: &VisibleIndexes<'_>,
39    ) -> Result<
40        (
41            AccessPlannedQuery,
42            EntityAuthority,
43            QueryPlanCacheAttribution,
44        ),
45        QueryError,
46    >
47    where
48        E: EntityKind<Canister = C>,
49    {
50        let (prepared_plan, cache_attribution) =
51            self.cached_shared_query_plan_for_entity::<E>(query)?;
52        let mut plan = prepared_plan.logical_plan().clone();
53        let authority = prepared_plan.authority();
54        let schema_info = authority
55            .accepted_schema_info()
56            .ok_or_else(QueryError::invariant)?;
57
58        plan.finalize_access_choice_for_model_with_semantic_indexes_and_schema(
59            query.structural().model(),
60            visible_indexes.accepted_semantic_index_contracts(),
61            schema_info,
62        );
63
64        Ok((plan, authority, cache_attribution))
65    }
66
67    // Project one logical explain payload using only planner-visible indexes.
68    pub(in crate::db) fn explain_query_with_visible_indexes<E>(
69        &self,
70        query: &Query<E>,
71    ) -> Result<ExplainPlan, QueryError>
72    where
73        E: EntityKind<Canister = C>,
74    {
75        self.with_query_visible_indexes(query, |query, visible_indexes| {
76            let (plan, _, _) = self.cached_finalized_explain_plan::<E>(query, visible_indexes)?;
77
78            Ok(plan.explain())
79        })
80    }
81
82    // Hash one typed query plan using only the indexes currently visible for
83    // the query's recovered store.
84    pub(in crate::db) fn query_plan_hash_hex_with_visible_indexes<E>(
85        &self,
86        query: &Query<E>,
87    ) -> Result<String, QueryError>
88    where
89        E: EntityKind<Canister = C>,
90    {
91        let (prepared_plan, _) = self.cached_shared_query_plan_for_entity::<E>(query)?;
92
93        Ok(prepared_plan.plan_hash_hex())
94    }
95
96    // Explain one load execution shape using only planner-visible
97    // indexes from the recovered store state.
98    pub(in crate::db) fn explain_query_execution_with_visible_indexes<E>(
99        &self,
100        query: &Query<E>,
101    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
102    where
103        E: EntityValue + EntityKind<Canister = C>,
104    {
105        self.with_query_visible_indexes(query, |query, visible_indexes| {
106            let (plan, authority, _) =
107                self.cached_finalized_explain_plan::<E>(query, visible_indexes)?;
108
109            query
110                .structural()
111                .explain_execution_descriptor_from_plan_with_authority(&plan, &authority)
112        })
113    }
114
115    // Render one load execution descriptor plus route diagnostics using
116    // only planner-visible indexes from the recovered store state.
117    pub(in crate::db) fn explain_query_execution_verbose_with_visible_indexes<E>(
118        &self,
119        query: &Query<E>,
120    ) -> Result<String, QueryError>
121    where
122        E: EntityValue + EntityKind<Canister = C>,
123    {
124        self.with_query_visible_indexes(query, |query, visible_indexes| {
125            let (plan, authority, cache_attribution) =
126                self.cached_finalized_explain_plan::<E>(query, visible_indexes)?;
127
128            query
129                .structural()
130                .finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
131                    &plan,
132                    &authority,
133                    Some(query_plan_cache_reuse_event(cache_attribution)),
134                    |_| {},
135                )
136                .map(|diagnostics| diagnostics.render_text_verbose())
137        })
138    }
139
140    // Render one finalized load execution JSON payload using only
141    // planner-visible indexes from the recovered store state.
142    pub(in crate::db) fn explain_query_execution_json_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_finalized_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_json_canonical())
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: EntityKind<Canister = C>,
174        S: AggregateExplain,
175    {
176        let (plan, _) = self.cached_shared_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: EntityKind<Canister = C>,
190    {
191        let (plan, _) = self.cached_shared_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: EntityKind<Canister = C>,
205        S: ProjectionExplain,
206    {
207        let (plan, _) = self.cached_shared_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_shared_query_plan_for_entity::<E>(query)?;
222        let logical_plan = prepared_plan.logical_plan();
223        let explain = logical_plan.explain();
224        let plan_hash = prepared_plan.plan_hash_hex();
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}