Skip to main content

risingwave_stream/executor/backfill/snapshot_backfill/
vnode_stream.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::mem::{replace, take};
17use std::pin::{Pin, pin};
18use std::task::{Context, Poll, ready};
19
20use futures::stream::{FuturesUnordered, Peekable, StreamFuture};
21use futures::{Stream, StreamExt, TryStreamExt};
22use pin_project::pin_project;
23use risingwave_common::array::{Op, StreamChunk};
24use risingwave_common::hash::VirtualNode;
25use risingwave_common::row::{OwnedRow, Row, RowExt};
26use risingwave_common::util::chunk_coalesce::DataChunkBuilder;
27use risingwave_common_rate_limit::RateLimit;
28use risingwave_storage::table::ChangeLogRow;
29use tokio::task::consume_budget;
30
31use crate::executor::StreamExecutorResult;
32use crate::executor::backfill::utils::create_builder;
33
34pub(super) trait ChangeLogRowStream =
35    Stream<Item = StreamExecutorResult<ChangeLogRow>> + Sized + 'static;
36
37#[pin_project]
38struct StreamWithVnode<St: ChangeLogRowStream> {
39    #[pin]
40    stream: Peekable<St>,
41    vnode: VirtualNode,
42    row_count: usize,
43}
44
45impl<St: ChangeLogRowStream> Stream for StreamWithVnode<St> {
46    type Item = St::Item;
47
48    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
49        let this = self.project();
50        let poll_result = this.stream.poll_next(cx);
51        if let Poll::Ready(Some(Ok(change_log_row))) = &poll_result {
52            match change_log_row {
53                ChangeLogRow::Insert(_) | ChangeLogRow::Delete(_) => {
54                    *this.row_count += 1;
55                }
56                ChangeLogRow::Update { .. } => {
57                    *this.row_count += 2;
58                }
59            }
60        }
61        poll_result
62    }
63}
64
65type ChangeLogRowVnodeStream<St> = Pin<Box<StreamWithVnode<St>>>;
66
67pub(super) struct VnodeStream<St: ChangeLogRowStream> {
68    streams: FuturesUnordered<StreamFuture<ChangeLogRowVnodeStream<St>>>,
69    pk_indices: Vec<usize>,
70    finished_vnode: HashMap<VirtualNode, usize>,
71    data_chunk_builder: DataChunkBuilder,
72    ops: Vec<Op>,
73}
74
75impl<St: ChangeLogRowStream> VnodeStream<St> {
76    pub(super) fn new(
77        vnode_streams: impl IntoIterator<Item = (VirtualNode, St, usize)>,
78        pk_indices: Vec<usize>,
79        data_chunk_builder: DataChunkBuilder,
80    ) -> Self {
81        assert!(data_chunk_builder.is_empty());
82        assert!(data_chunk_builder.batch_size() >= 2);
83        let streams = FuturesUnordered::from_iter(vnode_streams.into_iter().map(
84            |(vnode, stream, row_count)| {
85                let stream = stream.peekable();
86                Box::pin(StreamWithVnode {
87                    stream,
88                    vnode,
89                    row_count,
90                })
91                .into_future()
92            },
93        ));
94        let ops = Vec::with_capacity(data_chunk_builder.batch_size());
95        Self {
96            streams,
97            pk_indices,
98            finished_vnode: HashMap::new(),
99            data_chunk_builder,
100            ops,
101        }
102    }
103
104    pub(super) fn take_finished_vnodes(&mut self) -> HashMap<VirtualNode, usize> {
105        assert!(self.streams.is_empty());
106        assert!(self.data_chunk_builder.is_empty());
107        take(&mut self.finished_vnode)
108    }
109}
110
111impl<St: ChangeLogRowStream> VnodeStream<St> {
112    fn poll_next_row(
113        &mut self,
114        cx: &mut Context<'_>,
115    ) -> Poll<StreamExecutorResult<Option<ChangeLogRow>>> {
116        loop {
117            let ready_item = match ready!(self.streams.poll_next_unpin(cx)) {
118                None => Ok(None),
119                Some((None, stream)) => {
120                    self.finished_vnode
121                        .try_insert(stream.vnode, stream.row_count)
122                        .expect("non-duplicate");
123                    continue;
124                }
125                Some((Some(Ok(item)), stream)) => {
126                    // TODO: may avoid generating a `StreamFuture` for each row, because
127                    // `FuturesUnordered::push` involve memory allocation of `Arc`, and may
128                    // incur some unnecessary costs.
129                    self.streams.push(stream.into_future());
130                    Ok(Some(item))
131                }
132                Some((Some(Err(e)), _stream)) => Err(e),
133            };
134            break Poll::Ready(ready_item);
135        }
136    }
137
138    pub(super) fn consume_builder(&mut self) -> Option<StreamChunk> {
139        self.data_chunk_builder.consume_all().map(|chunk| {
140            let ops = replace(
141                &mut self.ops,
142                Vec::with_capacity(self.data_chunk_builder.batch_size()),
143            );
144            StreamChunk::from_parts(ops, chunk)
145        })
146    }
147
148    pub(super) fn update_rate_limiter(&mut self, new_rate_limit: RateLimit, chunk_size: usize) {
149        assert!(self.data_chunk_builder.is_empty());
150        self.data_chunk_builder = create_builder(
151            new_rate_limit,
152            chunk_size,
153            self.data_chunk_builder.data_types(),
154        );
155    }
156
157    pub(super) async fn for_vnode_pk_progress(
158        &mut self,
159        mut on_vnode_progress: impl FnMut(VirtualNode, usize, Option<OwnedRow>),
160    ) -> StreamExecutorResult<()> {
161        assert!(self.data_chunk_builder.is_empty());
162        for (vnode, row_count) in &self.finished_vnode {
163            on_vnode_progress(*vnode, *row_count, None);
164        }
165        let streams = take(&mut self.streams);
166        // When the `VnodeStream` is polled, the `FuturesUnordered` will generate a special cx to poll the futures.
167        // The pending futures will be stored in a separate linked list and will not be polled until the special cx is awakened
168        // and move the awakened future from the linked list to a ready queue.
169        //
170        // However, here if we use `FuturesUnordered::iter_mut` to in place access the pending futures and call `peek` directly,
171        // the cx specially generated in `FuturedUnordered::poll_next` will be overwritten, and then even the peeked future is ready,
172        // it will not be moved to the ready queue, and the `FuturesUnordered` will be stuck forever.
173        //
174        // Therefore, to avoid this, we will take all stream futures out and push them back again, so that all futures will be in the ready queue.
175        for vnode_stream_future in streams {
176            let mut vnode_stream = vnode_stream_future.into_inner().expect("should exist");
177            match vnode_stream.as_mut().project().stream.peek().await {
178                Some(Ok(change_log_row)) => {
179                    let row = match change_log_row {
180                        ChangeLogRow::Insert(row) | ChangeLogRow::Delete(row) => row,
181                        ChangeLogRow::Update {
182                            new_value,
183                            old_value,
184                        } => {
185                            if cfg!(debug_assertions) {
186                                assert_eq!(
187                                    old_value.project(&self.pk_indices),
188                                    new_value.project(&self.pk_indices)
189                                );
190                            }
191                            new_value
192                        }
193                    };
194                    let pk = row.project(&self.pk_indices).to_owned_row();
195                    on_vnode_progress(vnode_stream.vnode, vnode_stream.row_count, Some(pk));
196                    self.streams.push(vnode_stream.into_future());
197                }
198                Some(Err(_)) => {
199                    return Err(vnode_stream.try_next().await.expect_err("checked Err"));
200                }
201                None => {
202                    self.finished_vnode
203                        .try_insert(vnode_stream.vnode, vnode_stream.row_count)
204                        .expect("non-duplicate");
205                    on_vnode_progress(vnode_stream.vnode, vnode_stream.row_count, None);
206                }
207            }
208        }
209        Ok(())
210    }
211}
212
213impl<St: ChangeLogRowStream> Stream for VnodeStream<St> {
214    type Item = StreamExecutorResult<StreamChunk>;
215
216    // Here we implement the stream on our own instead of generating the stream with
217    // `try_stream` macro, because we want to access the state of the streams on the flight.
218    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
219        let this = self.get_mut();
220        let capacity = this.data_chunk_builder.batch_size();
221        loop {
222            match ready!(this.poll_next_row(cx)) {
223                Ok(Some(change_log_row)) => {
224                    let may_chunk = match change_log_row {
225                        ChangeLogRow::Insert(row) => {
226                            this.ops.push(Op::Insert);
227                            this.data_chunk_builder.append_one_row(row)
228                        }
229                        ChangeLogRow::Delete(row) => {
230                            this.ops.push(Op::Delete);
231                            this.data_chunk_builder.append_one_row(row)
232                        }
233                        ChangeLogRow::Update {
234                            new_value,
235                            old_value,
236                        } if new_value == old_value => {
237                            ready!(pin!(consume_budget()).poll(cx));
238                            continue;
239                        }
240                        ChangeLogRow::Update {
241                            new_value,
242                            old_value,
243                        } => {
244                            if this.data_chunk_builder.can_append_update() {
245                                this.ops.extend([Op::UpdateDelete, Op::UpdateInsert]);
246                                assert!(
247                                    this.data_chunk_builder.append_one_row(old_value).is_none()
248                                );
249                                this.data_chunk_builder.append_one_row(new_value)
250                            } else {
251                                let chunk = this
252                                    .data_chunk_builder
253                                    .consume_all()
254                                    .expect("should be Some when not can_append");
255                                let ops = replace(&mut this.ops, Vec::with_capacity(capacity));
256                                this.ops.extend([Op::UpdateDelete, Op::UpdateInsert]);
257                                assert!(
258                                    this.data_chunk_builder.append_one_row(old_value).is_none()
259                                );
260                                assert!(
261                                    this.data_chunk_builder.append_one_row(new_value).is_none()
262                                );
263                                break Poll::Ready(Some(Ok(StreamChunk::from_parts(ops, chunk))));
264                            }
265                        }
266                    };
267                    if let Some(chunk) = may_chunk {
268                        let ops = replace(&mut this.ops, Vec::with_capacity(capacity));
269                        break Poll::Ready(Some(Ok(StreamChunk::from_parts(ops, chunk))));
270                    }
271                }
272                Ok(None) => {
273                    break if let Some(chunk) = this.data_chunk_builder.consume_all() {
274                        let ops = take(&mut this.ops);
275                        Poll::Ready(Some(Ok(StreamChunk::from_parts(ops, chunk))))
276                    } else {
277                        Poll::Ready(None)
278                    };
279                }
280                Err(e) => {
281                    break Poll::Ready(Some(Err(e)));
282                }
283            }
284        }
285    }
286}
287
288#[cfg(test)]
289mod tests {
290    use std::collections::HashMap;
291    use std::future::poll_fn;
292    use std::sync::LazyLock;
293    use std::task::Poll;
294
295    use anyhow::anyhow;
296    use futures::{Future, FutureExt, pin_mut};
297    use risingwave_common::array::Op;
298    use risingwave_common::hash::VirtualNode;
299    use risingwave_common::row::OwnedRow;
300    use risingwave_common::types::{DataType, ScalarImpl};
301    use risingwave_common::util::chunk_coalesce::DataChunkBuilder;
302    use risingwave_storage::table::ChangeLogRow;
303    use tokio::sync::mpsc::unbounded_channel;
304    use tokio_stream::StreamExt;
305    use tokio_stream::wrappers::UnboundedReceiverStream;
306
307    use crate::executor::backfill::snapshot_backfill::vnode_stream::VnodeStream;
308
309    static DATA_TYPES: LazyLock<Vec<DataType>> = LazyLock::new(|| vec![DataType::Int64]);
310
311    fn test_row(index: i64) -> OwnedRow {
312        OwnedRow::new(vec![Some(ScalarImpl::Int64(index))])
313    }
314
315    impl<St: super::ChangeLogRowStream> VnodeStream<St> {
316        async fn assert_progress(
317            &mut self,
318            progress: impl IntoIterator<Item = (VirtualNode, usize, Option<OwnedRow>)>,
319        ) {
320            let expected_progress_map: HashMap<_, _> = progress
321                .into_iter()
322                .map(|(vnode, row_count, progress)| (vnode, (row_count, progress)))
323                .collect();
324            let mut progress_map = HashMap::new();
325            self.for_vnode_pk_progress(|vnode, row_count, progress| {
326                progress_map
327                    .try_insert(vnode, (row_count, progress))
328                    .unwrap();
329            })
330            .await
331            .unwrap();
332            assert_eq!(expected_progress_map, progress_map);
333        }
334    }
335
336    #[tokio::test]
337    async fn test_basic() {
338        let [vnode1, vnode2] = [1, 2].map(VirtualNode::from_index);
339        let (tx1, rx1) = unbounded_channel();
340        let (tx2, rx2) = unbounded_channel();
341        let mut stream = VnodeStream::<UnboundedReceiverStream<_>>::new(
342            [
343                (vnode1, UnboundedReceiverStream::new(rx1), 10),
344                (vnode2, UnboundedReceiverStream::new(rx2), 0),
345            ]
346            .into_iter(),
347            vec![0],
348            DataChunkBuilder::new(DATA_TYPES.clone(), 3),
349        );
350        assert!(stream.next().now_or_never().is_none());
351        tx1.send(Ok(ChangeLogRow::Insert(test_row(0)))).unwrap();
352        assert!(stream.next().now_or_never().is_none());
353        tx2.send(Ok(ChangeLogRow::Insert(test_row(0)))).unwrap();
354        tx2.send(Ok(ChangeLogRow::Insert(test_row(1)))).unwrap();
355        assert_eq!(3, stream.next().await.unwrap().unwrap().cardinality());
356
357        let next_row = test_row(1);
358        {
359            let future =
360                stream.assert_progress([(vnode1, 11, Some(next_row.clone())), (vnode2, 2, None)]);
361            pin_mut!(future);
362            assert!((&mut future).now_or_never().is_none());
363            tx1.send(Ok(ChangeLogRow::Insert(next_row.clone())))
364                .unwrap();
365            assert!((&mut future).now_or_never().is_none());
366            drop(tx2);
367            future.await;
368        }
369        assert!(stream.next().now_or_never().is_none());
370        assert_eq!(1, stream.consume_builder().unwrap().cardinality());
371        {
372            let future = stream.assert_progress([(vnode1, 12, None), (vnode2, 2, None)]);
373            pin_mut!(future);
374            assert!((&mut future).now_or_never().is_none());
375            drop(tx1);
376            future.await;
377        }
378        assert!(stream.next().await.is_none());
379    }
380
381    #[tokio::test]
382    async fn test_update() {
383        let (tx, rx) = unbounded_channel();
384        let mut stream = VnodeStream::new(
385            [(VirtualNode::ZERO, UnboundedReceiverStream::new(rx), 0)].into_iter(),
386            vec![0],
387            DataChunkBuilder::new(DATA_TYPES.clone(), 3),
388        );
389        assert!(stream.next().now_or_never().is_none());
390        tx.send(Ok(ChangeLogRow::Insert(test_row(0)))).unwrap();
391        tx.send(Ok(ChangeLogRow::Insert(test_row(1)))).unwrap();
392        assert!(stream.next().now_or_never().is_none());
393        tx.send(Ok(ChangeLogRow::Update {
394            new_value: test_row(2),
395            old_value: test_row(3),
396        }))
397        .unwrap();
398        assert_eq!(2, stream.next().await.unwrap().unwrap().cardinality());
399        drop(tx);
400        assert_eq!(2, stream.next().await.unwrap().unwrap().cardinality());
401        assert!(stream.next().await.is_none());
402        stream.assert_progress([(VirtualNode::ZERO, 4, None)]).await;
403    }
404
405    #[tokio::test]
406    async fn test_skip_noop_update() {
407        let (tx, rx) = unbounded_channel();
408        let mut stream = VnodeStream::new(
409            [(VirtualNode::ZERO, UnboundedReceiverStream::new(rx), 0)].into_iter(),
410            vec![0],
411            DataChunkBuilder::new(DATA_TYPES.clone(), 3),
412        );
413        tx.send(Ok(ChangeLogRow::Insert(test_row(0)))).unwrap();
414        tx.send(Ok(ChangeLogRow::Update {
415            new_value: test_row(1),
416            old_value: test_row(1),
417        }))
418        .unwrap();
419        tx.send(Ok(ChangeLogRow::Insert(test_row(2)))).unwrap();
420        drop(tx);
421        let chunk = stream.next().await.unwrap().unwrap();
422        assert_eq!(chunk.ops(), &[Op::Insert, Op::Insert]);
423        assert!(stream.next().await.is_none());
424        stream.assert_progress([(VirtualNode::ZERO, 4, None)]).await;
425    }
426
427    #[tokio::test]
428    async fn test_yield_after_skipping_noop_updates() {
429        let rows = (0..1024)
430            .map(|i| ChangeLogRow::Update {
431                new_value: test_row(i),
432                old_value: test_row(i),
433            })
434            .chain([ChangeLogRow::Insert(test_row(1024))])
435            .map(Ok);
436        let mut stream = VnodeStream::new(
437            [(VirtualNode::ZERO, futures::stream::iter(rows), 0)].into_iter(),
438            vec![0],
439            DataChunkBuilder::new(DATA_TYPES.clone(), 4),
440        );
441        assert!(stream.next().now_or_never().is_none());
442        let chunk = stream.next().await.unwrap().unwrap();
443        assert_eq!(chunk.ops(), &[Op::Insert]);
444        assert!(stream.next().await.is_none());
445        stream
446            .assert_progress([(VirtualNode::ZERO, 2049, None)])
447            .await;
448    }
449
450    #[tokio::test]
451    async fn test_empty() {
452        let mut stream = VnodeStream::<UnboundedReceiverStream<_>>::new(
453            [].into_iter(),
454            vec![0],
455            DataChunkBuilder::new(DATA_TYPES.clone(), 1024),
456        );
457        assert!(stream.next().await.is_none());
458    }
459
460    #[tokio::test]
461    async fn test_err() {
462        {
463            let (tx, rx) = unbounded_channel();
464            let mut stream = VnodeStream::new(
465                [(VirtualNode::ZERO, UnboundedReceiverStream::new(rx), 0)].into_iter(),
466                vec![0],
467                DataChunkBuilder::new(DATA_TYPES.clone(), 3),
468            );
469            assert!(stream.next().now_or_never().is_none());
470            tx.send(Err(anyhow!("err").into())).unwrap();
471            assert!(stream.next().await.unwrap().is_err());
472        }
473        {
474            let (tx, rx) = unbounded_channel();
475            let mut stream = VnodeStream::new(
476                [(VirtualNode::ZERO, UnboundedReceiverStream::new(rx), 0)].into_iter(),
477                vec![0],
478                DataChunkBuilder::new(DATA_TYPES.clone(), 3),
479            );
480            assert!(stream.next().now_or_never().is_none());
481            let future = stream.for_vnode_pk_progress(|_, _, _| unreachable!());
482            pin_mut!(future);
483            assert!((&mut future).now_or_never().is_none());
484            tx.send(Err(anyhow!("err").into())).unwrap();
485            assert!(future.await.is_err());
486        }
487    }
488
489    #[tokio::test]
490    async fn test_futures_unordered_peek() {
491        let (tx, rx) = unbounded_channel();
492        let mut stream = VnodeStream::new(
493            [(VirtualNode::ZERO, UnboundedReceiverStream::new(rx), 0)].into_iter(),
494            vec![0],
495            DataChunkBuilder::new(DATA_TYPES.clone(), 1024),
496        );
497        // poll the stream for once, and then the stream future inside it will be stored in the pending list.
498        assert!(stream.next().now_or_never().is_none());
499        let row = test_row(1);
500        {
501            let fut = stream.assert_progress([(VirtualNode::ZERO, 0, Some(row.clone()))]);
502            pin_mut!(fut);
503            assert!(
504                poll_fn(|cx| Poll::Ready(fut.as_mut().poll(cx)))
505                    .await
506                    .is_pending()
507            );
508            tx.send(Ok(ChangeLogRow::Insert(row.clone()))).unwrap();
509            drop(tx);
510            fut.await;
511        }
512        let chunk = stream.next().await.unwrap().unwrap();
513        assert_eq!(chunk.capacity(), 1);
514    }
515}