1mod descriptor;
7
8#[cfg(test)]
9use crate::db::executor::planning::route::AggregateRouteShape;
10#[cfg(test)]
11use crate::db::query::builder::AggregateExpr;
12use crate::{
13 db::{
14 Query, TraceReuseEvent,
15 executor::{EntityAuthority, SharedPreparedExecutionPlan},
16 query::{
17 builder::{AggregateExplain, ProjectionExplain},
18 explain::{
19 ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
20 ExplainExecutionNodeType, ExplainOrderPushdown, FinalizedQueryDiagnostics,
21 property_keys,
22 },
23 intent::{QueryError, StructuralQuery},
24 plan::{AccessPlannedQuery, VisibleIndexes},
25 },
26 },
27 model::entity::EntityModel,
28 traits::{EntityKind, EntityValue},
29 value::Value,
30};
31
32#[cfg(test)]
33pub(in crate::db) use descriptor::assemble_load_execution_node_descriptor;
34use descriptor::assemble_load_execution_verbose_diagnostics_from_route_facts;
35#[cfg(feature = "sql-explain")]
36pub(in crate::db) use descriptor::assemble_scalar_aggregate_execution_descriptor_with_projection;
37pub(in crate::db) use descriptor::{
38 assemble_aggregate_terminal_execution_descriptor,
39 assemble_load_execution_node_descriptor_for_authority,
40 assemble_load_execution_node_descriptor_from_route_facts,
41 freeze_load_execution_route_facts_for_authority,
42 freeze_load_execution_route_facts_for_model_only,
43};
44
45struct DescriptorStagePresence {
46 present: [bool; Self::STAGE_COUNT],
47}
48
49impl DescriptorStagePresence {
50 const STAGE_COUNT: usize = 4;
51 const TOP_N_SEEK: usize = 0;
52 const INDEX_RANGE_LIMIT_PUSHDOWN: usize = 1;
53 const INDEX_PREDICATE_PREFILTER: usize = 2;
54 const RESIDUAL_FILTER: usize = 3;
55
56 fn from_descriptor(descriptor: &ExplainExecutionNodeDescriptor) -> Self {
57 let mut presence = Self {
58 present: [false; Self::STAGE_COUNT],
59 };
60
61 descriptor.for_each_preorder(&mut |node| match node.node_type() {
62 ExplainExecutionNodeType::TopNSeek => presence.present[Self::TOP_N_SEEK] = true,
63 ExplainExecutionNodeType::IndexRangeLimitPushdown => {
64 presence.present[Self::INDEX_RANGE_LIMIT_PUSHDOWN] = true;
65 }
66 ExplainExecutionNodeType::IndexPredicatePrefilter => {
67 presence.present[Self::INDEX_PREDICATE_PREFILTER] = true;
68 }
69 ExplainExecutionNodeType::ResidualFilter => {
70 presence.present[Self::RESIDUAL_FILTER] = true;
71 }
72 _ => {}
73 });
74
75 presence
76 }
77
78 const fn has_top_n_seek(&self) -> bool {
79 self.present[Self::TOP_N_SEEK]
80 }
81
82 const fn has_index_range_limit_pushdown(&self) -> bool {
83 self.present[Self::INDEX_RANGE_LIMIT_PUSHDOWN]
84 }
85
86 const fn has_index_predicate_prefilter(&self) -> bool {
87 self.present[Self::INDEX_PREDICATE_PREFILTER]
88 }
89
90 const fn has_residual_filter(&self) -> bool {
91 self.present[Self::RESIDUAL_FILTER]
92 }
93}
94
95impl StructuralQuery {
96 fn finalized_execution_diagnostics_from_route_facts(
99 plan: &AccessPlannedQuery,
100 route_facts: &crate::db::executor::explain::descriptor::LoadExecutionRouteFacts,
101 reuse: Option<TraceReuseEvent>,
102 ) -> FinalizedQueryDiagnostics {
103 let descriptor =
104 assemble_load_execution_node_descriptor_from_route_facts(plan, route_facts);
105 let route_diagnostics =
106 assemble_load_execution_verbose_diagnostics_from_route_facts(plan, route_facts);
107 let explain = plan.explain();
108
109 let stage_presence = DescriptorStagePresence::from_descriptor(&descriptor);
111 let mut logical_diagnostics = Vec::new();
112 logical_diagnostics.push(format!(
113 "diag.d.has_top_n_seek={}",
114 stage_presence.has_top_n_seek()
115 ));
116 logical_diagnostics.push(format!(
117 "diag.d.has_index_range_limit_pushdown={}",
118 stage_presence.has_index_range_limit_pushdown()
119 ));
120 logical_diagnostics.push(format!(
121 "diag.d.has_index_predicate_prefilter={}",
122 stage_presence.has_index_predicate_prefilter()
123 ));
124 logical_diagnostics.push(format!(
125 "diag.d.has_residual_filter={}",
126 stage_presence.has_residual_filter()
127 ));
128
129 logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
131 logical_diagnostics.push(format!(
132 "diag.p.order_pushdown={}",
133 plan_order_pushdown_label(explain.order_pushdown())
134 ));
135 logical_diagnostics.push(format!(
136 "diag.p.predicate_pushdown={}",
137 plan.predicate_pushdown_label()
138 ));
139 logical_diagnostics.push(format!(
140 "diag.p.predicate_pushdown_outcome={}",
141 plan.predicate_pushdown_outcome_label()
142 ));
143 logical_diagnostics.push(format!(
144 "diag.p.predicate_pushdown_reason={}",
145 plan.predicate_pushdown_reason_label()
146 ));
147 logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
148 logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
149 logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
150
151 FinalizedQueryDiagnostics::new(descriptor, route_diagnostics, logical_diagnostics, reuse)
152 }
153
154 pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
158 &self,
159 plan: &AccessPlannedQuery,
160 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
161 let primary_key_names = model_primary_key_names(self.model());
162 let route_facts = freeze_load_execution_route_facts_for_model_only(
163 self.model().fields(),
164 primary_key_names.as_slice(),
165 plan,
166 )
167 .map_err(QueryError::execute)?;
168
169 Ok(assemble_load_execution_node_descriptor_from_route_facts(
170 plan,
171 &route_facts,
172 ))
173 }
174
175 pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
177 &self,
178 plan: &AccessPlannedQuery,
179 authority: &EntityAuthority,
180 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
181 debug_assert_eq!(self.model().path(), authority.entity_path());
182 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
183 .map_err(QueryError::execute)?;
184
185 Ok(assemble_load_execution_node_descriptor_from_route_facts(
186 plan,
187 &route_facts,
188 ))
189 }
190
191 fn finalized_execution_diagnostics_from_model_only_plan(
196 &self,
197 plan: &AccessPlannedQuery,
198 reuse: Option<TraceReuseEvent>,
199 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
200 let primary_key_names = model_primary_key_names(self.model());
201 let route_facts = freeze_load_execution_route_facts_for_model_only(
202 self.model().fields(),
203 primary_key_names.as_slice(),
204 plan,
205 )
206 .map_err(QueryError::execute)?;
207
208 Ok(Self::finalized_execution_diagnostics_from_route_facts(
209 plan,
210 &route_facts,
211 reuse,
212 ))
213 }
214
215 pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
218 &self,
219 plan: &AccessPlannedQuery,
220 authority: &EntityAuthority,
221 reuse: Option<TraceReuseEvent>,
222 mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
223 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
224 debug_assert_eq!(self.model().path(), authority.entity_path());
225 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
226 .map_err(QueryError::execute)?;
227 let mut diagnostics =
228 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse);
229 mutate_descriptor(&mut diagnostics.execution);
230
231 Ok(diagnostics)
232 }
233
234 fn explain_execution_verbose_from_plan(
237 &self,
238 plan: &AccessPlannedQuery,
239 ) -> Result<String, QueryError> {
240 self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
241 .map(|diagnostics| diagnostics.render_text_verbose())
242 }
243
244 fn finalize_explain_access_choice_for_visible_indexes(
247 &self,
248 plan: &mut AccessPlannedQuery,
249 visible_indexes: &VisibleIndexes<'_>,
250 ) {
251 if let Some(schema_info) = visible_indexes.accepted_schema_info() {
252 plan.finalize_access_choice_for_model_with_semantic_indexes_and_schema(
253 self.model(),
254 visible_indexes.accepted_semantic_index_contracts(),
255 schema_info,
256 );
257 return;
258 }
259
260 plan.finalize_access_choice_for_model_only_with_indexes(
261 self.model(),
262 visible_indexes.generated_model_only_indexes(),
263 );
264 }
265
266 fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
270 plan.finalize_access_choice_for_model_only_with_indexes(
271 self.model(),
272 self.model().indexes(),
273 );
274 }
275
276 fn finalized_model_only_explain_plan(&self) -> Result<AccessPlannedQuery, QueryError> {
279 let mut plan = self.build_plan()?;
280 self.finalize_explain_access_choice_for_model_only(&mut plan);
281
282 Ok(plan)
283 }
284
285 fn finalized_visible_indexes_explain_plan(
288 &self,
289 visible_indexes: &VisibleIndexes<'_>,
290 ) -> Result<AccessPlannedQuery, QueryError> {
291 let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
292 self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
293
294 Ok(plan)
295 }
296
297 fn explain_execution_descriptor_for_model_only(
300 &self,
301 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
302 let plan = self.finalized_model_only_explain_plan()?;
303
304 self.explain_execution_descriptor_from_model_only_plan(&plan)
305 }
306
307 fn explain_execution_descriptor_for_visible_indexes(
310 &self,
311 visible_indexes: &VisibleIndexes<'_>,
312 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
313 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
314
315 self.explain_execution_descriptor_from_model_only_plan(&plan)
316 }
317
318 fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
321 let plan = self.finalized_model_only_explain_plan()?;
322
323 self.explain_execution_verbose_from_plan(&plan)
324 }
325
326 fn explain_execution_verbose_for_visible_indexes(
329 &self,
330 visible_indexes: &VisibleIndexes<'_>,
331 ) -> Result<String, QueryError> {
332 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
333
334 self.explain_execution_verbose_from_plan(&plan)
335 }
336
337 #[inline(never)]
339 pub(in crate::db) fn explain_execution_for_model_only(
340 &self,
341 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
342 self.explain_execution_descriptor_for_model_only()
343 }
344
345 #[inline(never)]
347 pub(in crate::db) fn explain_execution_with_visible_indexes(
348 &self,
349 visible_indexes: &VisibleIndexes<'_>,
350 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
351 self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
352 }
353
354 #[inline(never)]
357 pub(in crate::db) fn explain_execution_verbose_for_model_only(
358 &self,
359 ) -> Result<String, QueryError> {
360 self.render_execution_verbose_for_model_only()
361 }
362
363 #[inline(never)]
365 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
366 &self,
367 visible_indexes: &VisibleIndexes<'_>,
368 ) -> Result<String, QueryError> {
369 self.explain_execution_verbose_for_visible_indexes(visible_indexes)
370 }
371
372 #[inline(never)]
374 #[cfg(test)]
375 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
376 &self,
377 visible_indexes: &VisibleIndexes<'_>,
378 aggregate: AggregateRouteShape<'_>,
379 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
380 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
381 let query_explain = plan.explain();
382 let terminal = aggregate.kind();
383 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
384
385 Ok(ExplainAggregateTerminalPlan::new(
386 query_explain,
387 terminal,
388 execution,
389 ))
390 }
391}
392
393impl SharedPreparedExecutionPlan {
394 pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
396 &self,
397 strategy: &S,
398 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
399 where
400 S: AggregateExplain,
401 {
402 let Some(kind) = strategy.explain_aggregate_kind() else {
403 return Err(QueryError::invariant());
404 };
405 let aggregate = self
406 .authority_ref()
407 .aggregate_route_shape(kind, strategy.explain_projected_field())
408 .map_err(QueryError::execute)?;
409 let execution =
410 assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate);
411
412 Ok(ExplainAggregateTerminalPlan::new(
413 self.logical_plan().explain(),
414 kind,
415 execution,
416 ))
417 }
418
419 fn explain_prepared_terminal_load_descriptor(
420 &self,
421 terminal_label: &str,
422 field_label: &str,
423 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
424 let mut descriptor = assemble_load_execution_node_descriptor_for_authority(
425 self.authority_ref(),
426 self.logical_plan(),
427 )
428 .map_err(QueryError::execute)?;
429
430 descriptor
431 .node_properties
432 .insert(property_keys::TERMINAL, Value::from(terminal_label));
433 descriptor.node_properties.insert(
434 property_keys::TERMINAL_FIELD,
435 Value::from(field_label.to_string()),
436 );
437
438 Ok(descriptor)
439 }
440
441 pub(in crate::db) fn explain_bytes_by_terminal(
443 &self,
444 target_field: &str,
445 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
446 let mut descriptor =
447 self.explain_prepared_terminal_load_descriptor("bytes_by", target_field)?;
448 let projection_mode = self.bytes_by_projection_mode(target_field);
449
450 descriptor.node_properties.insert(
451 property_keys::TERMINAL_PROJECTION_MODE,
452 Value::from(projection_mode.label()),
453 );
454 descriptor.node_properties.insert(
455 property_keys::TERMINAL_INDEX_ONLY,
456 Value::from(projection_mode.is_index_only()),
457 );
458
459 Ok(descriptor)
460 }
461
462 pub(in crate::db) fn explain_prepared_projection_terminal<S>(
464 &self,
465 strategy: &S,
466 ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
467 where
468 S: ProjectionExplain,
469 {
470 let projection_descriptor = strategy.explain_projection_descriptor();
471 let mut descriptor = self.explain_prepared_terminal_load_descriptor(
472 projection_descriptor.terminal_label(),
473 projection_descriptor.field_label(),
474 )?;
475 descriptor.node_properties.insert(
476 property_keys::TERMINAL_OUTPUT,
477 Value::from(projection_descriptor.output_label()),
478 );
479
480 Ok(descriptor)
481 }
482}
483
484impl<E> Query<E>
485where
486 E: EntityValue + EntityKind,
487{
488 fn explain_execution_descriptor_for_model_only_or_visible_indexes(
491 &self,
492 visible_indexes: Option<&VisibleIndexes<'_>>,
493 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
494 match visible_indexes {
495 Some(visible_indexes) => self
496 .structural()
497 .explain_execution_with_visible_indexes(visible_indexes),
498 None => self.structural().explain_execution_for_model_only(),
499 }
500 }
501
502 fn render_execution_descriptor_for_visibility(
505 &self,
506 visible_indexes: Option<&VisibleIndexes<'_>>,
507 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
508 ) -> Result<String, QueryError> {
509 let descriptor =
510 self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
511
512 Ok(render(descriptor))
513 }
514
515 fn explain_execution_verbose_for_model_only_or_visible_indexes(
518 &self,
519 visible_indexes: Option<&VisibleIndexes<'_>>,
520 ) -> Result<String, QueryError> {
521 match visible_indexes {
522 Some(visible_indexes) => self
523 .structural()
524 .explain_execution_verbose_with_visible_indexes(visible_indexes),
525 None => self.structural().explain_execution_verbose_for_model_only(),
526 }
527 }
528
529 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
531 self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
532 }
533
534 #[cfg(test)]
536 pub(in crate::db) fn explain_execution_with_visible_indexes(
537 &self,
538 visible_indexes: &VisibleIndexes<'_>,
539 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
540 self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
541 }
542
543 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
545 self.render_execution_descriptor_for_visibility(None, |descriptor| {
546 descriptor.render_text_tree()
547 })
548 }
549
550 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
552 self.render_execution_descriptor_for_visibility(None, |descriptor| {
553 descriptor.render_json_canonical()
554 })
555 }
556
557 #[inline(never)]
559 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
560 self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
561 }
562
563 #[cfg(test)]
565 #[inline(never)]
566 pub(in crate::db) fn explain_aggregate_terminal(
567 &self,
568 aggregate: AggregateExpr,
569 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
570 self.structural()
571 .explain_aggregate_terminal_with_visible_indexes(
572 &VisibleIndexes::generated_model_only(E::MODEL.indexes()),
573 AggregateRouteShape::new_from_fields(
574 aggregate.kind(),
575 aggregate.target_field(),
576 E::MODEL.fields(),
577 model_primary_key_names(E::MODEL).as_slice(),
578 ),
579 )
580 }
581}
582
583fn model_primary_key_names(model: &EntityModel) -> Vec<&'static str> {
584 model
585 .primary_key_model()
586 .fields()
587 .iter()
588 .map(crate::model::field::FieldModel::name)
589 .collect()
590}
591
592fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
594 match order_pushdown {
595 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
596 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
597 format!("eligible(index={index},prefix_len={prefix_len})")
598 }
599 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
600 }
601}