1use std::future::Future;
16
17use futures::future::{Either, pending, select};
18use futures::pin_mut;
19use futures::stream::FuturesOrdered;
20use multimap::MultiMap;
21use risingwave_common::metrics::RelabeledAggregatedIntGauge;
22use risingwave_common::row::RowExt;
23use risingwave_common::types::ToOwnedDatum;
24use risingwave_common::util::iter_util::ZipEqFast;
25use risingwave_expr::expr::NonStrictExpression;
26
27use super::inflight_rows::InflightRows;
28use crate::executor::prelude::*;
29
30type ProjectMessageFuture = impl Future<Output = StreamExecutorResult<ProjectedMessage>> + Send;
31type PendingProjectMessages = FuturesOrdered<ProjectMessageFuture>;
32
33enum ProjectMessageInput {
34 Chunk {
35 chunk: StreamChunk,
36 inflight_rows: Option<Arc<InflightRows>>,
37 },
38 Watermark {
39 watermark: Watermark,
40 out_col_indices: Vec<usize>,
41 },
42 Barrier(Barrier),
43}
44
45enum ProjectedMessage {
46 Chunk(StreamChunk),
47 Watermark(Vec<Watermark>),
48 Barrier(Barrier),
49}
50
51pub struct ProjectExecutor {
55 input: Executor,
56 inner: Inner,
57}
58
59struct Inner {
60 actor_id: ActorId,
61
62 exprs: Arc<Vec<NonStrictExpression>>,
64 watermark_derivations: MultiMap<usize, usize>,
67 nondecreasing_expr_indices: Vec<usize>,
69 last_nondec_expr_values: Vec<Option<ScalarImpl>>,
71
72 eliminate_noop_updates: bool,
75
76 project_expr_concurrency: usize,
78
79 project_expr_inflight_request_concurrency: Option<Arc<InflightRows>>,
82
83 project_expr_inflight_window_size: Option<RelabeledAggregatedIntGauge>,
85}
86
87impl ProjectExecutor {
88 pub fn new(
89 ctx: ActorContextRef,
90 input: Executor,
91 exprs: Vec<NonStrictExpression>,
92 watermark_derivations: MultiMap<usize, usize>,
93 nondecreasing_expr_indices: Vec<usize>,
94 noop_update_hint: bool,
95 ) -> Self {
96 let n_nondecreasing_exprs = nondecreasing_expr_indices.len();
97 let eliminate_noop_updates =
98 noop_update_hint || ctx.config.developer.aggressive_noop_update_elimination;
99 let is_async = exprs
100 .iter()
101 .any(|expr| matches!(expr, NonStrictExpression::Async(_)));
102 let project_expr_concurrency =
104 match (is_async, ctx.config.developer.project_expr_concurrency) {
105 (false, _) => 1,
106 (true, 0) => usize::MAX,
107 (true, concurrency) => concurrency,
108 };
109 let project_expr_inflight_request_concurrency = match ctx
110 .config
111 .developer
112 .project_expr_inflight_request_concurrency
113 {
114 0 => None,
115 concurrency if is_async => Some(Arc::new(InflightRows::new(concurrency))),
116 _ => None,
117 };
118 let project_expr_inflight_window_size = (is_async
119 && ctx.config.developer.project_expr_concurrency
120 != risingwave_common::config::default::developer::stream_project_expr_concurrency(
121 ))
122 .then(|| {
123 ctx.streaming_metrics
124 .project_expr_inflight_window_size
125 .with_guarded_label_values(&[&ctx.id.to_string(), &ctx.fragment_id.to_string()])
126 });
127 Self {
128 input,
129 inner: Inner {
130 actor_id: ctx.id,
131 exprs: Arc::new(exprs),
132 watermark_derivations,
133 nondecreasing_expr_indices,
134 last_nondec_expr_values: vec![None; n_nondecreasing_exprs],
135 eliminate_noop_updates,
136 project_expr_concurrency,
137 project_expr_inflight_request_concurrency,
138 project_expr_inflight_window_size,
139 },
140 }
141 }
142}
143
144impl Debug for ProjectExecutor {
145 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
146 f.debug_struct("ProjectExecutor")
147 .field("exprs", &self.inner.exprs)
148 .finish()
149 }
150}
151
152impl Execute for ProjectExecutor {
153 fn execute(self: Box<Self>) -> BoxedMessageStream {
154 self.inner.execute(self.input).boxed()
155 }
156}
157
158pub async fn apply_project_exprs(
159 exprs: &[NonStrictExpression],
160 chunk: StreamChunk,
161) -> StreamExecutorResult<StreamChunk> {
162 let (data_chunk, ops) = chunk.into_parts();
163 let mut projected_columns = Vec::new();
164
165 for expr in exprs {
166 let evaluated_expr = expr.eval_infallible(&data_chunk).await;
167 projected_columns.push(evaluated_expr);
168 }
169 let (_, vis) = data_chunk.into_parts();
170
171 let new_chunk = StreamChunk::with_visibility(ops, projected_columns, vis);
172
173 Ok(new_chunk)
174}
175
176impl Inner {
177 #[define_opaque(ProjectMessageFuture)]
178 fn project_message(
179 exprs: Arc<Vec<NonStrictExpression>>,
180 eliminate_noop_updates: bool,
181 input: ProjectMessageInput,
182 ) -> ProjectMessageFuture {
183 async move {
184 match input {
185 ProjectMessageInput::Chunk {
186 chunk,
187 inflight_rows,
188 } => {
189 let _permit = if let Some(budget) = inflight_rows {
190 Some(budget.acquire(chunk.cardinality()).await)
191 } else {
192 None
193 };
194 let mut new_chunk = apply_project_exprs(&exprs, chunk)
195 .instrument_await("project_eval_chunk")
196 .await?;
197 if eliminate_noop_updates {
198 new_chunk = new_chunk.eliminate_adjacent_noop_update();
199 }
200 Ok(ProjectedMessage::Chunk(new_chunk))
201 }
202 ProjectMessageInput::Watermark {
203 watermark,
204 out_col_indices,
205 } => {
206 let mut ret = vec![];
207 for out_col_idx in out_col_indices {
208 let derived_watermark = watermark
209 .clone()
210 .transform_with_expr(&exprs[out_col_idx], out_col_idx)
211 .await;
212 if let Some(derived_watermark) = derived_watermark {
213 ret.push(derived_watermark);
214 } else {
215 warn!(
216 "a NULL watermark is derived with the expression {}!",
217 out_col_idx
218 );
219 }
220 }
221 Ok(ProjectedMessage::Watermark(ret))
222 }
223 ProjectMessageInput::Barrier(barrier) => Ok(ProjectedMessage::Barrier(barrier)),
224 }
225 }
226 }
227
228 fn update_last_nondec_expr_values(
229 nondecreasing_expr_indices: &[usize],
230 last_nondec_expr_values: &mut [Option<ScalarImpl>],
231 new_chunk: &StreamChunk,
232 ) {
233 {
234 {
235 {
236 {
237 if !nondecreasing_expr_indices.is_empty()
238 && let Some((_, first_visible_row)) = new_chunk.rows().next()
239 {
240 first_visible_row
242 .project(nondecreasing_expr_indices)
243 .iter()
244 .enumerate()
245 .for_each(|(idx, value)| {
246 last_nondec_expr_values[idx] =
247 Some(value.to_owned_datum().expect(
248 "non-decreasing expression should never be NULL",
249 ));
250 });
251 }
252 }
253 }
254 }
255 }
256 }
257
258 #[try_stream(ok = Message, error = StreamExecutorError)]
259 async fn execute(self, input: Executor) {
260 let Inner {
261 actor_id,
262 exprs,
263 watermark_derivations,
264 nondecreasing_expr_indices,
265 mut last_nondec_expr_values,
266 eliminate_noop_updates,
267 project_expr_concurrency,
268 project_expr_inflight_request_concurrency,
269 project_expr_inflight_window_size,
270 } = self;
271
272 let mut input = input.execute();
273 let first_barrier = expect_first_barrier(&mut input).await?;
274 let mut is_paused = first_barrier.is_pause_on_startup();
275 let mut received_stop_barrier = first_barrier.is_stop(actor_id);
276 yield Message::Barrier(first_barrier);
277 if received_stop_barrier {
278 return Ok(());
279 }
280
281 let mut pending_project_messages = PendingProjectMessages::new();
282 let mut pending_project_chunks = 0;
283
284 loop {
285 let has_pending_project_message = !pending_project_messages.is_empty();
286 let can_read_input =
287 !received_stop_barrier && pending_project_chunks < project_expr_concurrency;
288 let next_projected_message = async {
289 if has_pending_project_message {
290 pending_project_messages
291 .next()
292 .await
293 .expect("pending project messages should not be empty")
294 } else {
295 pending().await
296 }
297 };
298 let next_input_msg = async {
299 if can_read_input {
300 input.next().await.ok_or_else(|| {
301 StreamExecutorError::channel_closed("upstream executor closed unexpectedly")
302 })?
303 } else {
304 pending().await
305 }
306 };
307
308 pin_mut!(next_projected_message);
309 pin_mut!(next_input_msg);
310
311 match select(next_projected_message, next_input_msg).await {
312 Either::Left((projected_message, _)) => match projected_message? {
313 ProjectedMessage::Chunk(new_chunk) => {
314 pending_project_chunks -= 1;
315 if let Some(metric) = &project_expr_inflight_window_size {
316 metric.set(pending_project_messages.len() as _);
317 }
318 Self::update_last_nondec_expr_values(
319 &nondecreasing_expr_indices,
320 &mut last_nondec_expr_values,
321 &new_chunk,
322 );
323 yield Message::Chunk(new_chunk);
324 }
325 ProjectedMessage::Watermark(watermarks) => {
326 if let Some(metric) = &project_expr_inflight_window_size {
327 metric.set(pending_project_messages.len() as _);
328 }
329 for watermark in watermarks {
330 yield Message::Watermark(watermark);
331 }
332 }
333 ProjectedMessage::Barrier(barrier) => {
334 if let Some(metric) = &project_expr_inflight_window_size {
335 metric.set(pending_project_messages.len() as _);
336 }
337 if !is_paused {
338 for (&expr_idx, value) in nondecreasing_expr_indices
339 .iter()
340 .zip_eq_fast(&mut last_nondec_expr_values)
341 {
342 if let Some(value) = std::mem::take(value) {
343 yield Message::Watermark(Watermark::new(
344 expr_idx,
345 exprs[expr_idx].return_type(),
346 value,
347 ))
348 }
349 }
350 }
351
352 if let Some(mutation) = barrier.mutation.as_deref() {
353 match mutation {
354 Mutation::Pause => {
355 is_paused = true;
356 }
357 Mutation::Resume => {
358 is_paused = false;
359 }
360 _ => (),
361 }
362 }
363
364 let should_stop = barrier.is_stop(actor_id);
365 yield Message::Barrier(barrier);
366 if should_stop {
367 break;
368 }
369 }
370 },
371 Either::Right((msg, _)) => match msg? {
372 Message::Watermark(w) => {
373 let out_col_indices = match watermark_derivations.get_vec(&w.col_idx) {
374 Some(v) => v,
375 None => continue,
376 };
377 pending_project_messages.push_back(Self::project_message(
378 exprs.clone(),
379 eliminate_noop_updates,
380 ProjectMessageInput::Watermark {
381 watermark: w,
382 out_col_indices: out_col_indices.clone(),
383 },
384 ));
385 if let Some(metric) = &project_expr_inflight_window_size {
386 metric.set(pending_project_messages.len() as _);
387 }
388 }
389 Message::Chunk(chunk) => {
390 pending_project_messages.push_back(Self::project_message(
391 exprs.clone(),
392 eliminate_noop_updates,
393 ProjectMessageInput::Chunk {
394 chunk,
395 inflight_rows: project_expr_inflight_request_concurrency.clone(),
396 },
397 ));
398 pending_project_chunks += 1;
399 if let Some(metric) = &project_expr_inflight_window_size {
400 metric.set(pending_project_messages.len() as _);
401 }
402 }
403 Message::Barrier(barrier) => {
404 if barrier.is_stop(actor_id) {
405 received_stop_barrier = true;
406 }
407 pending_project_messages.push_back(Self::project_message(
408 exprs.clone(),
409 eliminate_noop_updates,
410 ProjectMessageInput::Barrier(barrier),
411 ));
412 if let Some(metric) = &project_expr_inflight_window_size {
413 metric.set(pending_project_messages.len() as _);
414 }
415 }
416 },
417 }
418 }
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use std::sync::atomic::{self, AtomicBool, AtomicI64, AtomicUsize};
425 use std::time::Duration;
426
427 use risingwave_common::array::DataChunk;
428 use risingwave_common::array::stream_chunk::StreamChunkTestExt;
429 use risingwave_common::catalog::Field;
430 use risingwave_common::config::StreamingConfig;
431 use risingwave_common::types::DefaultOrd;
432 use risingwave_common::util::epoch::test_epoch;
433 use risingwave_expr::expr::{
434 self, AsyncExpression, AsyncExpressionBoxExt, ExpressionInfo, SyncExpression, ValueImpl,
435 };
436 use tokio::sync::Notify;
437 use tokio::time::timeout;
438
439 use super::*;
440 use crate::executor::StopMutation;
441 use crate::executor::test_utils::expr::build_from_pretty;
442 use crate::executor::test_utils::{MockSource, StreamExecutorTestExt};
443
444 fn actor_context_with_project_expr_concurrency(concurrency: usize) -> ActorContextRef {
445 actor_context_with_project_expr_limits(concurrency, 0)
446 }
447
448 fn actor_context_with_project_expr_limits(
449 concurrency: usize,
450 inflight_request_concurrency: usize,
451 ) -> ActorContextRef {
452 let mut config = StreamingConfig::default();
453 config.developer.project_expr_concurrency = concurrency;
454 config.developer.project_expr_inflight_request_concurrency = inflight_request_concurrency;
455 let mut ctx = ActorContext::for_test(123);
456 Arc::get_mut(&mut ctx)
457 .expect("test actor context should not be shared")
458 .config = Arc::new(config);
459 ctx
460 }
461
462 #[test]
463 fn test_synchronous_projection_ignores_async_configuration() {
464 for concurrency in [0, 1, 8] {
465 for rows in [0, 2] {
466 let (_, source) = MockSource::channel();
467 let source = source
468 .into_executor(Schema::new(vec![Field::unnamed(DataType::Int64)]), vec![0]);
469 let project = ProjectExecutor::new(
470 actor_context_with_project_expr_limits(concurrency, rows),
471 source,
472 vec![build_from_pretty("(add:int8 $0:int8 1:int8)")],
473 MultiMap::new(),
474 vec![],
475 false,
476 );
477 assert_eq!(project.inner.project_expr_concurrency, 1);
478 assert!(
479 project
480 .inner
481 .project_expr_inflight_request_concurrency
482 .is_none()
483 );
484 assert!(project.inner.project_expr_inflight_window_size.is_none());
485 }
486 }
487 }
488
489 #[derive(Debug)]
490 struct GatedProjectExpr {
491 started_rows: Arc<std::sync::Mutex<Vec<usize>>>,
492 gates: Vec<Arc<tokio::sync::Semaphore>>,
493 fail: bool,
494 }
495
496 impl ExpressionInfo for GatedProjectExpr {
497 fn return_type(&self) -> DataType {
498 DataType::Int64
499 }
500 }
501
502 impl AsyncExpression for GatedProjectExpr {
503 async fn eval_v2(&self, input: &DataChunk) -> expr::Result<ValueImpl> {
504 let idx = {
505 let mut rows = self.started_rows.lock().unwrap();
506 let idx = rows.len();
507 rows.push(input.cardinality());
508 idx
509 };
510 let _permit = self.gates[idx].acquire().await.unwrap();
511 if self.fail {
512 return Err(risingwave_expr::ExprError::Custom("test failure".into()));
513 }
514 Ok(ValueImpl::Scalar {
515 value: Some((idx as i64).into()),
516 capacity: input.capacity(),
517 })
518 }
519
520 async fn eval_row(&self, _: &OwnedRow) -> expr::Result<Datum> {
521 unimplemented!()
522 }
523 }
524
525 #[tokio::test]
526 async fn test_projection_charges_visible_rows_and_releases_before_ordered_output() {
527 let rows = Arc::new(std::sync::Mutex::new(vec![]));
528 let gates: Vec<_> = (0..4)
529 .map(|_| Arc::new(tokio::sync::Semaphore::new(0)))
530 .collect();
531 let exprs = Arc::new(vec![NonStrictExpression::for_test(
532 GatedProjectExpr {
533 started_rows: rows.clone(),
534 gates: gates.clone(),
535 fail: false,
536 }
537 .boxed(),
538 )]);
539 let budget = Arc::new(InflightRows::new(5));
540 let mut pending = PendingProjectMessages::new();
541 let chunks = [
543 StreamChunk::from_pretty("I\n+ 1\n+ 1\n+ 1\n+ 1 D\n+ 1 D\n+ 1 D\n+ 1 D"),
544 StreamChunk::from_pretty("I\n+ 2\n+ 2\n+ 2\n+ 2"),
545 StreamChunk::from_pretty("I\n+ 3\n+ 3\n+ 3\n+ 3\n+ 3\n+ 3\n+ 3\n+ 3"),
546 StreamChunk::from_pretty("I\n+ 4"),
547 ];
548 for chunk in &chunks {
549 pending.push_back(Inner::project_message(
550 exprs.clone(),
551 false,
552 ProjectMessageInput::Chunk {
553 chunk: chunk.clone(),
554 inflight_rows: Some(budget.clone()),
555 },
556 ));
557 }
558 assert!(futures::poll!(pending.next()).is_pending());
559 assert_eq!(*rows.lock().unwrap(), vec![3, 4]);
560 gates[1].add_permits(1);
563 assert!(futures::poll!(pending.next()).is_pending());
564 assert_eq!(*rows.lock().unwrap(), vec![3, 4, 8]);
565 gates[0].add_permits(1);
566 let ProjectedMessage::Chunk(first) = pending.next().await.unwrap().unwrap() else {
567 panic!()
568 };
569 assert_eq!(first.cardinality(), 3);
570 assert_eq!(first.visibility(), chunks[0].visibility());
571 assert!(matches!(
572 pending.next().await.unwrap().unwrap(),
573 ProjectedMessage::Chunk(_)
574 ));
575 assert!(futures::poll!(pending.next()).is_pending());
576 assert_eq!(*rows.lock().unwrap(), vec![3, 4, 8]);
577 gates[2].add_permits(1);
578 assert!(matches!(
579 pending.next().await.unwrap().unwrap(),
580 ProjectedMessage::Chunk(_)
581 ));
582 assert!(futures::poll!(pending.next()).is_pending());
583 assert_eq!(*rows.lock().unwrap(), vec![3, 4, 8, 1]);
584 drop(pending);
586 assert_eq!(budget.used_rows(), 0);
587 assert!(futures::FutureExt::now_or_never(budget.acquire(1)).is_some());
588 }
589
590 #[tokio::test]
591 async fn test_projection_expression_error_releases_rows() {
592 let budget = Arc::new(InflightRows::new(1));
593 let exprs = Arc::new(vec![NonStrictExpression::new_topmost(
594 GatedProjectExpr {
595 started_rows: Arc::default(),
596 gates: vec![Arc::new(tokio::sync::Semaphore::new(1))],
597 fail: true,
598 }
599 .boxed(),
600 expr::LogReport,
601 )]);
602 let projected = Inner::project_message(
603 exprs,
604 false,
605 ProjectMessageInput::Chunk {
606 chunk: StreamChunk::from_pretty("I\n+ 1\n+ 2"),
607 inflight_rows: Some(budget.clone()),
608 },
609 )
610 .await
611 .unwrap();
612 assert!(matches!(projected, ProjectedMessage::Chunk(_)));
613 assert_eq!(budget.used_rows(), 0);
614 assert!(futures::FutureExt::now_or_never(budget.acquire(1)).is_some());
615 }
616
617 #[tokio::test]
618 async fn test_projection() {
619 let chunk1 = StreamChunk::from_pretty(
620 " I I
621 + 1 4
622 + 2 5
623 + 3 6",
624 );
625 let chunk2 = StreamChunk::from_pretty(
626 " I I
627 + 7 8
628 - 3 6",
629 );
630 let schema = Schema {
631 fields: vec![
632 Field::unnamed(DataType::Int64),
633 Field::unnamed(DataType::Int64),
634 ],
635 };
636 let stream_key = vec![0];
637 let (mut tx, source) = MockSource::channel();
638 let source = source.into_executor(schema, stream_key);
639
640 let test_expr = build_from_pretty("(add:int8 $0:int8 $1:int8)");
641
642 let proj = ProjectExecutor::new(
643 ActorContext::for_test(123),
644 source,
645 vec![test_expr],
646 MultiMap::new(),
647 vec![],
648 false,
649 );
650 let mut proj = proj.boxed().execute();
651
652 tx.push_barrier(test_epoch(1), false);
653 let barrier = proj.next().await.unwrap().unwrap();
654 barrier.as_barrier().unwrap();
655
656 tx.push_chunk(chunk1);
657 tx.push_chunk(chunk2);
658
659 let msg = proj.next().await.unwrap().unwrap();
660 assert_eq!(
661 *msg.as_chunk().unwrap(),
662 StreamChunk::from_pretty(
663 " I
664 + 5
665 + 7
666 + 9"
667 )
668 );
669
670 let msg = proj.next().await.unwrap().unwrap();
671 assert_eq!(
672 *msg.as_chunk().unwrap(),
673 StreamChunk::from_pretty(
674 " I
675 + 15
676 - 9"
677 )
678 );
679
680 tx.push_barrier(test_epoch(2), true);
681 assert!(proj.next().await.unwrap().unwrap().is_stop());
682 }
683
684 #[tokio::test]
685 async fn test_projection_does_not_poll_after_stop_barrier() {
686 let schema = Schema {
687 fields: vec![Field::unnamed(DataType::Int64)],
688 };
689 let (mut tx, source) = MockSource::channel();
690 let source = source.into_executor(schema, StreamKey::new());
691
692 let test_expr = build_from_pretty("(add:int8 $0:int8 1:int8)");
693
694 let proj = ProjectExecutor::new(
695 ActorContext::for_test(123),
696 source,
697 vec![test_expr],
698 MultiMap::new(),
699 vec![],
700 false,
701 );
702 let mut proj = proj.boxed().execute();
703
704 tx.push_barrier(test_epoch(1), false);
705 proj.expect_barrier().await;
706
707 tx.send_barrier(
708 Barrier::new_test_barrier(test_epoch(2)).with_mutation(Mutation::Stop(StopMutation {
709 dropped_actors: std::iter::once(123.into()).collect(),
710 ..Default::default()
711 })),
712 );
713 tx.push_chunk(StreamChunk::from_pretty(
714 " I
715 + 1",
716 ));
717
718 assert!(proj.next().await.unwrap().unwrap().is_stop());
719 assert!(proj.next().await.is_none());
720 }
721
722 #[derive(Debug)]
723 struct BlockingProjectExpr {
724 started_count: Arc<AtomicUsize>,
725 second_started: Arc<AtomicBool>,
726 second_started_notify: Arc<Notify>,
727 release_first: Arc<AtomicBool>,
728 release_first_notify: Arc<Notify>,
729 }
730
731 impl ExpressionInfo for BlockingProjectExpr {
732 fn return_type(&self) -> DataType {
733 DataType::Int64
734 }
735 }
736
737 impl AsyncExpression for BlockingProjectExpr {
738 async fn eval_v2(&self, input: &DataChunk) -> expr::Result<ValueImpl> {
739 let call_idx = self.started_count.fetch_add(1, atomic::Ordering::SeqCst);
740 if call_idx == 0 {
741 loop {
742 let notified = self.second_started_notify.notified();
743 if self.second_started.load(atomic::Ordering::SeqCst) {
744 break;
745 }
746 notified.await;
747 }
748 loop {
749 let notified = self.release_first_notify.notified();
750 if self.release_first.load(atomic::Ordering::SeqCst) {
751 break;
752 }
753 notified.await;
754 }
755 } else if call_idx == 1 {
756 self.second_started.store(true, atomic::Ordering::SeqCst);
757 self.second_started_notify.notify_waiters();
758 }
759
760 Ok(ValueImpl::Scalar {
761 value: Some((call_idx as i64).into()),
762 capacity: input.capacity(),
763 })
764 }
765
766 async fn eval_row(&self, _input: &OwnedRow) -> expr::Result<Datum> {
767 unimplemented!()
768 }
769 }
770
771 #[derive(Debug)]
772 struct FirstProjectExprWaitsForStartedCount {
773 started_count: Arc<AtomicUsize>,
774 started_notify: Arc<Notify>,
775 unblock_first_at_started_count: usize,
776 }
777
778 impl ExpressionInfo for FirstProjectExprWaitsForStartedCount {
779 fn return_type(&self) -> DataType {
780 DataType::Int64
781 }
782 }
783
784 impl AsyncExpression for FirstProjectExprWaitsForStartedCount {
785 async fn eval_v2(&self, input: &DataChunk) -> expr::Result<ValueImpl> {
786 let call_idx = self.started_count.fetch_add(1, atomic::Ordering::SeqCst);
787 self.started_notify.notify_waiters();
788 if call_idx == 0 {
789 loop {
790 let notified = self.started_notify.notified();
791 if self.started_count.load(atomic::Ordering::SeqCst)
792 >= self.unblock_first_at_started_count
793 {
794 break;
795 }
796 notified.await;
797 }
798 }
799
800 Ok(ValueImpl::Scalar {
801 value: Some((call_idx as i64).into()),
802 capacity: input.capacity(),
803 })
804 }
805
806 async fn eval_row(&self, _input: &OwnedRow) -> expr::Result<Datum> {
807 Ok(Some(0_i64.into()))
808 }
809 }
810
811 #[tokio::test]
812 async fn test_projection_evaluates_chunks_concurrently_before_barrier() {
813 let schema = Schema {
814 fields: vec![Field::unnamed(DataType::Int64)],
815 };
816 let (mut tx, source) = MockSource::channel();
817 let source = source.into_executor(schema, StreamKey::new());
818
819 let started_count = Arc::new(AtomicUsize::new(0));
820 let second_started = Arc::new(AtomicBool::new(false));
821 let second_started_notify = Arc::new(Notify::new());
822 let release_first = Arc::new(AtomicBool::new(false));
823 let release_first_notify = Arc::new(Notify::new());
824
825 let test_expr = NonStrictExpression::for_test(
826 BlockingProjectExpr {
827 started_count,
828 second_started: second_started.clone(),
829 second_started_notify: second_started_notify.clone(),
830 release_first: release_first.clone(),
831 release_first_notify: release_first_notify.clone(),
832 }
833 .boxed(),
834 );
835
836 let proj = ProjectExecutor::new(
837 actor_context_with_project_expr_concurrency(2),
838 source,
839 vec![test_expr],
840 MultiMap::new(),
841 vec![],
842 false,
843 );
844 let mut proj = proj.boxed().execute();
845
846 tx.push_barrier(test_epoch(1), false);
847 proj.expect_barrier().await;
848
849 tx.push_chunk(StreamChunk::from_pretty(
850 " I
851 + 1",
852 ));
853 tx.push_chunk(StreamChunk::from_pretty(
854 " I
855 + 2",
856 ));
857 tx.push_barrier(test_epoch(2), true);
858
859 let next_msg = proj.next();
860 pin_mut!(next_msg);
861 timeout(Duration::from_secs(5), async {
862 loop {
863 let notified = second_started_notify.notified();
864 if second_started.load(atomic::Ordering::SeqCst) {
865 break;
866 }
867 tokio::select! {
868 _ = notified => {}
869 msg = &mut next_msg => {
870 panic!("project executor emitted before the second chunk started: {msg:?}");
871 }
872 }
873 }
874 })
875 .await
876 .expect("second chunk expression did not start");
877
878 release_first.store(true, atomic::Ordering::SeqCst);
879 release_first_notify.notify_waiters();
880
881 let msg = next_msg.await.unwrap().unwrap();
882 assert_eq!(
883 *msg.as_chunk().unwrap(),
884 StreamChunk::from_pretty(
885 " I
886 + 0"
887 )
888 );
889
890 let msg = proj.next().await.unwrap().unwrap();
891 assert_eq!(
892 *msg.as_chunk().unwrap(),
893 StreamChunk::from_pretty(
894 " I
895 + 1"
896 )
897 );
898
899 assert!(proj.next().await.unwrap().unwrap().is_stop());
900 }
901
902 #[tokio::test]
903 async fn test_projection_reuses_finished_inflight_permit_across_barrier() {
904 let schema = Schema {
905 fields: vec![Field::unnamed(DataType::Int64)],
906 };
907 let (mut tx, source) = MockSource::channel();
908 let source = source.into_executor(schema, StreamKey::new());
909
910 let started_count = Arc::new(AtomicUsize::new(0));
911 let started_notify = Arc::new(Notify::new());
912 let test_expr = NonStrictExpression::for_test(
913 FirstProjectExprWaitsForStartedCount {
914 started_count: started_count.clone(),
915 started_notify: started_notify.clone(),
916 unblock_first_at_started_count: 3,
917 }
918 .boxed(),
919 );
920
921 let proj = ProjectExecutor::new(
922 actor_context_with_project_expr_limits(3, 2),
923 source,
924 vec![test_expr],
925 MultiMap::new(),
926 vec![],
927 false,
928 );
929 let mut proj = proj.boxed().execute();
930
931 tx.push_barrier(test_epoch(1), false);
932 proj.expect_barrier().await;
933
934 tx.push_chunk(StreamChunk::from_pretty(
935 " I
936 + 1",
937 ));
938 tx.push_chunk(StreamChunk::from_pretty(
939 " I
940 + 2",
941 ));
942 tx.push_barrier(test_epoch(2), false);
943 tx.push_chunk(StreamChunk::from_pretty(
944 " I
945 + 3",
946 ));
947 tx.push_barrier(test_epoch(3), true);
948
949 let first_msg = timeout(Duration::from_secs(5), async {
950 let next_msg = proj.next();
951 pin_mut!(next_msg);
952 let mut first_msg = None;
953 loop {
954 let notified = started_notify.notified();
955 if started_count.load(atomic::Ordering::SeqCst) >= 3 {
956 break;
957 }
958 tokio::select! {
959 _ = notified => {}
960 msg = &mut next_msg => {
961 if started_count.load(atomic::Ordering::SeqCst) < 3 {
962 panic!("project executor emitted before the post-barrier chunk started: {msg:?}");
963 }
964 first_msg = Some(msg.unwrap().unwrap());
965 break;
966 }
967 }
968 }
969 match first_msg {
970 Some(msg) => msg,
971 None => next_msg.await.unwrap().unwrap(),
972 }
973 })
974 .await
975 .expect("post-barrier chunk expression did not start");
976
977 assert_eq!(
978 *first_msg.as_chunk().unwrap(),
979 StreamChunk::from_pretty(
980 " I
981 + 0"
982 )
983 );
984 assert_eq!(
985 *proj.next().await.unwrap().unwrap().as_chunk().unwrap(),
986 StreamChunk::from_pretty(
987 " I
988 + 1"
989 )
990 );
991 proj.expect_barrier().await;
992 assert_eq!(
993 *proj.next().await.unwrap().unwrap().as_chunk().unwrap(),
994 StreamChunk::from_pretty(
995 " I
996 + 2"
997 )
998 );
999 assert!(proj.next().await.unwrap().unwrap().is_stop());
1000 }
1001
1002 #[tokio::test]
1003 async fn test_projection_reuses_finished_inflight_permit_across_watermark() {
1004 let schema = Schema {
1005 fields: vec![Field::unnamed(DataType::Int64)],
1006 };
1007 let (mut tx, source) = MockSource::channel();
1008 let source = source.into_executor(schema, StreamKey::new());
1009
1010 let started_count = Arc::new(AtomicUsize::new(0));
1011 let started_notify = Arc::new(Notify::new());
1012 let test_expr = NonStrictExpression::for_test(
1013 FirstProjectExprWaitsForStartedCount {
1014 started_count: started_count.clone(),
1015 started_notify: started_notify.clone(),
1016 unblock_first_at_started_count: 3,
1017 }
1018 .boxed(),
1019 );
1020
1021 let proj = ProjectExecutor::new(
1022 actor_context_with_project_expr_limits(3, 2),
1023 source,
1024 vec![test_expr],
1025 MultiMap::from_iter(vec![(0, 0)].into_iter()),
1026 vec![],
1027 false,
1028 );
1029 let mut proj = proj.boxed().execute();
1030
1031 tx.push_barrier(test_epoch(1), false);
1032 proj.expect_barrier().await;
1033
1034 tx.push_chunk(StreamChunk::from_pretty(
1035 " I
1036 + 1",
1037 ));
1038 tx.push_chunk(StreamChunk::from_pretty(
1039 " I
1040 + 2",
1041 ));
1042 tx.push_int64_watermark(0, 100);
1043 tx.push_chunk(StreamChunk::from_pretty(
1044 " I
1045 + 3",
1046 ));
1047 tx.push_barrier(test_epoch(2), true);
1048
1049 let first_msg = timeout(Duration::from_secs(5), async {
1050 let next_msg = proj.next();
1051 pin_mut!(next_msg);
1052 let mut first_msg = None;
1053 loop {
1054 let notified = started_notify.notified();
1055 if started_count.load(atomic::Ordering::SeqCst) >= 3 {
1056 break;
1057 }
1058 tokio::select! {
1059 _ = notified => {}
1060 msg = &mut next_msg => {
1061 if started_count.load(atomic::Ordering::SeqCst) < 3 {
1062 panic!("project executor emitted before the post-watermark chunk started: {msg:?}");
1063 }
1064 first_msg = Some(msg.unwrap().unwrap());
1065 break;
1066 }
1067 }
1068 }
1069 match first_msg {
1070 Some(msg) => msg,
1071 None => next_msg.await.unwrap().unwrap(),
1072 }
1073 })
1074 .await
1075 .expect("post-watermark chunk expression did not start");
1076
1077 assert_eq!(
1078 *first_msg.as_chunk().unwrap(),
1079 StreamChunk::from_pretty(
1080 " I
1081 + 0"
1082 )
1083 );
1084 assert_eq!(
1085 *proj.next().await.unwrap().unwrap().as_chunk().unwrap(),
1086 StreamChunk::from_pretty(
1087 " I
1088 + 1"
1089 )
1090 );
1091 assert_eq!(
1092 proj.expect_watermark().await,
1093 Watermark {
1094 col_idx: 0,
1095 data_type: DataType::Int64,
1096 val: ScalarImpl::Int64(0)
1097 }
1098 );
1099 assert_eq!(
1100 *proj.next().await.unwrap().unwrap().as_chunk().unwrap(),
1101 StreamChunk::from_pretty(
1102 " I
1103 + 2"
1104 )
1105 );
1106 assert!(proj.next().await.unwrap().unwrap().is_stop());
1107 }
1108
1109 static DUMMY_COUNTER: AtomicI64 = AtomicI64::new(0);
1110
1111 #[derive(Debug)]
1112 struct DummyNondecreasingExpr;
1113
1114 impl ExpressionInfo for DummyNondecreasingExpr {
1115 fn return_type(&self) -> DataType {
1116 DataType::Int64
1117 }
1118 }
1119
1120 impl SyncExpression for DummyNondecreasingExpr {
1121 fn eval_v2(&self, input: &DataChunk) -> expr::Result<ValueImpl> {
1122 let value = DUMMY_COUNTER.fetch_add(1, atomic::Ordering::SeqCst);
1123 Ok(ValueImpl::Scalar {
1124 value: Some(value.into()),
1125 capacity: input.capacity(),
1126 })
1127 }
1128
1129 fn eval_row(&self, _input: &OwnedRow) -> expr::Result<Datum> {
1130 let value = DUMMY_COUNTER.fetch_add(1, atomic::Ordering::SeqCst);
1131 Ok(Some(value.into()))
1132 }
1133 }
1134
1135 #[tokio::test]
1136 async fn test_watermark_projection() {
1137 let schema = Schema {
1138 fields: vec![
1139 Field::unnamed(DataType::Int64),
1140 Field::unnamed(DataType::Int64),
1141 ],
1142 };
1143 let (mut tx, source) = MockSource::channel();
1144 let source = source.into_executor(schema, StreamKey::new());
1145
1146 let a_expr = build_from_pretty("(add:int8 $0:int8 1:int8)");
1147 let b_expr = build_from_pretty("(subtract:int8 $0:int8 1:int8)");
1148 let c_expr = NonStrictExpression::for_test(DummyNondecreasingExpr);
1149
1150 let proj = ProjectExecutor::new(
1151 ActorContext::for_test(123),
1152 source,
1153 vec![a_expr, b_expr, c_expr],
1154 MultiMap::from_iter(vec![(0, 0), (0, 1)].into_iter()),
1155 vec![2],
1156 false,
1157 );
1158 let mut proj = proj.boxed().execute();
1159
1160 tx.push_barrier(test_epoch(1), false);
1161 tx.push_int64_watermark(0, 100);
1162
1163 proj.expect_barrier().await;
1164 let w1 = proj.expect_watermark().await;
1165 let w2 = proj.expect_watermark().await;
1166 let (w1, w2) = if w1.col_idx < w2.col_idx {
1167 (w1, w2)
1168 } else {
1169 (w2, w1)
1170 };
1171
1172 assert_eq!(
1173 w1,
1174 Watermark {
1175 col_idx: 0,
1176 data_type: DataType::Int64,
1177 val: ScalarImpl::Int64(101)
1178 }
1179 );
1180 assert_eq!(
1181 w2,
1182 Watermark {
1183 col_idx: 1,
1184 data_type: DataType::Int64,
1185 val: ScalarImpl::Int64(99)
1186 }
1187 );
1188
1189 tx.push_chunk(StreamChunk::from_pretty(
1191 " I I
1192 + 120 4
1193 + 146 5
1194 + 133 6",
1195 ));
1196 proj.expect_chunk().await;
1197 tx.push_chunk(StreamChunk::from_pretty(
1198 " I I
1199 + 213 8
1200 - 133 6",
1201 ));
1202 proj.expect_chunk().await;
1203
1204 tx.push_barrier(test_epoch(2), false);
1205 let w3 = proj.expect_watermark().await;
1206 proj.expect_barrier().await;
1207
1208 tx.push_chunk(StreamChunk::from_pretty(
1209 " I I
1210 + 100 3
1211 + 104 5
1212 + 187 3",
1213 ));
1214 proj.expect_chunk().await;
1215
1216 tx.push_barrier(test_epoch(3), false);
1217 let w4 = proj.expect_watermark().await;
1218 proj.expect_barrier().await;
1219
1220 assert_eq!(w3.col_idx, w4.col_idx);
1221 assert!(w3.val.default_cmp(&w4.val).is_le());
1222
1223 tx.push_int64_watermark(1, 100);
1224 tx.push_barrier(test_epoch(4), true);
1225
1226 assert!(proj.next().await.unwrap().unwrap().is_stop());
1227 }
1228}