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 let explain = plan.explain();
109
110 let stage_presence = DescriptorStagePresence::from_descriptor(&descriptor);
112 let mut logical_diagnostics = Vec::new();
113 logical_diagnostics.push(format!(
114 "diag.d.has_top_n_seek={}",
115 stage_presence.has_top_n_seek()
116 ));
117 logical_diagnostics.push(format!(
118 "diag.d.has_index_range_limit_pushdown={}",
119 stage_presence.has_index_range_limit_pushdown()
120 ));
121 logical_diagnostics.push(format!(
122 "diag.d.has_index_predicate_prefilter={}",
123 stage_presence.has_index_predicate_prefilter()
124 ));
125 logical_diagnostics.push(format!(
126 "diag.d.has_residual_filter={}",
127 stage_presence.has_residual_filter()
128 ));
129
130 logical_diagnostics.push(format!("diag.p.mode={:?}", explain.mode()));
132 logical_diagnostics.push(format!(
133 "diag.p.order_pushdown={}",
134 plan_order_pushdown_label(explain.order_pushdown())
135 ));
136 logical_diagnostics.push(format!(
137 "diag.p.predicate_pushdown={}",
138 plan.predicate_pushdown_label()
139 ));
140 logical_diagnostics.push(format!(
141 "diag.p.predicate_pushdown_outcome={}",
142 plan.predicate_pushdown_outcome_label()
143 ));
144 logical_diagnostics.push(format!(
145 "diag.p.predicate_pushdown_reason={}",
146 plan.predicate_pushdown_reason_label()
147 ));
148 logical_diagnostics.push(format!("diag.p.distinct={}", explain.distinct()));
149 logical_diagnostics.push(format!("diag.p.page={:?}", explain.page()));
150 logical_diagnostics.push(format!("diag.p.consistency={:?}", explain.consistency()));
151
152 Ok(FinalizedQueryDiagnostics::new(
153 descriptor,
154 route_diagnostics,
155 logical_diagnostics,
156 reuse,
157 ))
158 }
159
160 pub(in crate::db) fn explain_execution_descriptor_from_model_only_plan(
164 &self,
165 plan: &AccessPlannedQuery,
166 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
167 let primary_key_names = model_primary_key_names(self.model());
168 let route_facts = freeze_load_execution_route_facts_for_model_only(
169 self.model().fields(),
170 primary_key_names.as_slice(),
171 plan,
172 )
173 .map_err(QueryError::execute)?;
174
175 assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts)
176 .map_err(QueryError::execute)
177 }
178
179 pub(in crate::db) fn explain_execution_descriptor_from_plan_with_authority(
181 &self,
182 plan: &AccessPlannedQuery,
183 authority: &EntityAuthority,
184 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
185 debug_assert_eq!(self.model().path(), authority.entity_path());
186 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
187 .map_err(QueryError::execute)?;
188
189 assemble_load_execution_node_descriptor_from_route_facts(plan, &route_facts)
190 .map_err(QueryError::execute)
191 }
192
193 fn finalized_execution_diagnostics_from_model_only_plan(
198 &self,
199 plan: &AccessPlannedQuery,
200 reuse: Option<TraceReuseEvent>,
201 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
202 let primary_key_names = model_primary_key_names(self.model());
203 let route_facts = freeze_load_execution_route_facts_for_model_only(
204 self.model().fields(),
205 primary_key_names.as_slice(),
206 plan,
207 )
208 .map_err(QueryError::execute)?;
209
210 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse)
211 }
212
213 pub(in crate::db) fn finalized_execution_diagnostics_from_plan_with_authority_and_descriptor_mutator(
216 &self,
217 plan: &AccessPlannedQuery,
218 authority: &EntityAuthority,
219 reuse: Option<TraceReuseEvent>,
220 mutate_descriptor: impl FnOnce(&mut ExplainExecutionNodeDescriptor),
221 ) -> Result<FinalizedQueryDiagnostics, QueryError> {
222 debug_assert_eq!(self.model().path(), authority.entity_path());
223 let route_facts = freeze_load_execution_route_facts_for_authority(authority, plan)
224 .map_err(QueryError::execute)?;
225 let mut diagnostics =
226 Self::finalized_execution_diagnostics_from_route_facts(plan, &route_facts, reuse)?;
227 mutate_descriptor(&mut diagnostics.execution);
228
229 Ok(diagnostics)
230 }
231
232 fn explain_execution_verbose_from_plan(
235 &self,
236 plan: &AccessPlannedQuery,
237 ) -> Result<String, QueryError> {
238 self.finalized_execution_diagnostics_from_model_only_plan(plan, None)
239 .map(|diagnostics| diagnostics.render_text_verbose())
240 }
241
242 fn finalize_explain_access_choice_for_visible_indexes(
245 &self,
246 plan: &mut AccessPlannedQuery,
247 visible_indexes: &VisibleIndexes<'_>,
248 ) {
249 if let Some(schema_info) = visible_indexes.accepted_schema_info() {
250 plan.finalize_access_choice_for_model_with_semantic_indexes_and_schema(
251 self.model(),
252 visible_indexes.accepted_semantic_index_contracts(),
253 schema_info,
254 );
255 return;
256 }
257
258 plan.finalize_access_choice_for_model_only_with_indexes(
259 self.model(),
260 visible_indexes.generated_model_only_indexes(),
261 );
262 }
263
264 fn finalize_explain_access_choice_for_model_only(&self, plan: &mut AccessPlannedQuery) {
268 plan.finalize_access_choice_for_model_only_with_indexes(
269 self.model(),
270 self.model().indexes(),
271 );
272 }
273
274 fn finalized_model_only_explain_plan(&self) -> Result<AccessPlannedQuery, QueryError> {
277 let mut plan = self.build_plan()?;
278 self.finalize_explain_access_choice_for_model_only(&mut plan);
279
280 Ok(plan)
281 }
282
283 fn finalized_visible_indexes_explain_plan(
286 &self,
287 visible_indexes: &VisibleIndexes<'_>,
288 ) -> Result<AccessPlannedQuery, QueryError> {
289 let mut plan = self.build_plan_with_visible_indexes(visible_indexes)?;
290 self.finalize_explain_access_choice_for_visible_indexes(&mut plan, visible_indexes);
291
292 Ok(plan)
293 }
294
295 fn explain_execution_descriptor_for_model_only(
298 &self,
299 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
300 let plan = self.finalized_model_only_explain_plan()?;
301
302 self.explain_execution_descriptor_from_model_only_plan(&plan)
303 }
304
305 fn explain_execution_descriptor_for_visible_indexes(
308 &self,
309 visible_indexes: &VisibleIndexes<'_>,
310 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
311 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
312
313 self.explain_execution_descriptor_from_model_only_plan(&plan)
314 }
315
316 fn render_execution_verbose_for_model_only(&self) -> Result<String, QueryError> {
319 let plan = self.finalized_model_only_explain_plan()?;
320
321 self.explain_execution_verbose_from_plan(&plan)
322 }
323
324 fn explain_execution_verbose_for_visible_indexes(
327 &self,
328 visible_indexes: &VisibleIndexes<'_>,
329 ) -> Result<String, QueryError> {
330 let plan = self.finalized_visible_indexes_explain_plan(visible_indexes)?;
331
332 self.explain_execution_verbose_from_plan(&plan)
333 }
334
335 #[inline(never)]
337 pub(in crate::db) fn explain_execution_for_model_only(
338 &self,
339 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
340 self.explain_execution_descriptor_for_model_only()
341 }
342
343 #[inline(never)]
345 pub(in crate::db) fn explain_execution_with_visible_indexes(
346 &self,
347 visible_indexes: &VisibleIndexes<'_>,
348 ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
349 self.explain_execution_descriptor_for_visible_indexes(visible_indexes)
350 }
351
352 #[inline(never)]
355 pub(in crate::db) fn explain_execution_verbose_for_model_only(
356 &self,
357 ) -> Result<String, QueryError> {
358 self.render_execution_verbose_for_model_only()
359 }
360
361 #[inline(never)]
363 pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
364 &self,
365 visible_indexes: &VisibleIndexes<'_>,
366 ) -> Result<String, QueryError> {
367 self.explain_execution_verbose_for_visible_indexes(visible_indexes)
368 }
369
370 #[inline(never)]
372 #[cfg(test)]
373 pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
374 &self,
375 visible_indexes: &VisibleIndexes<'_>,
376 aggregate: AggregateRouteShape<'_>,
377 ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
378 let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
379 let query_explain = plan.explain();
380 let terminal = aggregate.kind();
381 let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate)
382 .map_err(QueryError::execute)?;
383
384 Ok(ExplainAggregateTerminalPlan::new(
385 query_explain,
386 terminal,
387 execution,
388 ))
389 }
390}
391
392impl SharedPreparedExecutionPlan {
393 pub(in crate::db) fn explain_prepared_aggregate_terminal<S>(
395 &self,
396 strategy: &S,
397 ) -> Result<ExplainAggregateTerminalPlan, QueryError>
398 where
399 S: AggregateExplain,
400 {
401 let Some(kind) = strategy.explain_aggregate_kind() else {
402 return Err(QueryError::invariant());
403 };
404 let aggregate = self
405 .authority_ref()
406 .aggregate_route_shape(kind, strategy.explain_projected_field())
407 .map_err(QueryError::execute)?;
408 let execution =
409 assemble_aggregate_terminal_execution_descriptor(self.logical_plan(), aggregate)
410 .map_err(QueryError::execute)?;
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}