1use std::future;
15use std::sync::Arc;
16use std::task::Poll;
17
18use async_lock::Semaphore;
19use async_lock::SemaphoreGuardArc;
20use futures::SinkExt;
21use futures::StreamExt;
22use futures::TryStreamExt;
23use futures::channel::mpsc;
24use futures::future::Either;
25use futures::stream;
26use futures::stream::BoxStream;
27use vortex_array::ArrayRef;
28use vortex_error::VortexResult;
29use vortex_error::vortex_err;
30use vortex_io::request::IoService;
31use vortex_io::runtime::Handle;
32use vortex_mask::Mask;
33
34use crate::planning::driver::Progress;
35use crate::planning::driver::Run;
36use crate::planning::planner::Planner;
37use crate::planning::planner::WorkScope;
38use crate::prepare::ChunkPlanner;
39use crate::prepare::PreparedScan;
40use crate::prepare::PrunePlanner;
41use crate::prepare::ScanBuilder;
42
43pub struct ScanDriver {
45 handle: Handle,
46 concurrency: usize,
47 budget: Option<ChunkBudget>,
48 ordered: bool,
49}
50
51#[derive(Clone)]
54pub struct ChunkBudget {
55 chunks: usize,
56 slots: Arc<Semaphore>,
57}
58
59impl ChunkBudget {
60 pub fn new(chunks: usize) -> Self {
62 Self {
63 chunks,
64 slots: Arc::new(Semaphore::new(chunks)),
65 }
66 }
67}
68
69impl ScanDriver {
70 pub fn new(handle: Handle, concurrency: usize, ordered: bool) -> Self {
75 Self {
76 handle,
77 concurrency,
78 budget: None,
79 ordered,
80 }
81 }
82
83 pub fn with_budget(handle: Handle, budget: ChunkBudget, ordered: bool) -> Self {
87 Self {
88 handle,
89 concurrency: budget.chunks + 1,
90 budget: Some(budget),
91 ordered,
92 }
93 }
94
95 pub fn run(
98 self,
99 builder: impl Into<ScanBuilder>,
100 ) -> BoxStream<'static, VortexResult<ArrayRef>> {
101 self.run_mapped(builder, Ok)
102 }
103
104 pub fn run_mapped<A: Send + 'static>(
110 self,
111 builder: impl Into<ScanBuilder>,
112 map_fn: impl Fn(ArrayRef) -> VortexResult<A> + Send + Sync + 'static,
113 ) -> BoxStream<'static, VortexResult<A>> {
114 let builder = builder.into();
115 let handle = self.handle.clone();
116 stream::once(async move {
117 handle
118 .spawn_cpu(move || {
119 let scan = builder.prepare()?;
120 VortexResult::Ok(self.run_prepared(scan, map_fn))
121 })
122 .await
123 })
124 .try_flatten()
125 .boxed()
126 }
127
128 pub fn run_prepared<A: Send + 'static>(
131 self,
132 scan: PreparedScan,
133 map_fn: impl Fn(ArrayRef) -> VortexResult<A> + Send + Sync + 'static,
134 ) -> BoxStream<'static, VortexResult<A>> {
135 let scan = Arc::new(scan);
136 let map_fn: MapFn<A> = Arc::new(map_fn);
137 let in_flight = self.concurrency;
138 let inline = in_flight == 0;
139 let scope = WorkScope {
140 file_ordinal: 0,
141 rows: scan.rows().clone(),
142 };
143 let io = scan.io();
144 let root = compose(&scan);
145 let (chunk_handle, chunk_io, chunk_map) =
146 (self.handle.clone(), Arc::clone(&io), Arc::clone(&map_fn));
147 let slots = self
148 .budget
149 .map(|budget| (Arc::new(Semaphore::new(1)), budget.slots));
150 let batches = run_stream(self.handle, root, scope, io, map_fn, inline)
151 .map_ok(move |yielded| match yielded {
152 Yielded::Batch(start, batch) => {
153 stream::once(future::ready(Ok((start, batch)))).boxed()
154 }
155 Yielded::Spawn(scope, chunk) => {
156 let (handle, io, map_fn) = (
157 chunk_handle.clone(),
158 Arc::clone(&chunk_io),
159 Arc::clone(&chunk_map),
160 );
161 let Some((own, shared)) = slots.clone() else {
162 return chunk_stream(&handle, chunk, scope, io, map_fn);
163 };
164 stream::once(async move {
165 let slot = acquire_slot(own, shared).await;
166 chunk_stream(&handle, chunk, scope, io, map_fn).map(move |batch| {
167 let _ = &slot;
168 batch
169 })
170 })
171 .flatten()
172 .boxed()
173 }
174 })
175 .try_flatten_unordered(in_flight);
176 let batches = batches.chain(stream::poll_fn(move |_| {
179 let _ = &scan;
180 Poll::Ready(None)
181 }));
182 if !self.ordered {
183 return batches.map_ok(|(_, batch)| batch).boxed();
184 }
185 stream::once(async move {
186 let mut held: Vec<(u64, A)> = batches.try_collect().await?;
187 held.sort_by_key(|(start, _)| *start);
189 VortexResult::Ok(stream::iter(held.into_iter().map(|(_, batch)| Ok(batch))))
190 })
191 .try_flatten()
192 .boxed()
193 }
194}
195
196async fn acquire_slot(own: Arc<Semaphore>, shared: Arc<Semaphore>) -> SemaphoreGuardArc {
199 if let Some(slot) = own.try_acquire_arc().or_else(|| shared.try_acquire_arc()) {
200 return slot;
201 }
202 match futures::future::select(Box::pin(own.acquire_arc()), Box::pin(shared.acquire_arc())).await
203 {
204 Either::Left((slot, _)) | Either::Right((slot, _)) => slot,
205 }
206}
207
208fn compose(scan: &Arc<PreparedScan>) -> Box<dyn Planner> {
211 let rows = scan.rows().clone();
212 let chunks = {
213 let scan = Arc::clone(scan);
214 let rows = rows.clone();
215 move |kept: Option<Mask>| -> Box<dyn Planner> {
216 let selection = scan.selection().clone();
217 Box::new(ChunkPlanner::new(scan, rows, selection, kept))
218 }
219 };
220 if scan.filter().is_some() {
221 Box::new(PrunePlanner::new(Arc::clone(scan), rows, Box::new(chunks)))
222 } else {
223 chunks(None)
224 }
225}
226
227type MapFn<A> = Arc<dyn Fn(ArrayRef) -> VortexResult<A> + Send + Sync>;
229
230enum Yielded<A> {
233 Batch(u64, A),
234 Spawn(WorkScope, Box<dyn Planner>),
235}
236
237enum Step<A> {
239 Batch(u64, A),
240 Spawn(WorkScope, Box<dyn Planner>),
241 RootDone,
242 Idle,
243 Waiting,
244}
245
246struct RunState<A> {
248 handle: Handle,
249 run: Option<Run>,
251 io: Arc<dyn IoService>,
253 map_fn: MapFn<A>,
254 inline: bool,
256}
257
258fn run_stream<A: Send + 'static>(
262 handle: Handle,
263 root: Box<dyn Planner>,
264 scope: WorkScope,
265 io: Arc<dyn IoService>,
266 map_fn: MapFn<A>,
267 inline: bool,
268) -> BoxStream<'static, VortexResult<Yielded<A>>> {
269 let mut run = Run::new();
270 run.admit(root, scope, io.session());
271 let state = RunState {
272 handle,
273 run: Some(run),
274 io,
275 map_fn,
276 inline,
277 };
278 stream::try_unfold(state, |mut state| async move {
279 loop {
280 let run = state
281 .run
282 .take()
283 .ok_or_else(|| vortex_err!("the scan's run is missing"))?;
284 let map_fn = Arc::clone(&state.map_fn);
285 let (run, step) = state
286 .handle
287 .spawn_cpu(move || {
288 let mut run = run;
289 let step = run.advance().and_then(|progress| {
290 Ok(match progress {
291 Progress::Batch(batch) => {
292 Step::Batch(batch.scope.rows.start, map_fn(batch.array)?)
293 }
294 Progress::Spawn(scope, child) => Step::Spawn(scope, child),
295 Progress::RootDone(_) => Step::RootDone,
296 Progress::Idle => Step::Idle,
297 Progress::Waiting => Step::Waiting,
298 })
299 });
300 (run, step)
301 })
302 .await;
303 let run = state.run.insert(run);
304 match step? {
305 Step::Batch(start, batch) => {
306 return Ok(Some((Yielded::Batch(start, batch), state)));
307 }
308 Step::Spawn(scope, child) if state.inline => {
309 run.admit(child, scope, state.io.session());
310 }
311 Step::Spawn(scope, child) => {
312 return Ok(Some((Yielded::Spawn(scope, child), state)));
313 }
314 Step::RootDone if run.live_roots() > 0 => {}
315 Step::RootDone | Step::Idle => return Ok(None),
316 Step::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?,
317 }
318 }
319 })
320 .boxed()
321}
322
323fn chunk_stream<A: Send + 'static>(
327 handle: &Handle,
328 root: Box<dyn Planner>,
329 scope: WorkScope,
330 io: Arc<dyn IoService>,
331 map_fn: MapFn<A>,
332) -> BoxStream<'static, VortexResult<(u64, A)>> {
333 let (mut send, recv) = mpsc::channel(1);
334 let task = handle.spawn(async move {
335 let mut run = Run::new();
336 run.admit(root, scope, io.session());
337 loop {
338 match run.advance()? {
339 Progress::Batch(batch) => {
340 let start = batch.scope.rows.start;
341 let batch = map_fn(batch.array);
342 let failed = batch.is_err();
343 if send.send(batch.map(|batch| (start, batch))).await.is_err() || failed {
344 return Ok(());
345 }
346 }
347 Progress::Spawn(scope, child) => {
348 run.admit(child, scope, io.session());
349 }
350 Progress::RootDone(_) if run.live_roots() > 0 => {}
351 Progress::RootDone(_) | Progress::Idle => return Ok(()),
352 Progress::Waiting => future::poll_fn(|cx| run.poll_completion(cx)).await?,
353 }
354 }
355 });
356 let errors = stream::once(task)
357 .filter_map(|result: VortexResult<()>| future::ready(result.err().map(Err)));
358 stream::select(recv, errors).boxed()
359}
360
361#[cfg(test)]
362mod tests;