1mod aggregate;
2pub(in crate::db::executor) mod aggregate_field;
3mod aggregate_guard;
4mod execute;
5mod fast_stream;
6mod index_range_limit;
7mod page;
8mod pk_stream;
9mod secondary_index;
10mod trace;
11
12use self::{
13 execute::{ExecutionInputs, IndexPredicateCompileMode},
14 trace::{access_path_variant, execution_order_direction},
15};
16use crate::{
17 db::{
18 Db,
19 executor::{
20 AccessStreamBindings, KeyOrderComparator, OrderedKeyStreamBox,
21 plan::{record_plan_metrics, record_rows_scanned},
22 route::ExecutionRoutePlan,
23 },
24 query::plan::{
25 AccessPlan, CursorBoundary, Direction, ExecutablePlan, LogicalPlan, OrderDirection,
26 PlannedCursor, SlotSelectionPolicy, compute_page_window, decode_pk_cursor_boundary,
27 derive_scan_direction, validate::validate_executor_plan,
28 },
29 response::Response,
30 },
31 error::InternalError,
32 obs::sink::{ExecKind, Span},
33 traits::{EntityKind, EntityValue},
34};
35use std::marker::PhantomData;
36
37#[derive(Debug)]
45pub(crate) struct CursorPage<E: EntityKind> {
46 pub(crate) items: Response<E>,
47
48 pub(crate) next_cursor: Option<Vec<u8>>,
49}
50
51#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum ExecutionAccessPathVariant {
59 ByKey,
60 ByKeys,
61 KeyRange,
62 IndexPrefix,
63 IndexRange,
64 FullScan,
65 Union,
66 Intersection,
67}
68
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
76pub enum ExecutionOptimization {
77 PrimaryKey,
78 SecondaryOrderPushdown,
79 IndexRangeLimitPushdown,
80}
81
82#[derive(Clone, Copy, Debug, Eq, PartialEq)]
90pub struct ExecutionTrace {
91 pub access_path_variant: ExecutionAccessPathVariant,
92 pub direction: OrderDirection,
93 pub optimization: Option<ExecutionOptimization>,
94 pub keys_scanned: u64,
95 pub rows_returned: u64,
96 pub continuation_applied: bool,
97 pub index_predicate_applied: bool,
98 pub index_predicate_keys_rejected: u64,
99 pub distinct_keys_deduped: u64,
100}
101
102impl ExecutionTrace {
103 fn new<K>(access: &AccessPlan<K>, direction: Direction, continuation_applied: bool) -> Self {
104 Self {
105 access_path_variant: access_path_variant(access),
106 direction: execution_order_direction(direction),
107 optimization: None,
108 keys_scanned: 0,
109 rows_returned: 0,
110 continuation_applied,
111 index_predicate_applied: false,
112 index_predicate_keys_rejected: 0,
113 distinct_keys_deduped: 0,
114 }
115 }
116
117 fn set_path_outcome(
118 &mut self,
119 optimization: Option<ExecutionOptimization>,
120 keys_scanned: usize,
121 rows_returned: usize,
122 index_predicate_applied: bool,
123 index_predicate_keys_rejected: u64,
124 distinct_keys_deduped: u64,
125 ) {
126 self.optimization = optimization;
127 self.keys_scanned = u64::try_from(keys_scanned).unwrap_or(u64::MAX);
128 self.rows_returned = u64::try_from(rows_returned).unwrap_or(u64::MAX);
129 self.index_predicate_applied = index_predicate_applied;
130 self.index_predicate_keys_rejected = index_predicate_keys_rejected;
131 self.distinct_keys_deduped = distinct_keys_deduped;
132 }
133}
134
135fn key_stream_comparator_from_plan<K>(
136 plan: &LogicalPlan<K>,
137 fallback_direction: Direction,
138) -> KeyOrderComparator {
139 let derived_direction = plan.order.as_ref().map_or(fallback_direction, |order| {
140 derive_scan_direction(order, SlotSelectionPolicy::Last)
141 });
142
143 let comparator_direction = if derived_direction == fallback_direction {
146 derived_direction
147 } else {
148 fallback_direction
149 };
150
151 KeyOrderComparator::from_direction(comparator_direction)
152}
153
154struct FastPathKeyResult {
162 ordered_key_stream: OrderedKeyStreamBox,
163 rows_scanned: usize,
164 optimization: ExecutionOptimization,
165}
166
167#[derive(Clone)]
175pub(crate) struct LoadExecutor<E: EntityKind> {
176 db: Db<E::Canister>,
177 debug: bool,
178 _marker: PhantomData<E>,
179}
180
181impl<E> LoadExecutor<E>
182where
183 E: EntityKind + EntityValue,
184{
185 #[must_use]
186 pub(crate) const fn new(db: Db<E::Canister>, debug: bool) -> Self {
187 Self {
188 db,
189 debug,
190 _marker: PhantomData,
191 }
192 }
193
194 pub(crate) fn execute(&self, plan: ExecutablePlan<E>) -> Result<Response<E>, InternalError> {
195 self.execute_paged_with_cursor(plan, PlannedCursor::none())
196 .map(|page| page.items)
197 }
198
199 pub(in crate::db) fn execute_paged_with_cursor(
200 &self,
201 plan: ExecutablePlan<E>,
202 cursor: impl Into<PlannedCursor>,
203 ) -> Result<CursorPage<E>, InternalError> {
204 self.execute_paged_with_cursor_traced(plan, cursor)
205 .map(|(page, _)| page)
206 }
207
208 #[expect(clippy::too_many_lines)]
209 pub(in crate::db) fn execute_paged_with_cursor_traced(
210 &self,
211 plan: ExecutablePlan<E>,
212 cursor: impl Into<PlannedCursor>,
213 ) -> Result<(CursorPage<E>, Option<ExecutionTrace>), InternalError> {
214 let cursor: PlannedCursor = plan.revalidate_planned_cursor(cursor.into())?;
215 let cursor_boundary = cursor.boundary().cloned();
216 let index_range_anchor = cursor.index_range_anchor().cloned();
217
218 if !plan.mode().is_load() {
219 return Err(InternalError::query_executor_invariant(
220 "load executor requires load plans",
221 ));
222 }
223
224 let direction = plan.direction();
225 let continuation_signature = plan.continuation_signature();
226 let index_prefix_specs = plan.index_prefix_specs()?.to_vec();
227 let index_range_specs = plan.index_range_specs()?.to_vec();
228 let continuation_applied = cursor_boundary.is_some() || index_range_anchor.is_some();
229 let mut execution_trace = self
230 .debug
231 .then(|| ExecutionTrace::new(plan.access(), direction, continuation_applied));
232 let (plan, predicate_slots) = plan.into_parts();
233
234 let result = (|| {
235 let mut span = Span::<E>::new(ExecKind::Load);
236
237 validate_executor_plan::<E>(&plan)?;
238 let ctx = self.db.recovered_context::<E>()?;
239 let execution_inputs = ExecutionInputs {
240 ctx: &ctx,
241 plan: &plan,
242 stream_bindings: AccessStreamBindings {
243 index_prefix_specs: index_prefix_specs.as_slice(),
244 index_range_specs: index_range_specs.as_slice(),
245 index_range_anchor: index_range_anchor.as_ref(),
246 direction,
247 },
248 predicate_slots: predicate_slots.as_ref(),
249 };
250
251 record_plan_metrics(&plan.access);
252 let route_plan = Self::build_execution_route_plan_for_load(
254 &plan,
255 cursor_boundary.as_ref(),
256 index_range_anchor.as_ref(),
257 None,
258 direction,
259 )?;
260
261 let mut resolved = Self::resolve_execution_key_stream(
263 &execution_inputs,
264 &route_plan,
265 IndexPredicateCompileMode::ConservativeSubset,
266 )?;
267 let (mut page, keys_scanned, mut post_access_rows) =
268 Self::materialize_key_stream_into_page(
269 &ctx,
270 &plan,
271 predicate_slots.as_ref(),
272 resolved.key_stream.as_mut(),
273 route_plan.scan_hints.load_scan_budget_hint,
274 route_plan.streaming_access_shape_safe(),
275 cursor_boundary.as_ref(),
276 direction,
277 continuation_signature,
278 )?;
279 let mut rows_scanned = resolved.rows_scanned_override.unwrap_or(keys_scanned);
280 let mut optimization = resolved.optimization;
281 let mut index_predicate_applied = resolved.index_predicate_applied;
282 let mut index_predicate_keys_rejected = resolved.index_predicate_keys_rejected;
283 let mut distinct_keys_deduped = resolved
284 .distinct_keys_deduped_counter
285 .as_ref()
286 .map_or(0, |counter| counter.get());
287
288 if Self::index_range_limited_residual_retry_required(
289 &plan,
290 cursor_boundary.as_ref(),
291 &route_plan,
292 rows_scanned,
293 post_access_rows,
294 ) {
295 let mut fallback_route_plan = route_plan;
296 fallback_route_plan.index_range_limit_spec = None;
297 let mut fallback_resolved = Self::resolve_execution_key_stream(
298 &execution_inputs,
299 &fallback_route_plan,
300 IndexPredicateCompileMode::ConservativeSubset,
301 )?;
302 let (fallback_page, fallback_keys_scanned, fallback_post_access_rows) =
303 Self::materialize_key_stream_into_page(
304 &ctx,
305 &plan,
306 predicate_slots.as_ref(),
307 fallback_resolved.key_stream.as_mut(),
308 fallback_route_plan.scan_hints.load_scan_budget_hint,
309 fallback_route_plan.streaming_access_shape_safe(),
310 cursor_boundary.as_ref(),
311 direction,
312 continuation_signature,
313 )?;
314 let fallback_rows_scanned = fallback_resolved
315 .rows_scanned_override
316 .unwrap_or(fallback_keys_scanned);
317 let fallback_distinct_keys_deduped = fallback_resolved
318 .distinct_keys_deduped_counter
319 .as_ref()
320 .map_or(0, |counter| counter.get());
321
322 rows_scanned = rows_scanned.saturating_add(fallback_rows_scanned);
324 optimization = fallback_resolved.optimization;
325 index_predicate_applied =
326 index_predicate_applied || fallback_resolved.index_predicate_applied;
327 index_predicate_keys_rejected = index_predicate_keys_rejected
328 .saturating_add(fallback_resolved.index_predicate_keys_rejected);
329 distinct_keys_deduped =
330 distinct_keys_deduped.saturating_add(fallback_distinct_keys_deduped);
331 page = fallback_page;
332 post_access_rows = fallback_post_access_rows;
333 }
334
335 Ok(Self::finalize_execution(
336 page,
337 optimization,
338 rows_scanned,
339 post_access_rows,
340 index_predicate_applied,
341 index_predicate_keys_rejected,
342 distinct_keys_deduped,
343 &mut span,
344 &mut execution_trace,
345 ))
346 })();
347
348 result.map(|page| (page, execution_trace))
349 }
350
351 fn index_range_limited_residual_retry_required(
354 plan: &LogicalPlan<E::Key>,
355 cursor_boundary: Option<&CursorBoundary>,
356 route_plan: &ExecutionRoutePlan,
357 rows_scanned: usize,
358 post_access_rows: usize,
359 ) -> bool {
360 let Some(limit_spec) = route_plan.index_range_limit_spec else {
361 return false;
362 };
363 if plan.predicate.is_none() {
364 return false;
365 }
366 if limit_spec.fetch == 0 {
367 return false;
368 }
369 let Some(limit) = plan.page.as_ref().and_then(|page| page.limit) else {
370 return false;
371 };
372 let keep_count =
373 compute_page_window(plan.effective_page_offset(cursor_boundary), limit, false)
374 .keep_count;
375 if keep_count == 0 {
376 return false;
377 }
378 if rows_scanned < limit_spec.fetch {
379 return false;
380 }
381
382 post_access_rows < keep_count
383 }
384
385 fn finalize_path_outcome(
387 execution_trace: &mut Option<ExecutionTrace>,
388 optimization: Option<ExecutionOptimization>,
389 rows_scanned: usize,
390 rows_returned: usize,
391 index_predicate_applied: bool,
392 index_predicate_keys_rejected: u64,
393 distinct_keys_deduped: u64,
394 ) {
395 record_rows_scanned::<E>(rows_scanned);
396 if let Some(execution_trace) = execution_trace.as_mut() {
397 execution_trace.set_path_outcome(
398 optimization,
399 rows_scanned,
400 rows_returned,
401 index_predicate_applied,
402 index_predicate_keys_rejected,
403 distinct_keys_deduped,
404 );
405 debug_assert_eq!(
406 execution_trace.keys_scanned,
407 u64::try_from(rows_scanned).unwrap_or(u64::MAX),
408 "execution trace keys_scanned must match rows_scanned metrics input",
409 );
410 }
411 }
412
413 pub(in crate::db::executor) fn validate_pk_fast_path_boundary_if_applicable(
415 plan: &LogicalPlan<E::Key>,
416 cursor_boundary: Option<&CursorBoundary>,
417 ) -> Result<(), InternalError> {
418 if !Self::pk_order_stream_fast_path_shape_supported(plan) {
419 return Ok(());
420 }
421 let _ = decode_pk_cursor_boundary::<E>(cursor_boundary)?;
422
423 Ok(())
424 }
425}