risingwave_stream/executor/backfill/
arrangement_backfill.rs

1// Copyright 2025 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;
16
17use either::Either;
18use futures::stream::{select_all, select_with_strategy};
19use futures::{TryStreamExt, stream};
20use itertools::Itertools;
21use risingwave_common::array::{DataChunk, Op};
22use risingwave_common::bail;
23use risingwave_common::hash::{VirtualNode, VnodeBitmapExt};
24use risingwave_common::util::chunk_coalesce::DataChunkBuilder;
25use risingwave_common_rate_limit::{MonitoredRateLimiter, RateLimit, RateLimiter};
26use risingwave_storage::row_serde::value_serde::ValueRowSerde;
27use risingwave_storage::store::PrefetchOptions;
28
29use crate::common::table::state_table::ReplicatedStateTable;
30#[cfg(debug_assertions)]
31use crate::executor::backfill::utils::METADATA_STATE_LEN;
32use crate::executor::backfill::utils::{
33    BackfillProgressPerVnode, BackfillState, compute_bounds, create_builder,
34    get_progress_per_vnode, mapping_chunk, mapping_message, mark_chunk_ref_by_vnode,
35    persist_state_per_vnode, update_pos_by_vnode,
36};
37use crate::executor::prelude::*;
38use crate::task::{CreateMviewProgressReporter, FragmentId};
39
40type Builders = HashMap<VirtualNode, DataChunkBuilder>;
41
42/// Similar to [`super::no_shuffle_backfill::BackfillExecutor`].
43/// Main differences:
44/// - [`ArrangementBackfillExecutor`] can reside on a different CN, so it can be scaled
45///   independently.
46/// - To synchronize upstream shared buffer, it is initialized with a [`ReplicatedStateTable`].
47pub struct ArrangementBackfillExecutor<S: StateStore, SD: ValueRowSerde> {
48    /// Upstream table
49    upstream_table: ReplicatedStateTable<S, SD>,
50
51    /// Upstream with the same schema with the upstream table.
52    upstream: Executor,
53
54    /// Internal state table for persisting state of backfill state.
55    state_table: StateTable<S>,
56
57    /// The column indices need to be forwarded to the downstream from the upstream and table scan.
58    output_indices: Vec<usize>,
59
60    progress: CreateMviewProgressReporter,
61
62    actor_id: ActorId,
63
64    metrics: Arc<StreamingMetrics>,
65
66    chunk_size: usize,
67
68    rate_limiter: MonitoredRateLimiter,
69
70    /// Fragment id of the fragment this backfill node belongs to.
71    fragment_id: FragmentId,
72}
73
74impl<S, SD> ArrangementBackfillExecutor<S, SD>
75where
76    S: StateStore,
77    SD: ValueRowSerde,
78{
79    #[allow(clippy::too_many_arguments)]
80    #[allow(dead_code)]
81    pub fn new(
82        upstream_table: ReplicatedStateTable<S, SD>,
83        upstream: Executor,
84        state_table: StateTable<S>,
85        output_indices: Vec<usize>,
86        progress: CreateMviewProgressReporter,
87        metrics: Arc<StreamingMetrics>,
88        chunk_size: usize,
89        rate_limit: RateLimit,
90        fragment_id: FragmentId,
91    ) -> Self {
92        let rate_limiter = RateLimiter::new(rate_limit).monitored(upstream_table.table_id());
93        Self {
94            upstream_table,
95            upstream,
96            state_table,
97            output_indices,
98            actor_id: progress.actor_id(),
99            progress,
100            metrics,
101            chunk_size,
102            rate_limiter,
103            fragment_id,
104        }
105    }
106
107    #[try_stream(ok = Message, error = StreamExecutorError)]
108    async fn execute_inner(mut self) {
109        tracing::debug!("backfill executor started");
110        // The primary key columns, in the output columns of the upstream_table scan.
111        // Table scan scans a subset of the columns of the upstream table.
112        let pk_in_output_indices = self.upstream_table.pk_in_output_indices().unwrap();
113        #[cfg(debug_assertions)]
114        let state_len = self.upstream_table.pk_indices().len() + METADATA_STATE_LEN;
115        let pk_order = self.upstream_table.pk_serde().get_order_types().to_vec();
116        let upstream_table_id = self.upstream_table.table_id();
117        let mut upstream_table = self.upstream_table;
118        let vnodes = upstream_table.vnodes().clone();
119
120        // These builders will build data chunks.
121        // We must supply them with the full datatypes which correspond to
122        // pk + output_indices.
123        let snapshot_data_types = self
124            .upstream
125            .schema()
126            .fields()
127            .iter()
128            .map(|field| field.data_type.clone())
129            .collect_vec();
130        let mut builders: Builders = upstream_table
131            .vnodes()
132            .iter_vnodes()
133            .map(|vnode| {
134                let builder = create_builder(
135                    self.rate_limiter.rate_limit(),
136                    self.chunk_size,
137                    snapshot_data_types.clone(),
138                );
139                (vnode, builder)
140            })
141            .collect();
142
143        let mut upstream = self.upstream.execute();
144
145        // Poll the upstream to get the first barrier.
146        let first_barrier = expect_first_barrier(&mut upstream).await?;
147        let mut global_pause = first_barrier.is_pause_on_startup();
148        let mut backfill_paused = first_barrier.is_backfill_pause_on_startup(self.fragment_id);
149        let first_epoch = first_barrier.epoch;
150        let is_newly_added = first_barrier.is_newly_added(self.actor_id);
151        // The first barrier message should be propagated.
152        yield Message::Barrier(first_barrier);
153
154        self.state_table.init_epoch(first_epoch).await?;
155
156        let progress_per_vnode = get_progress_per_vnode(&self.state_table).await?;
157
158        let is_completely_finished = progress_per_vnode.iter().all(|(_, p)| {
159            matches!(
160                p.current_state(),
161                &BackfillProgressPerVnode::Completed { .. }
162            )
163        });
164        if is_completely_finished {
165            assert!(!is_newly_added);
166        }
167
168        upstream_table.init_epoch(first_epoch).await?;
169
170        let mut backfill_state: BackfillState = progress_per_vnode.into();
171
172        let to_backfill = !is_completely_finished;
173
174        // If no need backfill, but state was still "unfinished" we need to finish it.
175        // So we just update the state + progress to meta at the next barrier to finish progress,
176        // and forward other messages.
177        //
178        // Reason for persisting on second barrier rather than first:
179        // We can't update meta with progress as finished until state_table
180        // has been updated.
181        // We also can't update state_table in first epoch, since state_table
182        // expects to have been initialized in previous epoch.
183
184        // The epoch used to snapshot read upstream mv.
185        let mut snapshot_read_epoch;
186
187        // Keep track of rows from the snapshot.
188        let mut total_snapshot_processed_rows: u64 = backfill_state.get_snapshot_row_count();
189
190        // Arrangement Backfill Algorithm:
191        //
192        //   backfill_stream
193        //  /               \
194        // upstream       snapshot
195        //
196        // We construct a backfill stream with upstream as its left input and mv snapshot read
197        // stream as its right input. When a chunk comes from upstream, we will buffer it.
198        //
199        // When a barrier comes from upstream:
200        //  Immediately break out of backfill loop.
201        //  - For each row of the upstream chunk buffer, compute vnode.
202        //  - Get the `current_pos` corresponding to the vnode. Forward it to downstream if its pk
203        //    <= `current_pos`, otherwise ignore it.
204        //  - Flush all buffered upstream_chunks to replicated state table.
205        //  - Update the `snapshot_read_epoch`.
206        //  - Reconstruct the whole backfill stream with upstream and new mv snapshot read stream
207        //    with the `snapshot_read_epoch`.
208        //
209        // When a chunk comes from snapshot, we forward it to the downstream and raise
210        // `current_pos`.
211        //
212        // When we reach the end of the snapshot read stream, it means backfill has been
213        // finished.
214        //
215        // Once the backfill loop ends, we forward the upstream directly to the downstream.
216        if to_backfill {
217            let mut upstream_chunk_buffer: Vec<StreamChunk> = vec![];
218            let mut pending_barrier: Option<Barrier> = None;
219
220            let metrics = self
221                .metrics
222                .new_backfill_metrics(upstream_table_id, self.actor_id);
223
224            'backfill_loop: loop {
225                let mut cur_barrier_snapshot_processed_rows: u64 = 0;
226                let mut cur_barrier_upstream_processed_rows: u64 = 0;
227                let mut snapshot_read_complete = false;
228                let mut has_snapshot_read = false;
229
230                // NOTE(kwannoel): Scope it so that immutable reference to `upstream_table` can be
231                // dropped. Then we can write to `upstream_table` on barrier in the
232                // next block.
233                {
234                    let left_upstream = upstream.by_ref().map(Either::Left);
235
236                    // Check if stream paused
237                    let paused = global_pause
238                        || backfill_paused
239                        || matches!(self.rate_limiter.rate_limit(), RateLimit::Pause);
240                    // Create the snapshot stream
241                    let right_snapshot = pin!(
242                        Self::make_snapshot_stream(
243                            &upstream_table,
244                            backfill_state.clone(), // FIXME: Use mutable reference instead.
245                            paused,
246                            &self.rate_limiter,
247                        )
248                        .map(Either::Right)
249                    );
250
251                    // Prefer to select upstream, so we can stop snapshot stream as soon as the
252                    // barrier comes.
253                    let mut backfill_stream =
254                        select_with_strategy(left_upstream, right_snapshot, |_: &mut ()| {
255                            stream::PollNext::Left
256                        });
257
258                    #[for_await]
259                    for either in &mut backfill_stream {
260                        match either {
261                            // Upstream
262                            Either::Left(msg) => {
263                                match msg? {
264                                    Message::Barrier(barrier) => {
265                                        // We have to process the barrier outside of the loop.
266                                        // This is because our state_table reference is still live
267                                        // here, we have to break the loop to drop it,
268                                        // so we can do replication of upstream state_table.
269                                        pending_barrier = Some(barrier);
270
271                                        // Break the for loop and start a new snapshot read stream.
272                                        break;
273                                    }
274                                    Message::Chunk(chunk) => {
275                                        // Buffer the upstream chunk.
276                                        upstream_chunk_buffer.push(chunk.compact());
277                                    }
278                                    Message::Watermark(_) => {
279                                        // Ignore watermark during backfill.
280                                    }
281                                }
282                            }
283                            // Snapshot read
284                            Either::Right(msg) => {
285                                has_snapshot_read = true;
286                                match msg? {
287                                    None => {
288                                        // Consume remaining rows in the builder.
289                                        for (vnode, builder) in &mut builders {
290                                            if let Some(data_chunk) = builder.consume_all() {
291                                                yield Message::Chunk(Self::handle_snapshot_chunk(
292                                                    data_chunk,
293                                                    *vnode,
294                                                    &pk_in_output_indices,
295                                                    &mut backfill_state,
296                                                    &mut cur_barrier_snapshot_processed_rows,
297                                                    &mut total_snapshot_processed_rows,
298                                                    &self.output_indices,
299                                                )?);
300                                            }
301                                        }
302
303                                        // End of the snapshot read stream.
304                                        // We should not mark the chunk anymore,
305                                        // otherwise, we will ignore some rows
306                                        // in the buffer. Here we choose to never mark the chunk.
307                                        // Consume with the renaming stream buffer chunk without
308                                        // mark.
309                                        for chunk in upstream_chunk_buffer.drain(..) {
310                                            let chunk_cardinality = chunk.cardinality() as u64;
311                                            cur_barrier_upstream_processed_rows +=
312                                                chunk_cardinality;
313                                            yield Message::Chunk(mapping_chunk(
314                                                chunk,
315                                                &self.output_indices,
316                                            ));
317                                        }
318                                        metrics
319                                            .backfill_snapshot_read_row_count
320                                            .inc_by(cur_barrier_snapshot_processed_rows);
321                                        metrics
322                                            .backfill_upstream_output_row_count
323                                            .inc_by(cur_barrier_upstream_processed_rows);
324                                        break 'backfill_loop;
325                                    }
326                                    Some((vnode, row)) => {
327                                        let builder = builders.get_mut(&vnode).unwrap();
328                                        if let Some(chunk) = builder.append_one_row(row) {
329                                            yield Message::Chunk(Self::handle_snapshot_chunk(
330                                                chunk,
331                                                vnode,
332                                                &pk_in_output_indices,
333                                                &mut backfill_state,
334                                                &mut cur_barrier_snapshot_processed_rows,
335                                                &mut total_snapshot_processed_rows,
336                                                &self.output_indices,
337                                            )?);
338                                        }
339                                    }
340                                }
341                            }
342                        }
343                    }
344
345                    // Before processing barrier, if did not snapshot read,
346                    // do a snapshot read first.
347                    // This is so we don't lose the tombstone iteration progress.
348                    // Or if s3 read latency is high, we don't fail to read from s3.
349                    //
350                    // If paused, we can't read any snapshot records, skip this.
351                    //
352                    // If rate limit is set, respect the rate limit, check if we can read,
353                    // If we can't, skip it. If no rate limit set, we can read.
354                    let rate_limit_ready = self.rate_limiter.check(1).is_ok();
355                    if !has_snapshot_read && !paused && rate_limit_ready {
356                        debug_assert!(builders.values().all(|b| b.is_empty()));
357                        let (_, snapshot) = backfill_stream.into_inner();
358                        #[for_await]
359                        for msg in snapshot {
360                            let Either::Right(msg) = msg else {
361                                bail!("BUG: snapshot_read contains upstream messages");
362                            };
363                            match msg? {
364                                None => {
365                                    // End of the snapshot read stream.
366                                    // We let the barrier handling logic take care of upstream updates.
367                                    // But we still want to exit backfill loop, so we mark snapshot read complete.
368                                    snapshot_read_complete = true;
369                                    break;
370                                }
371                                Some((vnode, row)) => {
372                                    let builder = builders.get_mut(&vnode).unwrap();
373                                    if let Some(chunk) = builder.append_one_row(row) {
374                                        yield Message::Chunk(Self::handle_snapshot_chunk(
375                                            chunk,
376                                            vnode,
377                                            &pk_in_output_indices,
378                                            &mut backfill_state,
379                                            &mut cur_barrier_snapshot_processed_rows,
380                                            &mut total_snapshot_processed_rows,
381                                            &self.output_indices,
382                                        )?);
383                                    }
384
385                                    break;
386                                }
387                            }
388                        }
389                    }
390                }
391
392                // Process barrier
393                // When we break out of inner backfill_stream loop, it means we have a barrier.
394                // If there are no updates and there are no snapshots left,
395                // we already finished backfill and should have exited the outer backfill loop.
396                let barrier = match pending_barrier.take() {
397                    Some(barrier) => barrier,
398                    None => bail!("BUG: current_backfill loop exited without a barrier"),
399                };
400
401                // Process barrier:
402                // - consume snapshot rows left in builder.
403                // - consume upstream buffer chunk
404                // - handle mutations
405                // - switch snapshot
406
407                // consume snapshot rows left in builder.
408                // NOTE(kwannoel): `zip_eq_debug` does not work here,
409                // we encounter "higher-ranked lifetime error".
410                for (vnode, chunk) in builders.iter_mut().map(|(vnode, b)| {
411                    let chunk = b.consume_all().map(|chunk| {
412                        let ops = vec![Op::Insert; chunk.capacity()];
413                        StreamChunk::from_parts(ops, chunk)
414                    });
415                    (vnode, chunk)
416                }) {
417                    if let Some(chunk) = chunk {
418                        let chunk_cardinality = chunk.cardinality() as u64;
419                        // Raise the current position.
420                        // As snapshot read streams are ordered by pk, so we can
421                        // just use the last row to update `current_pos`.
422                        update_pos_by_vnode(
423                            *vnode,
424                            &chunk,
425                            &pk_in_output_indices,
426                            &mut backfill_state,
427                            chunk_cardinality,
428                        )?;
429
430                        cur_barrier_snapshot_processed_rows += chunk_cardinality;
431                        total_snapshot_processed_rows += chunk_cardinality;
432                        yield Message::Chunk(mapping_chunk(chunk, &self.output_indices));
433                    }
434                }
435
436                // consume upstream buffer chunk
437                for chunk in upstream_chunk_buffer.drain(..) {
438                    cur_barrier_upstream_processed_rows += chunk.cardinality() as u64;
439                    // FIXME: Replace with `snapshot_is_processed`
440                    // Flush downstream.
441                    // If no current_pos, means no snapshot processed yet.
442                    // Also means we don't need propagate any updates <= current_pos.
443                    if backfill_state.has_progress() {
444                        yield Message::Chunk(mapping_chunk(
445                            mark_chunk_ref_by_vnode(
446                                &chunk,
447                                &backfill_state,
448                                &pk_in_output_indices,
449                                &upstream_table,
450                                &pk_order,
451                            )?,
452                            &self.output_indices,
453                        ));
454                    }
455
456                    // Replicate
457                    upstream_table.write_chunk(chunk);
458                }
459
460                upstream_table
461                    .commit_assert_no_update_vnode_bitmap(barrier.epoch)
462                    .await?;
463
464                metrics
465                    .backfill_snapshot_read_row_count
466                    .inc_by(cur_barrier_snapshot_processed_rows);
467                metrics
468                    .backfill_upstream_output_row_count
469                    .inc_by(cur_barrier_upstream_processed_rows);
470
471                // Update snapshot read epoch.
472                snapshot_read_epoch = barrier.epoch.prev;
473
474                // TODO(kwannoel): Not sure if this holds for arrangement backfill.
475                // May need to revisit it.
476                // Need to check it after scale-in / scale-out.
477                self.progress.update(
478                    barrier.epoch,
479                    snapshot_read_epoch,
480                    total_snapshot_processed_rows,
481                );
482
483                // Persist state on barrier
484                persist_state_per_vnode(
485                    barrier.epoch,
486                    &mut self.state_table,
487                    &mut backfill_state,
488                    #[cfg(debug_assertions)]
489                    state_len,
490                    vnodes.iter_vnodes(),
491                )
492                .await?;
493
494                tracing::trace!(
495                    barrier = ?barrier,
496                    "barrier persisted"
497                );
498
499                // handle mutations
500                if let Some(mutation) = barrier.mutation.as_deref() {
501                    use crate::executor::Mutation;
502                    match mutation {
503                        Mutation::Pause => {
504                            global_pause = true;
505                        }
506                        Mutation::Resume => {
507                            global_pause = false;
508                        }
509                        Mutation::StartFragmentBackfill { fragment_ids } if backfill_paused => {
510                            if fragment_ids.contains(&self.fragment_id) {
511                                backfill_paused = false;
512                            }
513                        }
514                        Mutation::Throttle(actor_to_apply) => {
515                            let new_rate_limit_entry = actor_to_apply.get(&self.actor_id);
516                            if let Some(new_rate_limit) = new_rate_limit_entry {
517                                let new_rate_limit = (*new_rate_limit).into();
518                                let old_rate_limit = self.rate_limiter.update(new_rate_limit);
519                                if old_rate_limit != new_rate_limit {
520                                    tracing::info!(
521                                        old_rate_limit = ?old_rate_limit,
522                                        new_rate_limit = ?new_rate_limit,
523                                        upstream_table_id = upstream_table_id,
524                                        actor_id = self.actor_id,
525                                        "backfill rate limit changed",
526                                    );
527                                    builders = upstream_table
528                                        .vnodes()
529                                        .iter_vnodes()
530                                        .map(|vnode| {
531                                            let builder = create_builder(
532                                                new_rate_limit,
533                                                self.chunk_size,
534                                                snapshot_data_types.clone(),
535                                            );
536                                            (vnode, builder)
537                                        })
538                                        .collect();
539                                }
540                            }
541                        }
542                        _ => {}
543                    }
544                }
545
546                yield Message::Barrier(barrier);
547
548                // We will switch snapshot at the start of the next iteration of the backfill loop.
549                // Unless snapshot read is already completed.
550                if snapshot_read_complete {
551                    break 'backfill_loop;
552                }
553            }
554        }
555
556        tracing::debug!("snapshot read finished, wait to commit state on next barrier");
557
558        // Update our progress as finished in state table.
559
560        // Wait for first barrier to come after backfill is finished.
561        // So we can update our progress + persist the status.
562        while let Some(Ok(msg)) = upstream.next().await {
563            if let Some(msg) = mapping_message(msg, &self.output_indices) {
564                // If not finished then we need to update state, otherwise no need.
565                if let Message::Barrier(barrier) = &msg {
566                    if is_completely_finished {
567                        // If already finished, no need to persist any state. But we need to advance the epoch anyway
568                        self.state_table
569                            .commit_assert_no_update_vnode_bitmap(barrier.epoch)
570                            .await?;
571                    } else {
572                        // If snapshot was empty, we do not need to backfill,
573                        // but we still need to persist the finished state.
574                        // We currently persist it on the second barrier here rather than first.
575                        // This is because we can't update state table in first epoch,
576                        // since it expects to have been initialized in previous epoch
577                        // (there's no epoch before the first epoch).
578                        for vnode in upstream_table.vnodes().iter_vnodes() {
579                            backfill_state
580                                .finish_progress(vnode, upstream_table.pk_indices().len());
581                        }
582
583                        persist_state_per_vnode(
584                            barrier.epoch,
585                            &mut self.state_table,
586                            &mut backfill_state,
587                            #[cfg(debug_assertions)]
588                            state_len,
589                            vnodes.iter_vnodes(),
590                        )
591                        .await?;
592                    }
593
594                    self.progress
595                        .finish(barrier.epoch, total_snapshot_processed_rows);
596                    yield msg;
597                    break;
598                }
599                // Allow other messages to pass through.
600                // We won't yield twice here, since if there's a barrier,
601                // we will always break out of the loop.
602                yield msg;
603            }
604        }
605
606        tracing::debug!("backfill finished");
607
608        // After progress finished + state persisted,
609        // we can forward messages directly to the downstream,
610        // as backfill is finished.
611        #[for_await]
612        for msg in upstream {
613            if let Some(msg) = mapping_message(msg?, &self.output_indices) {
614                if let Message::Barrier(barrier) = &msg {
615                    // If already finished, no need persist any state, but we need to advance the epoch of the state table anyway.
616                    self.state_table
617                        .commit_assert_no_update_vnode_bitmap(barrier.epoch)
618                        .await?;
619                }
620                yield msg;
621            }
622        }
623    }
624
625    #[try_stream(ok = Option<(VirtualNode, OwnedRow)>, error = StreamExecutorError)]
626    async fn make_snapshot_stream<'a>(
627        upstream_table: &'a ReplicatedStateTable<S, SD>,
628        backfill_state: BackfillState,
629        paused: bool,
630        rate_limiter: &'a MonitoredRateLimiter,
631    ) {
632        if paused {
633            #[for_await]
634            for _ in tokio_stream::pending() {
635                bail!("BUG: paused stream should not yield");
636            }
637        } else {
638            // Checked the rate limit is not zero.
639            #[for_await]
640            for r in Self::snapshot_read_per_vnode(upstream_table, backfill_state) {
641                let r = r?;
642                rate_limiter.wait(1).await;
643                yield r;
644            }
645        }
646    }
647
648    fn handle_snapshot_chunk(
649        chunk: DataChunk,
650        vnode: VirtualNode,
651        pk_in_output_indices: &[usize],
652        backfill_state: &mut BackfillState,
653        cur_barrier_snapshot_processed_rows: &mut u64,
654        total_snapshot_processed_rows: &mut u64,
655        output_indices: &[usize],
656    ) -> StreamExecutorResult<StreamChunk> {
657        let chunk = StreamChunk::from_parts(vec![Op::Insert; chunk.capacity()], chunk);
658        // Raise the current position.
659        // As snapshot read streams are ordered by pk, so we can
660        // just use the last row to update `current_pos`.
661        let snapshot_row_count_delta = chunk.cardinality() as u64;
662        update_pos_by_vnode(
663            vnode,
664            &chunk,
665            pk_in_output_indices,
666            backfill_state,
667            snapshot_row_count_delta,
668        )?;
669
670        let chunk_cardinality = chunk.cardinality() as u64;
671        *cur_barrier_snapshot_processed_rows += chunk_cardinality;
672        *total_snapshot_processed_rows += chunk_cardinality;
673        Ok(mapping_chunk(chunk, output_indices))
674    }
675
676    /// Read snapshot per vnode.
677    /// These streams should be sorted in storage layer.
678    /// 1. Get row iterator / vnode.
679    /// 2. Merge it with `select_all`.
680    /// 3. Change it into a chunk iterator with `iter_chunks`.
681    /// This means it should fetch a row from each iterator to form a chunk.
682    ///
683    /// We interleave at chunk per vnode level rather than rows.
684    /// This is so that we can compute `current_pos` once per chunk, since they correspond to 1
685    /// vnode.
686    ///
687    /// The stream contains pairs of `(VirtualNode, StreamChunk)`.
688    /// The `VirtualNode` is the vnode that the chunk belongs to.
689    /// The `StreamChunk` is the chunk that contains the rows from the vnode.
690    /// If it's `None`, it means the vnode has no more rows for this snapshot read.
691    ///
692    /// The `snapshot_read_epoch` is supplied as a parameter for `state_table`.
693    /// It is required to ensure we read a fully-checkpointed snapshot the **first time**.
694    ///
695    /// The rows from upstream snapshot read will be buffered inside the `builder`.
696    /// If snapshot is dropped before its rows are consumed,
697    /// remaining data in `builder` must be flushed manually.
698    /// Otherwise when we scan a new snapshot, it is possible the rows in the `builder` would be
699    /// present, Then when we flush we contain duplicate rows.
700    #[try_stream(ok = Option<(VirtualNode, OwnedRow)>, error = StreamExecutorError)]
701    async fn snapshot_read_per_vnode(
702        upstream_table: &ReplicatedStateTable<S, SD>,
703        backfill_state: BackfillState,
704    ) {
705        let mut iterators = vec![];
706        for vnode in upstream_table.vnodes().iter_vnodes() {
707            let backfill_progress = backfill_state.get_progress(&vnode)?;
708            let current_pos = match backfill_progress {
709                BackfillProgressPerVnode::NotStarted => None,
710                BackfillProgressPerVnode::Completed { .. } => {
711                    continue;
712                }
713                BackfillProgressPerVnode::InProgress { current_pos, .. } => {
714                    Some(current_pos.clone())
715                }
716            };
717
718            let range_bounds = compute_bounds(upstream_table.pk_indices(), current_pos.clone());
719            if range_bounds.is_none() {
720                continue;
721            }
722            let range_bounds = range_bounds.unwrap();
723
724            tracing::trace!(
725                vnode = ?vnode,
726                current_pos = ?current_pos,
727                range_bounds = ?range_bounds,
728                "iter_with_vnode_and_output_indices"
729            );
730            let vnode_row_iter = upstream_table
731                .iter_with_vnode_and_output_indices(
732                    vnode,
733                    &range_bounds,
734                    PrefetchOptions::prefetch_for_small_range_scan(),
735                )
736                .await?;
737
738            let vnode_row_iter = vnode_row_iter.map_ok(move |row| (vnode, row));
739
740            let vnode_row_iter = Box::pin(vnode_row_iter);
741
742            iterators.push(vnode_row_iter);
743        }
744
745        // TODO(kwannoel): We can provide an option between snapshot read in parallel vs serial.
746        let vnode_row_iter = select_all(iterators);
747
748        #[for_await]
749        for vnode_and_row in vnode_row_iter {
750            yield Some(vnode_and_row?);
751        }
752        yield None;
753        return Ok(());
754    }
755}
756
757impl<S, SD> Execute for ArrangementBackfillExecutor<S, SD>
758where
759    S: StateStore,
760    SD: ValueRowSerde,
761{
762    fn execute(self: Box<Self>) -> BoxedMessageStream {
763        self.execute_inner().boxed()
764    }
765}