1use std::{
7 collections::HashMap,
8 fmt::{self, Formatter},
9 num::NonZero,
10 sync::{Arc, Mutex, OnceLock},
11 time::Duration,
12};
13
14use chrono::{DateTime, Utc};
15
16use arrow_array::RecordBatch;
17use arrow_schema::Schema as ArrowSchema;
18use datafusion::{
19 catalog::{TableProvider, streaming::StreamingTable},
20 dataframe::DataFrame,
21 execution::{
22 TaskContext,
23 context::{SessionConfig, SessionContext},
24 disk_manager::DiskManagerBuilder,
25 memory_pool::FairSpillPool,
26 runtime_env::RuntimeEnvBuilder,
27 },
28 physical_plan::{
29 DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
30 SendableRecordBatchStream,
31 analyze::AnalyzeExec,
32 coalesce_partitions::CoalescePartitionsExec,
33 display::DisplayableExecutionPlan,
34 execution_plan::{Boundedness, CardinalityEffect, EmissionType},
35 metrics::MetricValue,
36 sorts::sort_preserving_merge::SortPreservingMergeExec,
37 stream::RecordBatchStreamAdapter,
38 streaming::PartitionStream,
39 },
40};
41use datafusion::{execution::memory_pool::TrackConsumersPool, physical_plan::metrics::MetricType};
42use datafusion_common::{DataFusionError, Statistics};
43use datafusion_physical_expr::{EquivalenceProperties, Partitioning};
44
45use futures::{StreamExt, stream};
46use lance_arrow::SchemaExt;
47use lance_core::{
48 Error, Result,
49 utils::{
50 futures::FinallyStreamExt,
51 tracing::{EXECUTION_PLAN_RUN, StreamTracingExt, TRACE_EXECUTION},
52 },
53};
54use log::{debug, info, warn};
55use tracing::Span;
56
57use crate::udf::register_functions;
58use crate::{
59 chunker::StrictBatchSizeStream,
60 utils::{
61 BYTES_READ_METRIC, INDEX_CACHE_HITS_METRIC, INDEX_CACHE_MISSES_METRIC,
62 INDEX_COMPARISONS_METRIC, INDICES_LOADED_METRIC, IOPS_METRIC, MetricsExt,
63 PARTS_LOADED_METRIC, REQUESTS_METRIC,
64 },
65};
66
67pub struct OneShotExec {
75 stream: Mutex<Option<SendableRecordBatchStream>>,
76 schema: Arc<ArrowSchema>,
79 properties: Arc<PlanProperties>,
80}
81
82impl OneShotExec {
83 pub fn new(stream: SendableRecordBatchStream) -> Self {
85 let schema = stream.schema();
86 Self {
87 stream: Mutex::new(Some(stream)),
88 schema: schema.clone(),
89 properties: Arc::new(PlanProperties::new(
90 EquivalenceProperties::new(schema),
91 Partitioning::RoundRobinBatch(1),
92 EmissionType::Incremental,
93 Boundedness::Bounded,
94 )),
95 }
96 }
97
98 pub fn from_batch(batch: RecordBatch) -> Self {
99 let schema = batch.schema();
100 let stream = Box::pin(RecordBatchStreamAdapter::new(
101 schema,
102 stream::iter(vec![Ok(batch)]),
103 ));
104 Self::new(stream)
105 }
106}
107
108impl std::fmt::Debug for OneShotExec {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 let stream = self.stream.lock().unwrap();
111 f.debug_struct("OneShotExec")
112 .field("exhausted", &stream.is_none())
113 .field("schema", self.schema.as_ref())
114 .finish()
115 }
116}
117
118impl DisplayAs for OneShotExec {
119 fn fmt_as(
120 &self,
121 t: datafusion::physical_plan::DisplayFormatType,
122 f: &mut std::fmt::Formatter,
123 ) -> std::fmt::Result {
124 let stream = self.stream.lock().unwrap();
125 let exhausted = if stream.is_some() { "" } else { "EXHAUSTED" };
126 let columns = self
127 .schema
128 .field_names()
129 .iter()
130 .cloned()
131 .cloned()
132 .collect::<Vec<_>>();
133 match t {
134 DisplayFormatType::Default | DisplayFormatType::Verbose => {
135 write!(
136 f,
137 "OneShotStream: {}columns=[{}]",
138 exhausted,
139 columns.join(",")
140 )
141 }
142 DisplayFormatType::TreeRender => {
143 write!(
144 f,
145 "OneShotStream\nexhausted={}\ncolumns=[{}]",
146 exhausted,
147 columns.join(",")
148 )
149 }
150 }
151 }
152}
153
154impl ExecutionPlan for OneShotExec {
155 fn name(&self) -> &str {
156 "OneShotExec"
157 }
158
159 fn schema(&self) -> arrow_schema::SchemaRef {
160 self.schema.clone()
161 }
162
163 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
164 vec![]
165 }
166
167 fn with_new_children(
168 self: Arc<Self>,
169 children: Vec<Arc<dyn ExecutionPlan>>,
170 ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
171 if !children.is_empty() {
173 return Err(datafusion_common::DataFusionError::Internal(
174 "OneShotExec does not support children".to_string(),
175 ));
176 }
177 Ok(self)
178 }
179
180 fn execute(
181 &self,
182 _partition: usize,
183 _context: Arc<datafusion::execution::TaskContext>,
184 ) -> datafusion_common::Result<SendableRecordBatchStream> {
185 let stream = self
186 .stream
187 .lock()
188 .map_err(|err| DataFusionError::Execution(err.to_string()))?
189 .take();
190 if let Some(stream) = stream {
191 Ok(stream)
192 } else {
193 Err(DataFusionError::Execution(
194 "OneShotExec has already been executed".to_string(),
195 ))
196 }
197 }
198
199 fn properties(&self) -> &Arc<datafusion::physical_plan::PlanProperties> {
200 &self.properties
201 }
202}
203
204struct TracedExec {
205 input: Arc<dyn ExecutionPlan>,
206 properties: Arc<PlanProperties>,
207 span: Span,
208}
209
210impl TracedExec {
211 pub fn new(input: Arc<dyn ExecutionPlan>, span: Span) -> Self {
212 Self {
213 properties: input.properties().clone(),
214 input,
215 span,
216 }
217 }
218}
219
220impl DisplayAs for TracedExec {
221 fn fmt_as(
222 &self,
223 t: datafusion::physical_plan::DisplayFormatType,
224 f: &mut std::fmt::Formatter,
225 ) -> std::fmt::Result {
226 match t {
227 DisplayFormatType::Default
228 | DisplayFormatType::Verbose
229 | DisplayFormatType::TreeRender => {
230 write!(f, "TracedExec")
231 }
232 }
233 }
234}
235
236impl std::fmt::Debug for TracedExec {
237 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
238 write!(f, "TracedExec")
239 }
240}
241impl ExecutionPlan for TracedExec {
242 fn name(&self) -> &str {
243 "TracedExec"
244 }
245
246 fn properties(&self) -> &Arc<PlanProperties> {
247 &self.properties
248 }
249
250 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
251 vec![&self.input]
252 }
253
254 fn with_new_children(
255 self: Arc<Self>,
256 children: Vec<Arc<dyn ExecutionPlan>>,
257 ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
258 Ok(Arc::new(Self {
259 input: children[0].clone(),
260 properties: self.properties.clone(),
261 span: self.span.clone(),
262 }))
263 }
264
265 fn execute(
266 &self,
267 partition: usize,
268 context: Arc<TaskContext>,
269 ) -> datafusion_common::Result<SendableRecordBatchStream> {
270 let _guard = self.span.enter();
271 let stream = self.input.execute(partition, context)?;
272 let schema = stream.schema();
273 let stream = stream.stream_in_span(self.span.clone());
274 Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
275 }
276}
277
278pub type ExecutionStatsCallback = Arc<dyn Fn(&ExecutionSummaryCounts) + Send + Sync>;
280
281#[derive(Default, Clone)]
282pub struct LanceExecutionOptions {
283 pub use_spilling: bool,
284 pub mem_pool_size: Option<u64>,
285 pub max_temp_directory_size: Option<u64>,
286 pub batch_size: Option<usize>,
287 pub target_partition: Option<usize>,
288 pub execution_stats_callback: Option<ExecutionStatsCallback>,
289 pub skip_logging: bool,
290}
291
292impl std::fmt::Debug for LanceExecutionOptions {
293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
294 f.debug_struct("LanceExecutionOptions")
295 .field("use_spilling", &self.use_spilling)
296 .field("mem_pool_size", &self.mem_pool_size)
297 .field("max_temp_directory_size", &self.max_temp_directory_size)
298 .field("batch_size", &self.batch_size)
299 .field("target_partition", &self.target_partition)
300 .field("skip_logging", &self.skip_logging)
301 .field(
302 "execution_stats_callback",
303 &self.execution_stats_callback.is_some(),
304 )
305 .finish()
306 }
307}
308
309const DEFAULT_LANCE_MEM_POOL_SIZE_PER_PARTITION: u64 = 150 * 1024 * 1024;
310const DEFAULT_LANCE_MAX_TEMP_DIRECTORY_SIZE: u64 = 100 * 1024 * 1024 * 1024; impl LanceExecutionOptions {
313 pub fn mem_pool_size(&self) -> u64 {
314 let num_partitions = self.target_partition.unwrap_or(1) as u64;
315 self.mem_pool_size.unwrap_or_else(|| {
316 std::env::var("LANCE_MEM_POOL_SIZE")
317 .map(|s| match s.parse::<u64>() {
318 Ok(v) => v,
319 Err(e) => {
320 warn!("Failed to parse LANCE_MEM_POOL_SIZE: {}, using default", e);
321 DEFAULT_LANCE_MEM_POOL_SIZE_PER_PARTITION * num_partitions
322 }
323 })
324 .unwrap_or(DEFAULT_LANCE_MEM_POOL_SIZE_PER_PARTITION * num_partitions)
325 })
326 }
327
328 pub fn max_temp_directory_size(&self) -> u64 {
329 self.max_temp_directory_size.unwrap_or_else(|| {
330 std::env::var("LANCE_MAX_TEMP_DIRECTORY_SIZE")
331 .map(|s| match s.parse::<u64>() {
332 Ok(v) => v,
333 Err(e) => {
334 warn!(
335 "Failed to parse LANCE_MAX_TEMP_DIRECTORY_SIZE: {}, using default",
336 e
337 );
338 DEFAULT_LANCE_MAX_TEMP_DIRECTORY_SIZE
339 }
340 })
341 .unwrap_or(DEFAULT_LANCE_MAX_TEMP_DIRECTORY_SIZE)
342 })
343 }
344
345 pub fn use_spilling(&self) -> bool {
346 if !self.use_spilling {
347 return false;
348 }
349 std::env::var("LANCE_BYPASS_SPILLING")
350 .map(|_| {
351 info!("Bypassing spilling because LANCE_BYPASS_SPILLING is set");
352 false
353 })
354 .unwrap_or(true)
355 }
356}
357
358pub fn new_session_context(options: &LanceExecutionOptions) -> SessionContext {
359 let mut session_config = SessionConfig::new();
360 let mut runtime_env_builder = RuntimeEnvBuilder::new();
361 if let Some(target_partition) = options.target_partition {
362 session_config = session_config.with_target_partitions(target_partition);
363 }
364 if options.use_spilling() {
365 let sort_spill_reservation_bytes =
370 (options.mem_pool_size() / 3).min(40 * 1024 * 1024) as usize;
371 session_config =
372 session_config.with_sort_spill_reservation_bytes(sort_spill_reservation_bytes);
373 let disk_manager_builder = DiskManagerBuilder::default()
374 .with_max_temp_directory_size(options.max_temp_directory_size());
375 runtime_env_builder = runtime_env_builder
376 .with_disk_manager_builder(disk_manager_builder)
377 .with_memory_pool(Arc::new(TrackConsumersPool::new(
378 FairSpillPool::new(options.mem_pool_size() as usize),
379 NonZero::try_from(16).unwrap(),
380 )));
381 }
382 let runtime_env = runtime_env_builder.build_arc().unwrap();
383
384 let ctx = SessionContext::new_with_config_rt(session_config, runtime_env);
385 register_functions(&ctx);
386
387 ctx
388}
389
390#[derive(Clone, Debug, PartialEq, Eq, Hash)]
392struct SessionContextCacheKey {
393 mem_pool_size: u64,
394 max_temp_directory_size: u64,
395 target_partition: Option<usize>,
396 use_spilling: bool,
397}
398
399impl SessionContextCacheKey {
400 fn from_options(options: &LanceExecutionOptions) -> Self {
401 Self {
402 mem_pool_size: options.mem_pool_size(),
403 max_temp_directory_size: options.max_temp_directory_size(),
404 target_partition: options.target_partition,
405 use_spilling: options.use_spilling(),
406 }
407 }
408}
409
410struct CachedSessionContext {
411 context: SessionContext,
412 last_access: std::time::Instant,
413}
414
415fn get_session_cache() -> &'static Mutex<HashMap<SessionContextCacheKey, CachedSessionContext>> {
416 static SESSION_CACHE: OnceLock<Mutex<HashMap<SessionContextCacheKey, CachedSessionContext>>> =
417 OnceLock::new();
418 SESSION_CACHE.get_or_init(|| Mutex::new(HashMap::new()))
419}
420
421fn get_max_cache_size() -> usize {
422 const DEFAULT_CACHE_SIZE: usize = 4;
423 static MAX_CACHE_SIZE: OnceLock<usize> = OnceLock::new();
424 *MAX_CACHE_SIZE.get_or_init(|| {
425 std::env::var("LANCE_SESSION_CACHE_SIZE")
426 .ok()
427 .and_then(|v| v.parse().ok())
428 .unwrap_or(DEFAULT_CACHE_SIZE)
429 })
430}
431
432pub fn get_session_context(options: &LanceExecutionOptions) -> SessionContext {
433 let key = SessionContextCacheKey::from_options(options);
434 let mut cache = get_session_cache()
435 .lock()
436 .unwrap_or_else(|e| e.into_inner());
437
438 if let Some(entry) = cache.get_mut(&key) {
440 entry.last_access = std::time::Instant::now();
441 return entry.context.clone();
442 }
443
444 if cache.len() >= get_max_cache_size()
446 && let Some(lru_key) = cache
447 .iter()
448 .min_by_key(|(_, v)| v.last_access)
449 .map(|(k, _)| k.clone())
450 {
451 cache.remove(&lru_key);
452 }
453
454 let context = new_session_context(options);
455 cache.insert(
456 key,
457 CachedSessionContext {
458 context: context.clone(),
459 last_access: std::time::Instant::now(),
460 },
461 );
462 context
463}
464
465fn get_task_context(
466 session_ctx: &SessionContext,
467 options: &LanceExecutionOptions,
468) -> Arc<TaskContext> {
469 let mut state = session_ctx.state();
470 if let Some(batch_size) = options.batch_size.as_ref() {
471 state.config_mut().options_mut().execution.batch_size = *batch_size;
472 }
473
474 state.task_ctx()
475}
476
477#[derive(Default, Clone, Debug, PartialEq, Eq)]
478pub struct ExecutionSummaryCounts {
479 pub iops: usize,
481 pub requests: usize,
484 pub bytes_read: usize,
486 pub indices_loaded: usize,
488 pub parts_loaded: usize,
490 pub index_comparisons: usize,
492 pub all_counts: HashMap<String, usize>,
499 pub all_times: HashMap<String, usize>,
502}
503
504impl ExecutionSummaryCounts {
505 pub fn index_cache_hits(&self) -> usize {
533 self.all_counts
534 .get(INDEX_CACHE_HITS_METRIC)
535 .copied()
536 .unwrap_or(0)
537 }
538
539 pub fn index_cache_misses(&self) -> usize {
548 self.all_counts
549 .get(INDEX_CACHE_MISSES_METRIC)
550 .copied()
551 .unwrap_or(0)
552 }
553
554 pub fn index_cache_hit_ratio(&self) -> f32 {
564 let hits = self.index_cache_hits() as u128;
567 let total = hits + self.index_cache_misses() as u128;
568 if total == 0 {
569 0.0
570 } else {
571 hits as f32 / total as f32
572 }
573 }
574}
575
576pub fn collect_execution_metrics(node: &dyn ExecutionPlan, counts: &mut ExecutionSummaryCounts) {
577 if let Some(metrics) = node.metrics() {
578 for (metric_name, count) in metrics.iter_counts() {
579 match metric_name.as_ref() {
580 IOPS_METRIC => counts.iops += count.value(),
581 REQUESTS_METRIC => counts.requests += count.value(),
582 BYTES_READ_METRIC => counts.bytes_read += count.value(),
583 INDICES_LOADED_METRIC => counts.indices_loaded += count.value(),
584 PARTS_LOADED_METRIC => counts.parts_loaded += count.value(),
585 INDEX_COMPARISONS_METRIC => counts.index_comparisons += count.value(),
586 _ => {
587 let existing = counts
588 .all_counts
589 .entry(metric_name.as_ref().to_string())
590 .or_insert(0);
591 *existing += count.value();
592 }
593 }
594 }
595 for (metric_name, time) in metrics.iter_times() {
596 let existing = counts
597 .all_times
598 .entry(metric_name.as_ref().to_string())
599 .or_insert(0);
600 *existing += time.value();
601 }
602 for (metric_name, gauge) in metrics.iter_gauges() {
604 match metric_name.as_ref() {
605 IOPS_METRIC => counts.iops += gauge.value(),
606 REQUESTS_METRIC => counts.requests += gauge.value(),
607 BYTES_READ_METRIC => counts.bytes_read += gauge.value(),
608 _ => {}
609 }
610 }
611 }
612 for child in node.children() {
613 collect_execution_metrics(child.as_ref(), counts);
614 }
615}
616
617fn report_plan_summary_metrics(plan: &dyn ExecutionPlan, options: &LanceExecutionOptions) {
618 let output_rows = plan
619 .metrics()
620 .map(|m| m.output_rows().unwrap_or(0))
621 .unwrap_or(0);
622 let mut counts = ExecutionSummaryCounts::default();
623 collect_execution_metrics(plan, &mut counts);
624 if !options.skip_logging {
625 tracing::info!(
626 target: TRACE_EXECUTION,
627 r#type = EXECUTION_PLAN_RUN,
628 plan_summary = display_plan_one_liner(plan),
629 output_rows,
630 iops = counts.iops,
631 requests = counts.requests,
632 bytes_read = counts.bytes_read,
633 indices_loaded = counts.indices_loaded,
634 parts_loaded = counts.parts_loaded,
635 index_comparisons = counts.index_comparisons,
636 index_cache_hits = counts.index_cache_hits(),
637 index_cache_misses = counts.index_cache_misses(),
638 );
639 }
640 if let Some(callback) = options.execution_stats_callback.as_ref() {
641 callback(&counts);
642 }
643}
644
645fn display_plan_one_liner(plan: &dyn ExecutionPlan) -> String {
652 let mut output = String::new();
653
654 display_plan_one_liner_impl(plan, &mut output);
655
656 output
657}
658
659fn display_plan_one_liner_impl(plan: &dyn ExecutionPlan, output: &mut String) {
660 let name = plan.name().trim_end_matches("Exec");
662 output.push_str(name);
663
664 let children = plan.children();
665 if !children.is_empty() {
666 output.push('(');
667 for (i, child) in children.iter().enumerate() {
668 if i > 0 {
669 output.push(',');
670 }
671 display_plan_one_liner_impl(child.as_ref(), output);
672 }
673 output.push(')');
674 }
675}
676
677pub fn execute_plan(
681 plan: Arc<dyn ExecutionPlan>,
682 options: LanceExecutionOptions,
683) -> Result<SendableRecordBatchStream> {
684 if !options.skip_logging {
685 debug!(
686 "Executing plan:\n{}",
687 DisplayableExecutionPlan::new(plan.as_ref()).indent(true)
688 );
689 }
690
691 let session_ctx = get_session_context(&options);
692
693 let plan: Arc<dyn ExecutionPlan> = if plan.properties().partitioning.partition_count() == 1 {
704 plan
705 } else if let Some(ordering) = plan.output_ordering() {
706 Arc::new(SortPreservingMergeExec::new(ordering.clone(), plan))
707 } else {
708 Arc::new(CoalescePartitionsExec::new(plan))
709 };
710
711 let stream = plan.execute(0, get_task_context(&session_ctx, &options))?;
712
713 let schema = stream.schema();
714 let stream = stream.finally(move || {
715 if !options.skip_logging || options.execution_stats_callback.is_some() {
716 report_plan_summary_metrics(plan.as_ref(), &options);
717 }
718 });
719 Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
720}
721
722pub async fn analyze_plan(
723 plan: Arc<dyn ExecutionPlan>,
724 options: LanceExecutionOptions,
725) -> Result<String> {
726 let plan = Arc::new(TracedExec::new(plan, Span::current()));
729
730 let schema = plan.schema();
731 let analyze = Arc::new(AnalyzeExec::new(
733 true,
734 true,
735 vec![MetricType::Summary],
736 None,
737 plan,
738 schema,
739 ));
740
741 let session_ctx = get_session_context(&options);
742 assert_eq!(analyze.properties().partitioning.partition_count(), 1);
743 let mut stream = analyze
744 .execute(0, get_task_context(&session_ctx, &options))
745 .map_err(|err| Error::io(format!("Failed to execute analyze plan: {}", err)))?;
746
747 while (stream.next().await).is_some() {}
749
750 let result = format_plan(analyze);
751 Ok(result)
752}
753
754pub fn format_plan(plan: Arc<dyn ExecutionPlan>) -> String {
755 struct CalculateVisitor {
757 highest_index: usize,
758 index_to_elapsed: HashMap<usize, Duration>,
759 }
760
761 struct SubtreeMetrics {
763 min_start: Option<DateTime<Utc>>,
764 max_end: Option<DateTime<Utc>>,
765 }
766
767 impl CalculateVisitor {
768 fn calculate_metrics(&mut self, plan: &Arc<dyn ExecutionPlan>) -> SubtreeMetrics {
769 self.highest_index += 1;
770 let plan_index = self.highest_index;
771
772 let (mut min_start, mut max_end) = Self::node_timerange(plan);
774
775 for child in plan.children() {
777 let child_metrics = self.calculate_metrics(child);
778 min_start = Self::min_option(min_start, child_metrics.min_start);
779 max_end = Self::max_option(max_end, child_metrics.max_end);
780 }
781
782 let elapsed = match (min_start, max_end) {
784 (Some(start), Some(end)) => Some((end - start).to_std().unwrap_or_default()),
785 _ => None,
786 };
787
788 if let Some(e) = elapsed {
789 self.index_to_elapsed.insert(plan_index, e);
790 }
791
792 SubtreeMetrics { min_start, max_end }
793 }
794
795 fn node_timerange(
796 plan: &Arc<dyn ExecutionPlan>,
797 ) -> (Option<DateTime<Utc>>, Option<DateTime<Utc>>) {
798 let Some(metrics) = plan.metrics() else {
799 return (None, None);
800 };
801 let min_start = metrics
802 .iter()
803 .filter_map(|m| match m.value() {
804 MetricValue::StartTimestamp(ts) => ts.value(),
805 _ => None,
806 })
807 .min();
808 let max_end = metrics
809 .iter()
810 .filter_map(|m| match m.value() {
811 MetricValue::EndTimestamp(ts) => ts.value(),
812 _ => None,
813 })
814 .max();
815 (min_start, max_end)
816 }
817
818 fn min_option(a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>) -> Option<DateTime<Utc>> {
819 [a, b].into_iter().flatten().min()
820 }
821
822 fn max_option(a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>) -> Option<DateTime<Utc>> {
823 [a, b].into_iter().flatten().max()
824 }
825 }
826
827 struct PrintVisitor {
829 highest_index: usize,
830 indent: usize,
831 }
832 impl PrintVisitor {
833 fn write_output(
834 &mut self,
835 plan: &Arc<dyn ExecutionPlan>,
836 f: &mut Formatter,
837 calcs: &CalculateVisitor,
838 ) -> std::fmt::Result {
839 self.highest_index += 1;
840 write!(f, "{:indent$}", "", indent = self.indent * 2)?;
841
842 let displayable =
844 datafusion::physical_plan::display::DisplayableExecutionPlan::new(plan.as_ref());
845 let plan_str = displayable.one_line().to_string();
846 let plan_str = plan_str.trim();
847
848 match calcs.index_to_elapsed.get(&self.highest_index) {
850 Some(elapsed) => match plan_str.find(": ") {
851 Some(i) => write!(
852 f,
853 "{}: elapsed={elapsed:?}, {}",
854 &plan_str[..i],
855 &plan_str[i + 2..]
856 )?,
857 None => write!(f, "{plan_str}, elapsed={elapsed:?}")?,
858 },
859 None => write!(f, "{plan_str}")?,
860 }
861
862 if let Some(metrics) = plan.metrics() {
863 let metrics = metrics
864 .aggregate_by_name()
865 .sorted_for_display()
866 .timestamps_removed();
867
868 write!(f, ", metrics=[{metrics}]")?;
869 } else {
870 write!(f, ", metrics=[]")?;
871 }
872 writeln!(f)?;
873 self.indent += 1;
874 for child in plan.children() {
875 self.write_output(child, f, calcs)?;
876 }
877 self.indent -= 1;
878 std::fmt::Result::Ok(())
879 }
880 }
881 struct PrintWrapper {
883 plan: Arc<dyn ExecutionPlan>,
884 }
885 impl fmt::Display for PrintWrapper {
886 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
887 let mut calcs = CalculateVisitor {
888 highest_index: 0,
889 index_to_elapsed: HashMap::new(),
890 };
891 calcs.calculate_metrics(&self.plan);
892 let mut prints = PrintVisitor {
893 highest_index: 0,
894 indent: 0,
895 };
896 prints.write_output(&self.plan, f, &calcs)
897 }
898 }
899 let wrapper = PrintWrapper { plan };
900 format!("{}", wrapper)
901}
902
903pub trait SessionContextExt {
904 fn read_one_shot(
908 &self,
909 data: SendableRecordBatchStream,
910 ) -> datafusion::common::Result<DataFrame>;
911}
912
913pub struct OneShotPartitionStream {
914 data: Arc<Mutex<Option<SendableRecordBatchStream>>>,
915 schema: Arc<ArrowSchema>,
916}
917
918impl std::fmt::Debug for OneShotPartitionStream {
919 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
920 let data = self.data.lock().unwrap();
921 f.debug_struct("OneShotPartitionStream")
922 .field("exhausted", &data.is_none())
923 .field("schema", self.schema.as_ref())
924 .finish()
925 }
926}
927
928impl OneShotPartitionStream {
929 pub fn new(data: SendableRecordBatchStream) -> Self {
930 let schema = data.schema();
931 Self {
932 data: Arc::new(Mutex::new(Some(data))),
933 schema,
934 }
935 }
936}
937
938impl PartitionStream for OneShotPartitionStream {
939 fn schema(&self) -> &arrow_schema::SchemaRef {
940 &self.schema
941 }
942
943 fn execute(&self, _ctx: Arc<TaskContext>) -> SendableRecordBatchStream {
944 let mut stream = self.data.lock().unwrap();
945 stream
946 .take()
947 .expect("Attempt to consume a one shot dataframe multiple times")
948 }
949}
950
951impl SessionContextExt for SessionContext {
952 fn read_one_shot(
953 &self,
954 data: SendableRecordBatchStream,
955 ) -> datafusion::common::Result<DataFrame> {
956 let schema = data.schema();
957 let part_stream = Arc::new(OneShotPartitionStream::new(data));
958 let provider = StreamingTable::try_new(schema, vec![part_stream])?;
959 self.read_table(Arc::new(provider))
960 }
961}
962
963pub async fn provider_to_stream(
993 provider: Arc<dyn TableProvider>,
994) -> Result<SendableRecordBatchStream> {
995 let ctx = SessionContext::new();
996 let plan = provider.scan(&ctx.state(), None, &[], None).await?;
997 let plan: Arc<dyn ExecutionPlan> =
998 if plan.properties().output_partitioning().partition_count() > 1 {
999 Arc::new(CoalescePartitionsExec::new(plan))
1000 } else {
1001 plan
1002 };
1003 Ok(plan.execute(0, ctx.task_ctx())?)
1004}
1005
1006#[derive(Clone, Debug)]
1007pub struct StrictBatchSizeExec {
1008 input: Arc<dyn ExecutionPlan>,
1009 batch_size: usize,
1010}
1011
1012impl StrictBatchSizeExec {
1013 pub fn new(input: Arc<dyn ExecutionPlan>, batch_size: usize) -> Self {
1014 Self { input, batch_size }
1015 }
1016}
1017
1018impl DisplayAs for StrictBatchSizeExec {
1019 fn fmt_as(
1020 &self,
1021 _t: datafusion::physical_plan::DisplayFormatType,
1022 f: &mut std::fmt::Formatter,
1023 ) -> std::fmt::Result {
1024 write!(f, "StrictBatchSizeExec")
1025 }
1026}
1027
1028impl ExecutionPlan for StrictBatchSizeExec {
1029 fn name(&self) -> &str {
1030 "StrictBatchSizeExec"
1031 }
1032
1033 fn properties(&self) -> &Arc<PlanProperties> {
1034 self.input.properties()
1035 }
1036
1037 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1038 vec![&self.input]
1039 }
1040
1041 fn with_new_children(
1042 self: Arc<Self>,
1043 children: Vec<Arc<dyn ExecutionPlan>>,
1044 ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
1045 Ok(Arc::new(Self {
1046 input: children[0].clone(),
1047 batch_size: self.batch_size,
1048 }))
1049 }
1050
1051 fn execute(
1052 &self,
1053 partition: usize,
1054 context: Arc<TaskContext>,
1055 ) -> datafusion_common::Result<SendableRecordBatchStream> {
1056 let stream = self.input.execute(partition, context)?;
1057 let schema = stream.schema();
1058 let stream = StrictBatchSizeStream::new(stream, self.batch_size);
1059 Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
1060 }
1061
1062 fn maintains_input_order(&self) -> Vec<bool> {
1063 vec![true]
1064 }
1065
1066 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
1067 vec![false]
1068 }
1069
1070 fn partition_statistics(
1071 &self,
1072 partition: Option<usize>,
1073 ) -> datafusion_common::Result<std::sync::Arc<Statistics>> {
1074 self.input.partition_statistics(partition)
1075 }
1076
1077 fn cardinality_effect(&self) -> CardinalityEffect {
1078 CardinalityEffect::Equal
1079 }
1080
1081 fn supports_limit_pushdown(&self) -> bool {
1082 true
1083 }
1084}
1085
1086#[derive(Clone, Debug)]
1109pub struct HardCapBatchSizeExec {
1110 input: Arc<dyn ExecutionPlan>,
1111 max_bytes: usize,
1112}
1113
1114impl HardCapBatchSizeExec {
1115 pub fn new(input: Arc<dyn ExecutionPlan>, max_bytes: usize) -> Self {
1116 Self { input, max_bytes }
1117 }
1118}
1119
1120impl DisplayAs for HardCapBatchSizeExec {
1121 fn fmt_as(
1122 &self,
1123 _t: datafusion::physical_plan::DisplayFormatType,
1124 f: &mut std::fmt::Formatter,
1125 ) -> std::fmt::Result {
1126 write!(f, "HardCapBatchSizeExec(max_bytes={})", self.max_bytes)
1127 }
1128}
1129
1130impl ExecutionPlan for HardCapBatchSizeExec {
1131 fn name(&self) -> &str {
1132 "HardCapBatchSizeExec"
1133 }
1134
1135 fn properties(&self) -> &Arc<PlanProperties> {
1136 self.input.properties()
1137 }
1138
1139 fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
1140 vec![&self.input]
1141 }
1142
1143 fn with_new_children(
1144 self: Arc<Self>,
1145 children: Vec<Arc<dyn ExecutionPlan>>,
1146 ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
1147 Ok(Arc::new(Self {
1148 input: children[0].clone(),
1149 max_bytes: self.max_bytes,
1150 }))
1151 }
1152
1153 fn execute(
1154 &self,
1155 partition: usize,
1156 context: Arc<TaskContext>,
1157 ) -> datafusion_common::Result<SendableRecordBatchStream> {
1158 let stream = self.input.execute(partition, context)?;
1159 let schema = stream.schema();
1160 let max_bytes = self.max_bytes;
1161 let rechunked = lance_arrow::stream::rechunk_stream_by_size_deep_copy(
1162 stream,
1163 schema.clone(),
1164 0,
1165 max_bytes,
1166 );
1167 let validated = rechunked.map(move |result| {
1169 let batch = result?;
1170 if batch.num_rows() == 1 && batch.get_array_memory_size() > max_bytes {
1171 return Err(DataFusionError::External(Box::new(Error::invalid_input(
1172 format!(
1173 "a single row is {} bytes which exceeds the maximum allowed batch \
1174 size of {} bytes",
1175 batch.get_array_memory_size(),
1176 max_bytes,
1177 ),
1178 ))));
1179 }
1180 Ok(batch)
1181 });
1182 Ok(Box::pin(RecordBatchStreamAdapter::new(schema, validated)))
1183 }
1184
1185 fn maintains_input_order(&self) -> Vec<bool> {
1186 vec![true]
1187 }
1188
1189 fn benefits_from_input_partitioning(&self) -> Vec<bool> {
1190 vec![false]
1191 }
1192
1193 fn partition_statistics(
1194 &self,
1195 partition: Option<usize>,
1196 ) -> datafusion_common::Result<std::sync::Arc<Statistics>> {
1197 self.input.partition_statistics(partition)
1198 }
1199
1200 fn cardinality_effect(&self) -> CardinalityEffect {
1201 CardinalityEffect::Equal
1202 }
1203
1204 fn supports_limit_pushdown(&self) -> bool {
1205 true
1206 }
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211 use super::*;
1212
1213 static CACHE_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1215
1216 #[test]
1217 fn test_session_context_cache() {
1218 let _lock = CACHE_TEST_LOCK.lock().unwrap();
1219 let cache = get_session_cache();
1220
1221 cache.lock().unwrap().clear();
1223
1224 let opts1 = LanceExecutionOptions::default();
1226 let _ctx1 = get_session_context(&opts1);
1227
1228 {
1229 let cache_guard = cache.lock().unwrap();
1230 assert_eq!(cache_guard.len(), 1);
1231 }
1232
1233 let _ctx1_again = get_session_context(&opts1);
1235 {
1236 let cache_guard = cache.lock().unwrap();
1237 assert_eq!(cache_guard.len(), 1);
1238 }
1239
1240 let opts2 = LanceExecutionOptions {
1242 use_spilling: true,
1243 ..Default::default()
1244 };
1245 let _ctx2 = get_session_context(&opts2);
1246 {
1247 let cache_guard = cache.lock().unwrap();
1248 assert_eq!(cache_guard.len(), 2);
1249 }
1250 }
1251
1252 #[test]
1253 fn test_session_context_cache_lru_eviction() {
1254 let _lock = CACHE_TEST_LOCK.lock().unwrap();
1255 let cache = get_session_cache();
1256
1257 cache.lock().unwrap().clear();
1259
1260 let configs: Vec<LanceExecutionOptions> = (0..4)
1262 .map(|i| LanceExecutionOptions {
1263 mem_pool_size: Some((i + 1) as u64 * 1024 * 1024),
1264 ..Default::default()
1265 })
1266 .collect();
1267
1268 for config in &configs {
1269 let _ctx = get_session_context(config);
1270 }
1271
1272 {
1273 let cache_guard = cache.lock().unwrap();
1274 assert_eq!(cache_guard.len(), 4);
1275 }
1276
1277 std::thread::sleep(std::time::Duration::from_millis(1));
1280 let _ctx = get_session_context(&configs[0]);
1281
1282 let opts5 = LanceExecutionOptions {
1284 mem_pool_size: Some(5 * 1024 * 1024),
1285 ..Default::default()
1286 };
1287 let _ctx5 = get_session_context(&opts5);
1288
1289 {
1290 let cache_guard = cache.lock().unwrap();
1291 assert_eq!(cache_guard.len(), 4);
1292
1293 let key0 = SessionContextCacheKey::from_options(&configs[0]);
1295 assert!(
1296 cache_guard.contains_key(&key0),
1297 "config[0] should still be cached after recent access"
1298 );
1299
1300 let key1 = SessionContextCacheKey::from_options(&configs[1]);
1302 assert!(
1303 !cache_guard.contains_key(&key1),
1304 "config[1] should have been evicted"
1305 );
1306
1307 let key5 = SessionContextCacheKey::from_options(&opts5);
1309 assert!(
1310 cache_guard.contains_key(&key5),
1311 "new config should be cached"
1312 );
1313 }
1314 }
1315
1316 #[test]
1317 fn test_mem_pool_size_scales_with_partitions() {
1318 let default_per_partition = DEFAULT_LANCE_MEM_POOL_SIZE_PER_PARTITION;
1319
1320 let opts = LanceExecutionOptions::default();
1322 assert_eq!(opts.mem_pool_size(), default_per_partition);
1323
1324 let opts = LanceExecutionOptions {
1326 target_partition: Some(4),
1327 ..Default::default()
1328 };
1329 assert_eq!(opts.mem_pool_size(), default_per_partition * 4);
1330
1331 let opts = LanceExecutionOptions {
1333 target_partition: Some(8),
1334 ..Default::default()
1335 };
1336 assert_eq!(opts.mem_pool_size(), default_per_partition * 8);
1337
1338 let opts = LanceExecutionOptions {
1340 mem_pool_size: Some(50 * 1024 * 1024),
1341 target_partition: Some(8),
1342 ..Default::default()
1343 };
1344 assert_eq!(opts.mem_pool_size(), 50 * 1024 * 1024);
1345 }
1346}