|
1 | | -// Licensed to the Apache Software Foundation (ASF) under one |
2 | | -// or more contributor license agreements. See the NOTICE file |
3 | | -// distributed with this work for additional information |
4 | | -// regarding copyright ownership. The ASF licenses this file |
5 | | -// to you under the Apache License, Version 2.0 (the |
6 | | -// "License"); you may not use this file except in compliance |
7 | | -// with the License. You may obtain a copy of the License at |
8 | | -// |
9 | | -// http://www.apache.org/licenses/LICENSE-2.0 |
10 | | -// |
11 | | -// Unless required by applicable law or agreed to in writing, |
12 | | -// software distributed under the License is distributed on an |
13 | | -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | -// KIND, either express or implied. See the License for the |
15 | | -// specific language governing permissions and limitations |
16 | | -// under the License. |
17 | | - |
18 | | -/// Print Peak RSS, Peak Commit, Page Faults based on mimalloc api |
19 | | -pub fn print_memory_stats() { |
20 | | - // removed as not used in this project. |
| 1 | +use dashmap::{DashMap, Entry}; |
| 2 | +use datafusion::arrow::record_batch::RecordBatch; |
| 3 | +use datafusion::common::tree_node::{Transformed, TreeNode}; |
| 4 | +use datafusion::common::{exec_err, extensions_options, plan_err}; |
| 5 | +use datafusion::config::{ConfigExtension, ConfigOptions}; |
| 6 | +use datafusion::error::DataFusionError; |
| 7 | +use datafusion::execution::{FunctionRegistry, SendableRecordBatchStream, TaskContext}; |
| 8 | +use datafusion::physical_optimizer::PhysicalOptimizerRule; |
| 9 | +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; |
| 10 | +use datafusion::physical_plan::{ |
| 11 | + displayable, DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties, |
| 12 | +}; |
| 13 | +use datafusion_proto::physical_plan::PhysicalExtensionCodec; |
| 14 | +use futures::{FutureExt, StreamExt}; |
| 15 | +use prost::Message; |
| 16 | +use std::any::Any; |
| 17 | +use std::fmt::Formatter; |
| 18 | +use std::sync::{Arc, LazyLock}; |
| 19 | +use tokio::sync::OnceCell; |
| 20 | + |
| 21 | +type Key = (String, usize); |
| 22 | +type Value = Arc<OnceCell<Vec<RecordBatch>>>; |
| 23 | +static CACHE: LazyLock<DashMap<Key, Value>> = LazyLock::new(DashMap::default); |
| 24 | + |
| 25 | +/// Caches all the record batches in a global [CACHE] on the first run, and serves |
| 26 | +/// them from the cache in any subsequent run. |
| 27 | +#[derive(Debug, Clone)] |
| 28 | +pub struct InMemoryCacheExec { |
| 29 | + inner: Arc<dyn ExecutionPlan>, |
| 30 | +} |
| 31 | + |
| 32 | +extensions_options! { |
| 33 | + /// Marker used by the [InMemoryCacheExec] that determines wether its fine |
| 34 | + /// to load data from disk because we are warming up, or not. |
| 35 | + /// |
| 36 | + /// If this marker is not present during InMemoryCacheExec::execute(), and |
| 37 | + /// the data was not loaded in-memory already, the query will fail. |
| 38 | + pub struct WarmingUpMarker { |
| 39 | + is_warming_up: bool, default = false |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl ConfigExtension for WarmingUpMarker { |
| 44 | + const PREFIX: &'static str = "in-memory-cache-exec"; |
| 45 | +} |
| 46 | + |
| 47 | +impl WarmingUpMarker { |
| 48 | + pub fn warming_up() -> Self { |
| 49 | + Self { |
| 50 | + is_warming_up: true, |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl ExecutionPlan for InMemoryCacheExec { |
| 56 | + fn name(&self) -> &str { |
| 57 | + "InMemoryDataSourceExec" |
| 58 | + } |
| 59 | + |
| 60 | + fn as_any(&self) -> &dyn Any { |
| 61 | + self |
| 62 | + } |
| 63 | + |
| 64 | + fn properties(&self) -> &PlanProperties { |
| 65 | + self.inner.properties() |
| 66 | + } |
| 67 | + |
| 68 | + fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> { |
| 69 | + vec![&self.inner] |
| 70 | + } |
| 71 | + |
| 72 | + fn with_new_children( |
| 73 | + self: Arc<Self>, |
| 74 | + children: Vec<Arc<dyn ExecutionPlan>>, |
| 75 | + ) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> { |
| 76 | + Ok(Arc::new(Self { |
| 77 | + inner: children[0].clone(), |
| 78 | + })) |
| 79 | + } |
| 80 | + |
| 81 | + fn execute( |
| 82 | + &self, |
| 83 | + partition: usize, |
| 84 | + context: Arc<TaskContext>, |
| 85 | + ) -> datafusion::common::Result<SendableRecordBatchStream> { |
| 86 | + let once = { |
| 87 | + let inner_display = displayable(self.inner.as_ref()).one_line().to_string(); |
| 88 | + let entry = CACHE.entry((inner_display, partition)); |
| 89 | + if matches!(entry, Entry::Vacant(_)) |
| 90 | + && !context |
| 91 | + .session_config() |
| 92 | + .options() |
| 93 | + .extensions |
| 94 | + .get::<WarmingUpMarker>() |
| 95 | + .map(|v| v.is_warming_up) |
| 96 | + .unwrap_or_default() |
| 97 | + { |
| 98 | + return exec_err!("InMemoryCacheExec is not yet warmed up"); |
| 99 | + } |
| 100 | + let once = entry.or_insert(Arc::new(OnceCell::new())); |
| 101 | + once.value().clone() |
| 102 | + }; |
| 103 | + |
| 104 | + let inner = Arc::clone(&self.inner); |
| 105 | + |
| 106 | + let stream = async move { |
| 107 | + let batches = once |
| 108 | + .get_or_try_init(|| async move { |
| 109 | + let mut stream = inner.execute(partition, context)?; |
| 110 | + let mut batches = vec![]; |
| 111 | + while let Some(batch) = stream.next().await { |
| 112 | + batches.push(batch?); |
| 113 | + } |
| 114 | + Ok::<_, DataFusionError>(batches) |
| 115 | + }) |
| 116 | + .await?; |
| 117 | + Ok(batches.clone()) |
| 118 | + } |
| 119 | + .into_stream() |
| 120 | + .map(|v| match v { |
| 121 | + Ok(batch) => futures::stream::iter(batch.into_iter().map(Ok)).boxed(), |
| 122 | + Err(err) => futures::stream::once(async { Err(err) }).boxed(), |
| 123 | + }) |
| 124 | + .flatten(); |
| 125 | + |
| 126 | + Ok(Box::pin(RecordBatchStreamAdapter::new( |
| 127 | + self.inner.schema(), |
| 128 | + stream, |
| 129 | + ))) |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +impl DisplayAs for InMemoryCacheExec { |
| 134 | + fn fmt_as(&self, _t: DisplayFormatType, f: &mut Formatter) -> std::fmt::Result { |
| 135 | + writeln!(f, "InMemoryDataSourceExec") |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +#[derive(Clone, PartialEq, ::prost::Message)] |
| 140 | +struct InMemoryCacheExecProto { |
| 141 | + #[prost(string, tag = "1")] |
| 142 | + name: String, |
| 143 | +} |
| 144 | + |
| 145 | +#[derive(Debug)] |
| 146 | +pub struct InMemoryCacheExecCodec; |
| 147 | + |
| 148 | +impl PhysicalExtensionCodec for InMemoryCacheExecCodec { |
| 149 | + fn try_decode( |
| 150 | + &self, |
| 151 | + buf: &[u8], |
| 152 | + inputs: &[Arc<dyn ExecutionPlan>], |
| 153 | + _registry: &dyn FunctionRegistry, |
| 154 | + ) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> { |
| 155 | + let Ok(proto) = InMemoryCacheExecProto::decode(buf) else { |
| 156 | + return plan_err!("no InMemoryDataSourceExecProto"); |
| 157 | + }; |
| 158 | + if proto.name != "InMemoryDataSourceExec" { |
| 159 | + return plan_err!("unsupported InMemoryDataSourceExec proto: {:?}", proto.name); |
| 160 | + }; |
| 161 | + Ok(Arc::new(InMemoryCacheExec { |
| 162 | + inner: inputs[0].clone(), |
| 163 | + })) |
| 164 | + } |
| 165 | + |
| 166 | + fn try_encode( |
| 167 | + &self, |
| 168 | + node: Arc<dyn ExecutionPlan>, |
| 169 | + buf: &mut Vec<u8>, |
| 170 | + ) -> datafusion::common::Result<()> { |
| 171 | + if !node.as_any().is::<InMemoryCacheExec>() { |
| 172 | + return plan_err!("no InMemoryDataSourceExec"); |
| 173 | + }; |
| 174 | + let proto = InMemoryCacheExecProto { |
| 175 | + name: "InMemoryDataSourceExec".to_string(), |
| 176 | + }; |
| 177 | + let Ok(_) = proto.encode(buf) else { |
| 178 | + return plan_err!("no InMemoryDataSourceExecProto"); |
| 179 | + }; |
| 180 | + |
| 181 | + Ok(()) |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +/// Wraps any plan without children with an [InMemoryCacheExec] node. |
| 186 | +#[derive(Debug)] |
| 187 | +pub struct InMemoryDataSourceRule; |
| 188 | + |
| 189 | +impl PhysicalOptimizerRule for InMemoryDataSourceRule { |
| 190 | + fn optimize( |
| 191 | + &self, |
| 192 | + plan: Arc<dyn ExecutionPlan>, |
| 193 | + _config: &ConfigOptions, |
| 194 | + ) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> { |
| 195 | + Ok(plan |
| 196 | + .transform_up(|plan| { |
| 197 | + if plan.children().is_empty() { |
| 198 | + Ok(Transformed::yes(Arc::new(InMemoryCacheExec { |
| 199 | + inner: plan.clone(), |
| 200 | + }))) |
| 201 | + } else { |
| 202 | + Ok(Transformed::no(plan)) |
| 203 | + } |
| 204 | + })? |
| 205 | + .data) |
| 206 | + } |
| 207 | + |
| 208 | + fn name(&self) -> &str { |
| 209 | + "InMemoryDataSourceRule" |
| 210 | + } |
| 211 | + |
| 212 | + fn schema_check(&self) -> bool { |
| 213 | + true |
| 214 | + } |
21 | 215 | } |
0 commit comments