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 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
103 let descriptor =
104 assemble_load_execution_node_descriptor_from_route_facts(plan, route_facts)
105 .map_err(QueryError::execute)?;
106 let route_diagnostics =
107 assemble_load_execution_verbose_diagnostics_from_route_facts(plan, route_facts)
108 .map_err(QueryError::execute)?;
109 let explain = plan.explain();
110
111 let stage_presence = DescriptorStagePresence::from_descriptor(&descriptor);
113 let mut logical_diagnostics = Vec::new();
114 logical_diagnostics.push(format!(
115 "diag.d.has_top_n_seek={}",
116 stage_presence.has_top_n_seek()
117 ));
118 logical_diagnostics.push(format!(
119 "diag.d.has_index_range_limit_pushdown={}",
120 stage_presence.has_index_range_limit_pushdown()
121 ));
122 logical_diagnostics.push(format!(
123 "diag.d.has_index_predicate_prefilter={}",
124 stage_presence.has_index_predicate_prefilter()
125 ));
126 logical_diagnostics.push(format!(
127 "diag.d.has_residual_filter={}",
128 stage_presence.has_residual_filter()
129 ));
130
131 logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
133 logical_diagnostics.push(format!(
134 "diag.p.order_pushdown={}",
135 plan_order_pushdown_label(explain.order_pushdown())
136 ));
137 logical_diagnostics.push(format!(
138 "diag.p.predicate_pushdown={}",
139 plan.predicate_pushdown_label()
140 ));
141 logical_diagnostics.push(format!(
142 "diag.p.predicate_pushdown_outcome={}",
143 plan.predicate_pushdown_outcome_label()
144 ));
145 logical_diagnostics.push(format!(
146 "diag.p.predicate_pushdown_reason={}",
147 plan.predicate_pushdown_reason_label()
148 ));
149 logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
150 logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
151 logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
152
153 Ok(FinalizedQueryDiagnostics::new(
154 descriptor,
155 route_diagnostics,
156 logical_diagnostics,
157 reuse,
158 ))
159 }
160
161 pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
165 &self,
166 plan: &AccessPlannedQuery,
167 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
168 let primary_key_names = model_primary_key_names(self.model());
169 let route_facts = freeze_load_execution_route_facts_for_model_only(
170 self.model().fields(),
171 primary_key_names.as_slice(),
172 plan,
173 )
174 .map_err(QueryError::execute)?;
175
176 assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts)
177 .map_err(QueryError::execute)
178 }
179
180 pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
182 &self,
183 plan: &AccessPlannedQuery,
184 authority: &EntityAuthority,
185 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
186 debug_assert_eq!(self.model().path(), authority.entity_path());
187 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
188 .map_err(QueryError::execute)?;
189
190 assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts)
191 .map_err(QueryError::execute)
192 }
193
194 fn finalized_execution_diagnostics_from_model_only_plan(
199 &self,
200 plan: &AccessPlannedQuery,
201 reuse: Option<TraceReuseEvent>,
202 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
203 let primary_key_names = model_primary_key_names(self.model());
204 let route_facts = freeze_load_execution_route_facts_for_model_only(
205 self.model().fields(),
206 primary_key_names.as_slice(),
207 plan,
208 )
209 .map_err(QueryError::execute)?;
210
211 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse)
212 }
213
214 pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
217 &self,
218 plan: &AccessPlannedQuery,
219 authority: &EntityAuthority,
220 reuse: Option<TraceReuseEvent>,
221 mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
222 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
223 debug_assert_eq!(self.model().path(), authority.entity_path());
224 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
225 .map_err(QueryError::execute)?;
226 let mut diagnostics =
227 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse)?;
228 mutate_descriptor(&mut diagnostics.execution);
229
230 Ok(diagnostics)
231 }
232
233 fn explain_execution_verbose_from_plan(
236 &self,
237 plan: &AccessPlannedQuery,
238 ) -> Result<String, QueryError> {
239 self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
240 .map(|diagnostics| diagnostics.render_text_verbose())
241 }
242
243 fn finalize_explain_access_choice_for_visible_indexes(
246 &self,
247 plan: &mut AccessPlannedQuery,
248 visible_indexes: &VisibleIndexes<'_>,
249 ) {
250 if let Some(schema_info) = visible_indexes.accepted_schema_info() {
251 plan.finalize_access_choice_for_model_with_semantic_indexes_and_schema(
252 self.model(),
253 visible_indexes.accepted_semantic_index_contracts(),
254 schema_info,
255 );
256 return;
257 }
258
259 plan.finalize_access_choice_for_model_only_with_indexes(
260 self.model(),
261 visible_indexes.generated_model_only_indexes(),
262 );
263 }
264
265 fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
269 plan.finalize_access_choice_for_model_only_with_indexes(
270 self.model(),
271 self.model().indexes(),
272 );
273 }
274
275 fn finalized_model_only_explain_plan(&self) -> Result<AccessPlannedQuery, QueryError> {
278 let mut plan = self.build_plan()?;
279 self.finalize_explain_access_choice_for_model_only(&mut plan);
280
281 Ok(plan)
282 }
283
284 fn finalized_visible_indexes_explain_plan(
287 &self,
288 visible_indexes: &VisibleIndexes<'_>,
289 ) -> Result<AccessPlannedQuery, QueryError> {
290 let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
291 self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
292
293 Ok(plan)
294 }
295
296 fn explain_execution_descriptor_for_model_only(
299 &self,
300 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
301 let plan = self.finalized_model_only_explain_plan()?;
302
303 self.explain_execution_descriptor_from_model_only_plan(&plan)
304 }
305
306 fn explain_execution_descriptor_for_visible_indexes(
309 &self,
310 visible_indexes: &VisibleIndexes<'_>,
311 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
312 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
313
314 self.explain_execution_descriptor_from_model_only_plan(&plan)
315 }
316
317 fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
320 let plan = self.finalized_model_only_explain_plan()?;
321
322 self.explain_execution_verbose_from_plan(&plan)
323 }
324
325 fn explain_execution_verbose_for_visible_indexes(
328 &self,
329 visible_indexes: &VisibleIndexes<'_>,
330 ) -> Result<String, QueryError> {
331 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
332
333 self.explain_execution_verbose_from_plan(&plan)
334 }
335
336 #[inline(never)]
338 pub(in crate::db) fn explain_execution_for_model_only(
339 &self,
340 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
341 self.explain_execution_descriptor_for_model_only()
342 }
343
344 #[inline(never)]
346 pub(in crate::db) fn explain_execution_with_visible_indexes(
347 &self,
348 visible_indexes: &VisibleIndexes<'_>,
349 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
350 self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
351 }
352
353 #[inline(never)]
356 pub(in crate::db) fn explain_execution_verbose_for_model_only(
357 &self,
358 ) -> Result<String, QueryError> {
359 self.render_execution_verbose_for_model_only()
360 }
361
362 #[inline(never)]
364 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
365 &self,
366 visible_indexes: &VisibleIndexes<'_>,
367 ) -> Result<String, QueryError> {
368 self.explain_execution_verbose_for_visible_indexes(visible_indexes)
369 }
370
371 #[inline(never)]
373 #[cfg(test)]
374 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
375 &self,
376 visible_indexes: &VisibleIndexes<'_>,
377 aggregate: AggregateRouteShape<'_>,
378 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
379 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
380 let query_explain = plan.explain();
381 let terminal = aggregate.kind();
382 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate)
383 .map_err(QueryError::execute)?;
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 .map_err(QueryError::execute)?;
412
413 Ok(ExplainAggregateTerminalPlan::new(
414 self.logical_plan().explain(),
415 kind,
416 execution,
417 ))
418 }
419
420 fn explain_prepared_terminal_load_descriptor(
421 &self,
422 terminal_label: &str,
423 field_label: &str,
424 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
425 let mut descriptor = assemble_load_execution_node_descriptor_for_authority(
426 self.authority_ref(),
427 self.logical_plan(),
428 )
429 .map_err(QueryError::execute)?;
430
431 descriptor
432 .node_properties
433 .insert(property_keys::TERMINAL, Value::from(terminal_label));
434 descriptor.node_properties.insert(
435 property_keys::TERMINAL_FIELD,
436 Value::from(field_label.to_string()),
437 );
438
439 Ok(descriptor)
440 }
441
442 pub(in crate::db) fn explain_bytes_by_terminal(
444 &self,
445 target_field: &str,
446 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
447 let mut descriptor =
448 self.explain_prepared_terminal_load_descriptor("bytes_by", target_field)?;
449 let projection_mode = self.bytes_by_projection_mode(target_field);
450
451 descriptor.node_properties.insert(
452 property_keys::TERMINAL_PROJECTION_MODE,
453 Value::from(projection_mode.label()),
454 );
455 descriptor.node_properties.insert(
456 property_keys::TERMINAL_INDEX_ONLY,
457 Value::from(projection_mode.is_index_only()),
458 );
459
460 Ok(descriptor)
461 }
462
463 pub(in crate::db) fn explain_prepared_projection_terminal<S>(
465 &self,
466 strategy: &S,
467 ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
468 where
469 S: ProjectionExplain,
470 {
471 let projection_descriptor = strategy.explain_projection_descriptor();
472 let mut descriptor = self.explain_prepared_terminal_load_descriptor(
473 projection_descriptor.terminal_label(),
474 projection_descriptor.field_label(),
475 )?;
476 descriptor.node_properties.insert(
477 property_keys::TERMINAL_OUTPUT,
478 Value::from(projection_descriptor.output_label()),
479 );
480
481 Ok(descriptor)
482 }
483}
484
485impl<E> Query<E>
486where
487 E: EntityValue + EntityKind,
488{
489 fn explain_execution_descriptor_for_model_only_or_visible_indexes(
492 &self,
493 visible_indexes: Option<&VisibleIndexes<'_>>,
494 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
495 match visible_indexes {
496 Some(visible_indexes) => self
497 .structural()
498 .explain_execution_with_visible_indexes(visible_indexes),
499 None => self.structural().explain_execution_for_model_only(),
500 }
501 }
502
503 fn render_execution_descriptor_for_visibility(
506 &self,
507 visible_indexes: Option<&VisibleIndexes<'_>>,
508 render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
509 ) -> Result<String, QueryError> {
510 let descriptor =
511 self.explain_execution_descriptor_for_model_only_or_visible_indexes(visible_indexes)?;
512
513 Ok(render(descriptor))
514 }
515
516 fn explain_execution_verbose_for_model_only_or_visible_indexes(
519 &self,
520 visible_indexes: Option<&VisibleIndexes<'_>>,
521 ) -> Result<String, QueryError> {
522 match visible_indexes {
523 Some(visible_indexes) => self
524 .structural()
525 .explain_execution_verbose_with_visible_indexes(visible_indexes),
526 None => self.structural().explain_execution_verbose_for_model_only(),
527 }
528 }
529
530 pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
532 self.explain_execution_descriptor_for_model_only_or_visible_indexes(None)
533 }
534
535 #[cfg(test)]
537 pub(in crate::db) fn explain_execution_with_visible_indexes(
538 &self,
539 visible_indexes: &VisibleIndexes<'_>,
540 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
541 self.explain_execution_descriptor_for_model_only_or_visible_indexes(Some(visible_indexes))
542 }
543
544 pub fn explain_execution_text(&self) -> Result<String, QueryError> {
546 self.render_execution_descriptor_for_visibility(None, |descriptor| {
547 descriptor.render_text_tree()
548 })
549 }
550
551 pub fn explain_execution_json(&self) -> Result<String, QueryError> {
553 self.render_execution_descriptor_for_visibility(None, |descriptor| {
554 descriptor.render_json_canonical()
555 })
556 }
557
558 #[inline(never)]
560 pub fn explain_execution_verbose(&self) -> Result<String, QueryError> {
561 self.explain_execution_verbose_for_model_only_or_visible_indexes(None)
562 }
563
564 #[cfg(test)]
566 #[inline(never)]
567 pub(in crate::db) fn explain_aggregate_terminal(
568 &self,
569 aggregate: AggregateExpr,
570 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
571 self.structural()
572 .explain_aggregate_terminal_with_visible_indexes(
573 &VisibleIndexes::generated_model_only(E::MODEL.indexes()),
574 AggregateRouteShape::new_from_fields(
575 aggregate.kind(),
576 aggregate.target_field(),
577 E::MODEL.fields(),
578 model_primary_key_names(E::MODEL).as_slice(),
579 ),
580 )
581 }
582}
583
584fn model_primary_key_names(model: &EntityModel) -> Vec<&'static str> {
585 model
586 .primary_key_model()
587 .fields()
588 .iter()
589 .map(crate::model::field::FieldModel::name)
590 .collect()
591}
592
593fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
595 match order_pushdown {
596 ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
597 ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
598 format!("eligible(index={index},prefix_len={prefix_len})")
599 }
600 ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
601 }
602}