Skip to main content

risingwave_stream/executor/backfill/
utils.rs

1// Copyright 2023 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::borrow::Cow;
16use std::cmp::{max, min};
17use std::collections::HashMap;
18use std::ops::Bound;
19
20use await_tree::InstrumentAwait;
21use futures::Stream;
22use futures::future::try_join_all;
23use futures_async_stream::try_stream;
24use risingwave_common::array::stream_record::Record;
25use risingwave_common::array::{DataChunk, Op, StreamChunk};
26use risingwave_common::bail;
27use risingwave_common::bitmap::BitmapBuilder;
28use risingwave_common::hash::{VirtualNode, VnodeBitmapExt};
29use risingwave_common::row::{OwnedRow, Row, RowExt};
30use risingwave_common::types::{DataType, Datum};
31use risingwave_common::util::chunk_coalesce::DataChunkBuilder;
32use risingwave_common::util::epoch::EpochPair;
33use risingwave_common::util::iter_util::ZipEqDebug;
34use risingwave_common::util::sort_util::{OrderType, cmp_datum_iter};
35use risingwave_common::util::value_encoding::BasicSerde;
36use risingwave_common_rate_limit::RateLimit;
37use risingwave_connector::error::ConnectorError;
38use risingwave_connector::source::cdc::external::{CdcOffset, CdcOffsetParseFunc};
39use risingwave_storage::StateStore;
40use risingwave_storage::row_serde::value_serde::ValueRowSerde;
41use risingwave_storage::table::collect_data_chunk_with_builder;
42
43use crate::common::table::state_table::{ReplicatedStateTable, StateTableInner};
44use crate::executor::{Message, StreamExecutorError, StreamExecutorResult, Watermark};
45
46/// `vnode`, `is_finished`, `row_count`, all occupy 1 column each.
47pub const METADATA_STATE_LEN: usize = 3;
48
49#[derive(Clone, Debug)]
50pub struct BackfillState {
51    /// Used to track backfill progress.
52    // TODO: Instead of using hashmap, perhaps we can just use static array.
53    inner: HashMap<VirtualNode, BackfillStatePerVnode>,
54}
55
56impl BackfillState {
57    pub(crate) fn has_progress(&self) -> bool {
58        self.inner.values().any(|p| {
59            matches!(
60                p.current_state(),
61                &BackfillProgressPerVnode::InProgress { .. }
62            )
63        })
64    }
65
66    pub(crate) fn get_current_state(
67        &mut self,
68        vnode: &VirtualNode,
69    ) -> &mut BackfillProgressPerVnode {
70        &mut self.inner.get_mut(vnode).unwrap().current_state
71    }
72
73    // Expects the vnode to always have progress, otherwise it will return an error.
74    pub(crate) fn get_progress(
75        &self,
76        vnode: &VirtualNode,
77    ) -> StreamExecutorResult<&BackfillProgressPerVnode> {
78        match self.inner.get(vnode) {
79            Some(p) => Ok(p.current_state()),
80            None => bail!(
81                "Backfill progress for vnode {:#?} not found, backfill_state not initialized properly",
82                vnode,
83            ),
84        }
85    }
86
87    pub(crate) fn update_progress(
88        &mut self,
89        vnode: VirtualNode,
90        new_pos: OwnedRow,
91        snapshot_row_count_delta: u64,
92    ) -> StreamExecutorResult<()> {
93        let state = self.get_current_state(&vnode);
94        match state {
95            BackfillProgressPerVnode::NotStarted => {
96                *state = BackfillProgressPerVnode::InProgress {
97                    current_pos: new_pos,
98                    snapshot_row_count: snapshot_row_count_delta,
99                };
100            }
101            BackfillProgressPerVnode::InProgress {
102                snapshot_row_count, ..
103            } => {
104                *state = BackfillProgressPerVnode::InProgress {
105                    current_pos: new_pos,
106                    snapshot_row_count: *snapshot_row_count + snapshot_row_count_delta,
107                };
108            }
109            BackfillProgressPerVnode::Completed { .. } => unreachable!(),
110        }
111        Ok(())
112    }
113
114    pub(crate) fn finish_progress(&mut self, vnode: VirtualNode, pos_len: usize) {
115        let finished_placeholder_position = construct_initial_finished_state(pos_len);
116        let current_state = self.get_current_state(&vnode);
117        let (new_pos, snapshot_row_count) = match current_state {
118            BackfillProgressPerVnode::NotStarted => (finished_placeholder_position, 0),
119            BackfillProgressPerVnode::InProgress {
120                current_pos,
121                snapshot_row_count,
122            } => (current_pos.clone(), *snapshot_row_count),
123            BackfillProgressPerVnode::Completed { .. } => {
124                return;
125            }
126        };
127        *current_state = BackfillProgressPerVnode::Completed {
128            current_pos: new_pos,
129            snapshot_row_count,
130        };
131    }
132
133    /// Return state to be committed.
134    fn get_commit_state(&self, vnode: &VirtualNode) -> Option<(Option<Vec<Datum>>, Vec<Datum>)> {
135        let new_state = self.inner.get(vnode).unwrap().current_state().clone();
136        let new_encoded_state = match new_state {
137            BackfillProgressPerVnode::NotStarted => unreachable!(),
138            BackfillProgressPerVnode::InProgress {
139                current_pos,
140                snapshot_row_count,
141            } => {
142                let mut encoded_state = vec![None; current_pos.len() + METADATA_STATE_LEN];
143                encoded_state[0] = Some(vnode.to_scalar().into());
144                encoded_state[1..current_pos.len() + 1].clone_from_slice(current_pos.as_inner());
145                encoded_state[current_pos.len() + 1] = Some(false.into());
146                encoded_state[current_pos.len() + 2] = Some((snapshot_row_count as i64).into());
147                encoded_state
148            }
149            BackfillProgressPerVnode::Completed {
150                current_pos,
151                snapshot_row_count,
152            } => {
153                let mut encoded_state = vec![None; current_pos.len() + METADATA_STATE_LEN];
154                encoded_state[0] = Some(vnode.to_scalar().into());
155                encoded_state[1..current_pos.len() + 1].clone_from_slice(current_pos.as_inner());
156                encoded_state[current_pos.len() + 1] = Some(true.into());
157                encoded_state[current_pos.len() + 2] = Some((snapshot_row_count as i64).into());
158                encoded_state
159            }
160        };
161        let old_state = self.inner.get(vnode).unwrap().committed_state().clone();
162        let old_encoded_state = match old_state {
163            BackfillProgressPerVnode::NotStarted => None,
164            BackfillProgressPerVnode::InProgress {
165                current_pos,
166                snapshot_row_count,
167            } => {
168                let committed_pos = current_pos;
169                let mut encoded_state = vec![None; committed_pos.len() + METADATA_STATE_LEN];
170                encoded_state[0] = Some(vnode.to_scalar().into());
171                encoded_state[1..committed_pos.len() + 1]
172                    .clone_from_slice(committed_pos.as_inner());
173                encoded_state[committed_pos.len() + 1] = Some(false.into());
174                encoded_state[committed_pos.len() + 2] = Some((snapshot_row_count as i64).into());
175                Some(encoded_state)
176            }
177            BackfillProgressPerVnode::Completed {
178                current_pos,
179                snapshot_row_count,
180            } => {
181                let committed_pos = current_pos;
182                let mut encoded_state = vec![None; committed_pos.len() + METADATA_STATE_LEN];
183                encoded_state[0] = Some(vnode.to_scalar().into());
184                encoded_state[1..committed_pos.len() + 1]
185                    .clone_from_slice(committed_pos.as_inner());
186                encoded_state[committed_pos.len() + 1] = Some(true.into());
187                encoded_state[committed_pos.len() + 2] = Some((snapshot_row_count as i64).into());
188                Some(encoded_state)
189            }
190        };
191        Some((old_encoded_state, new_encoded_state))
192    }
193
194    // TODO: We can add a committed flag to speed up this check.
195    /// Checks if the state needs to be committed.
196    fn need_commit(&self, vnode: &VirtualNode) -> bool {
197        let state = self.inner.get(vnode).unwrap();
198        match state.current_state() {
199            // If current state and committed state are the same, we don't need to commit.
200            s @ BackfillProgressPerVnode::InProgress { .. }
201            | s @ BackfillProgressPerVnode::Completed { .. } => s != state.committed_state(),
202            BackfillProgressPerVnode::NotStarted => false,
203        }
204    }
205
206    fn mark_committed(&mut self, vnode: VirtualNode) {
207        let BackfillStatePerVnode {
208            committed_state,
209            current_state,
210        } = self.inner.get_mut(&vnode).unwrap();
211
212        assert!(matches!(
213            current_state,
214            BackfillProgressPerVnode::InProgress { .. }
215                | BackfillProgressPerVnode::Completed { .. }
216        ));
217        *committed_state = current_state.clone();
218    }
219
220    pub(crate) fn get_snapshot_row_count(&self) -> u64 {
221        self.inner
222            .values()
223            .map(|p| p.get_snapshot_row_count())
224            .sum()
225    }
226}
227
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub struct BackfillStatePerVnode {
230    committed_state: BackfillProgressPerVnode,
231    current_state: BackfillProgressPerVnode,
232}
233
234impl BackfillStatePerVnode {
235    pub(crate) fn new(
236        committed_state: BackfillProgressPerVnode,
237        current_state: BackfillProgressPerVnode,
238    ) -> Self {
239        Self {
240            committed_state,
241            current_state,
242        }
243    }
244
245    pub(crate) fn committed_state(&self) -> &BackfillProgressPerVnode {
246        &self.committed_state
247    }
248
249    pub(crate) fn current_state(&self) -> &BackfillProgressPerVnode {
250        &self.current_state
251    }
252
253    pub(crate) fn get_snapshot_row_count(&self) -> u64 {
254        self.current_state().get_snapshot_row_count()
255    }
256}
257
258impl From<Vec<(VirtualNode, BackfillStatePerVnode)>> for BackfillState {
259    fn from(v: Vec<(VirtualNode, BackfillStatePerVnode)>) -> Self {
260        Self {
261            inner: v.into_iter().collect(),
262        }
263    }
264}
265
266/// Used for tracking backfill state per vnode
267/// The `OwnedRow` only contains the pk of upstream, to track `current_pos`.
268#[derive(Clone, Eq, PartialEq, Debug)]
269pub enum BackfillProgressPerVnode {
270    /// no entry exists for a vnode, or on initialization of the executor.
271    NotStarted,
272    InProgress {
273        /// The current snapshot offset
274        current_pos: OwnedRow,
275        /// Number of snapshot records read for this vnode.
276        snapshot_row_count: u64,
277    },
278    Completed {
279        /// The current snapshot offset
280        current_pos: OwnedRow,
281        /// Number of snapshot records read for this vnode.
282        snapshot_row_count: u64,
283    },
284}
285
286impl BackfillProgressPerVnode {
287    fn get_snapshot_row_count(&self) -> u64 {
288        match self {
289            BackfillProgressPerVnode::NotStarted => 0,
290            BackfillProgressPerVnode::InProgress {
291                snapshot_row_count, ..
292            }
293            | BackfillProgressPerVnode::Completed {
294                snapshot_row_count, ..
295            } => *snapshot_row_count,
296        }
297    }
298}
299
300pub(crate) fn mark_cdc_chunk(
301    offset_parse_func: &CdcOffsetParseFunc,
302    chunk: StreamChunk,
303    current_pos: &OwnedRow,
304    pk_in_output_indices: &[usize],
305    pk_order: &[OrderType],
306    last_cdc_offset: Option<CdcOffset>,
307) -> StreamExecutorResult<StreamChunk> {
308    let chunk = chunk.compact_vis();
309    mark_cdc_chunk_inner(
310        offset_parse_func,
311        chunk,
312        current_pos,
313        last_cdc_offset,
314        pk_in_output_indices,
315        pk_order,
316    )
317}
318
319/// Mark chunk:
320/// For each row of the chunk, forward it to downstream if its pk <= `current_pos` for the
321/// corresponding `vnode`, otherwise ignore it.
322/// We implement it by changing the visibility bitmap.
323pub(crate) fn mark_chunk_ref_by_vnode<S: StateStore, SD: ValueRowSerde>(
324    chunk: &StreamChunk,
325    backfill_state: &BackfillState,
326    pk_in_output_indices: &[usize],
327    upstream_table: &ReplicatedStateTable<S, SD>,
328    pk_order: &[OrderType],
329) -> StreamExecutorResult<StreamChunk> {
330    let chunk = chunk.clone();
331    let (data, ops) = chunk.into_parts();
332    let mut new_visibility = BitmapBuilder::with_capacity(ops.len());
333
334    let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
335    let mut unmatched_update_delete = false;
336    let mut visible_update_delete = false;
337    for (i, (op, row)) in ops.iter().zip_eq_debug(data.rows()).enumerate() {
338        let pk = row.project(pk_in_output_indices);
339        let vnode = upstream_table.compute_vnode_by_pk(pk);
340        let visible = match backfill_state.get_progress(&vnode)? {
341            // We want to just forward the row, if the vnode has finished backfill.
342            BackfillProgressPerVnode::Completed { .. } => true,
343            // If not started, no need to forward.
344            BackfillProgressPerVnode::NotStarted => false,
345            // If in progress, we need to check row <= current_pos.
346            BackfillProgressPerVnode::InProgress { current_pos, .. } => {
347                cmp_datum_iter(pk.iter(), current_pos.iter(), pk_order.iter().copied()).is_le()
348            }
349        };
350        if !visible {
351            tracing::trace!(
352                source = "upstream",
353                state = "process_barrier",
354                action = "mark_chunk",
355                ?vnode,
356                ?op,
357                ?pk,
358                ?row,
359                "update_filtered",
360            );
361        }
362        new_visibility.append(visible);
363
364        normalize_unmatched_updates(
365            &mut new_ops,
366            &mut unmatched_update_delete,
367            &mut visible_update_delete,
368            visible,
369            i,
370            op,
371        );
372    }
373    let (columns, _) = data.into_parts();
374    let chunk = StreamChunk::with_visibility(new_ops, columns, new_visibility.finish());
375    Ok(chunk)
376}
377
378/// We will rewrite unmatched U-/U+ into +/- ops.
379/// They can be unmatched because while they will always have the same stream key,
380/// their storage pk might be different. Here we use storage pk (`current_pos`) to filter them,
381/// as such, a U+ might be filtered out, but their corresponding U- could be kept, and vice versa.
382///
383/// This hanging U-/U+ can lead to issues downstream, since we work with an assumption in the
384/// system that there's never hanging U-/U+.
385fn normalize_unmatched_updates(
386    normalized_ops: &mut Cow<'_, [Op]>,
387    unmatched_update_delete: &mut bool,
388    visible_update_delete: &mut bool,
389    current_visibility: bool,
390    current_op_index: usize,
391    current_op: &Op,
392) {
393    if *unmatched_update_delete {
394        assert_eq!(*current_op, Op::UpdateInsert);
395        let visible_update_insert = current_visibility;
396        match (visible_update_delete, visible_update_insert) {
397            (true, false) => {
398                // Lazily clone the ops here.
399                let ops = normalized_ops.to_mut();
400                ops[current_op_index - 1] = Op::Delete;
401            }
402            (false, true) => {
403                // Lazily clone the ops here.
404                let ops = normalized_ops.to_mut();
405                ops[current_op_index] = Op::Insert;
406            }
407            (true, true) | (false, false) => {}
408        }
409        *unmatched_update_delete = false;
410    } else {
411        match current_op {
412            Op::UpdateDelete => {
413                *unmatched_update_delete = true;
414                *visible_update_delete = current_visibility;
415            }
416            Op::UpdateInsert => {
417                unreachable!("UpdateInsert should not be present without UpdateDelete")
418            }
419            _ => {}
420        }
421    }
422}
423
424fn mark_cdc_chunk_inner(
425    offset_parse_func: &CdcOffsetParseFunc,
426    chunk: StreamChunk,
427    current_pos: &OwnedRow,
428    last_cdc_offset: Option<CdcOffset>,
429    pk_in_output_indices: &[usize],
430    pk_order: &[OrderType],
431) -> StreamExecutorResult<StreamChunk> {
432    let (data, ops) = chunk.into_parts();
433    let mut new_visibility = BitmapBuilder::with_capacity(ops.len());
434
435    // `_rw_offset` must be placed at the last column right now
436    let offset_col_idx = data.dimension() - 1;
437    for v in data.rows().map(|row| {
438        let offset_datum = row.datum_at(offset_col_idx).unwrap();
439        let event_offset = (*offset_parse_func)(offset_datum.into_utf8())?;
440        let visible = {
441            // filter changelog events with binlog range
442            let in_binlog_range = if let Some(binlog_low) = &last_cdc_offset {
443                binlog_low <= &event_offset
444            } else {
445                true
446            };
447
448            if in_binlog_range {
449                let lhs = row.project(pk_in_output_indices);
450                let rhs = current_pos;
451                cmp_datum_iter(lhs.iter(), rhs.iter(), pk_order.iter().copied()).is_le()
452            } else {
453                false
454            }
455        };
456        Ok::<_, ConnectorError>(visible)
457    }) {
458        new_visibility.append(v?);
459    }
460
461    let (columns, _) = data.into_parts();
462    Ok(StreamChunk::with_visibility(
463        ops,
464        columns,
465        new_visibility.finish(),
466    ))
467}
468
469/// Builds a new stream chunk with `output_indices`.
470pub(crate) fn mapping_chunk(chunk: StreamChunk, output_indices: &[usize]) -> StreamChunk {
471    let (ops, columns, visibility) = chunk.into_inner();
472    let mapped_columns = output_indices.iter().map(|&i| columns[i].clone()).collect();
473    StreamChunk::with_visibility(ops, mapped_columns, visibility)
474}
475
476fn mapping_watermark(watermark: Watermark, upstream_indices: &[usize]) -> Option<Watermark> {
477    watermark.transform_with_indices(upstream_indices)
478}
479
480pub(crate) fn mapping_message(msg: Message, upstream_indices: &[usize]) -> Option<Message> {
481    match msg {
482        Message::Barrier(_) => Some(msg),
483        Message::Watermark(watermark) => {
484            mapping_watermark(watermark, upstream_indices).map(Message::Watermark)
485        }
486        Message::Chunk(chunk) => Some(Message::Chunk(mapping_chunk(chunk, upstream_indices))),
487    }
488}
489
490fn same_key_columns(lhs: &[usize], rhs: &[usize]) -> bool {
491    lhs.len() == rhs.len() && lhs.iter().all(|idx| rhs.contains(idx))
492}
493
494/// Rewrites upstream updates when the input stream key is not the same column
495/// set as the current executor stream key.
496///
497/// If an upstream update keeps the input stream key unchanged but changes the
498/// current executor stream key, downstream state keyed by the current stream key
499/// must see it as a delete followed by an insert.
500pub(super) struct UpstreamStreamKeyUpdateNormalizer {
501    current_stream_key_indices: Option<Vec<usize>>,
502}
503
504impl UpstreamStreamKeyUpdateNormalizer {
505    /// Creates a normalizer for chunks with the given schema.
506    ///
507    /// `input_stream_key_indices` are the stream-key column indices of the input
508    /// executor in the incoming chunk schema.
509    ///
510    /// `current_stream_key_indices` are the stream-key column indices of the
511    /// current executor in the same incoming chunk schema.
512    ///
513    /// For example, if an upstream MV has input stream key `[k]` but the current
514    /// executor stream key is `[k, ts]`, then an update from
515    /// `(k = 1, ts = 10)` to `(k = 1, ts = 20)` is rewritten as
516    /// `Delete(k = 1, ts = 10)` plus `Insert(k = 1, ts = 20)`. If the two stream
517    /// keys are the same column set, or if an update does not change current
518    /// stream-key values, it is left unchanged.
519    pub(super) fn new(
520        input_stream_key_indices: &[usize],
521        current_stream_key_indices: Vec<usize>,
522    ) -> Self {
523        let current_stream_key_indices =
524            (!same_key_columns(input_stream_key_indices, &current_stream_key_indices))
525                .then_some(current_stream_key_indices);
526        Self {
527            current_stream_key_indices,
528        }
529    }
530
531    pub(super) fn normalize_chunk(&self, chunk: StreamChunk) -> Option<StreamChunk> {
532        if let Some(current_stream_key_indices) = &self.current_stream_key_indices {
533            normalize_update_chunk_by_key(chunk, current_stream_key_indices)
534        } else {
535            Some(chunk)
536        }
537    }
538
539    pub(super) fn normalize_message(&self, msg: Message) -> Option<Message> {
540        match msg {
541            Message::Chunk(chunk) => self.normalize_chunk(chunk).map(Message::Chunk),
542            msg => Some(msg),
543        }
544    }
545}
546
547fn normalize_update_chunk_by_key(chunk: StreamChunk, key_indices: &[usize]) -> Option<StreamChunk> {
548    let (data_chunk, ops) = chunk.into_parts();
549    let mut update_indices = vec![];
550    let mut row_idx = data_chunk.next_visible_row_idx(0);
551    while let Some(idx) = row_idx {
552        let row = data_chunk.row_at_unchecked_vis(idx);
553        match ops[idx] {
554            Op::UpdateDelete => {
555                let next_idx = data_chunk
556                    .next_visible_row_idx(idx + 1)
557                    .unwrap_or_else(|| panic!("expect a U+ after U-\nU- row: {}", row.display()));
558                let next_row = data_chunk.row_at_unchecked_vis(next_idx);
559                debug_assert_eq!(
560                    ops[next_idx],
561                    Op::UpdateInsert,
562                    "expect a U+ after U-\nU- row: {}\nrow after U-: {}",
563                    row.display(),
564                    next_row.display()
565                );
566                if row.project(key_indices) != next_row.project(key_indices) {
567                    update_indices.push((idx, next_idx));
568                }
569                row_idx = data_chunk.next_visible_row_idx(next_idx + 1);
570            }
571            Op::UpdateInsert => panic!("expect a U- before U+\nU+ row: {}", row.display()),
572            Op::Insert | Op::Delete => {
573                row_idx = data_chunk.next_visible_row_idx(idx + 1);
574            }
575        }
576    }
577
578    if update_indices.is_empty() {
579        return Some(StreamChunk::from_parts(ops, data_chunk));
580    }
581
582    let (columns, visibility) = data_chunk.into_parts();
583    let mut ops = ops.to_vec();
584    for (delete_idx, insert_idx) in update_indices {
585        ops[delete_idx] = Op::Delete;
586        ops[insert_idx] = Op::Insert;
587    }
588    Some(StreamChunk::from_parts(
589        ops,
590        DataChunk::new(columns, visibility),
591    ))
592}
593
594/// Recovers progress per vnode, so we know which to backfill.
595/// See how it decodes the state with the inline comments.
596pub(crate) async fn get_progress_per_vnode<S: StateStore, const IS_REPLICATED: bool>(
597    state_table: &StateTableInner<S, BasicSerde, IS_REPLICATED>,
598) -> StreamExecutorResult<Vec<(VirtualNode, BackfillStatePerVnode)>> {
599    debug_assert!(!state_table.vnodes().is_empty());
600    let vnodes = state_table.vnodes().iter_vnodes();
601    let mut result = Vec::with_capacity(state_table.vnodes().len());
602    // 1. Get the vnode keys, so we can get the state per vnode.
603    let vnode_keys = vnodes.map(|vnode| {
604        let datum: [Datum; 1] = [Some(vnode.to_scalar().into())];
605        datum
606    });
607    let tasks = vnode_keys.map(|vnode_key| state_table.get_row(vnode_key));
608    // 2. Fetch the state for each vnode.
609    //    It should have the following schema, it should not contain vnode:
610    //    | pk | `backfill_finished` | `row_count` |
611    let state_for_vnodes = try_join_all(tasks).await?;
612    for (vnode, state_for_vnode) in state_table
613        .vnodes()
614        .iter_vnodes()
615        .zip_eq_debug(state_for_vnodes)
616    {
617        let backfill_progress = match state_for_vnode {
618            // There's some state, means there was progress made. It's either finished / in progress.
619            Some(row) => {
620                // 3. Decode the `snapshot_row_count`. Decode from the back, since
621                //    pk is variable length.
622                let snapshot_row_count = row.as_inner().get(row.len() - 1).unwrap();
623                let snapshot_row_count = (*snapshot_row_count.as_ref().unwrap().as_int64()) as u64;
624
625                // 4. Decode the `is_finished` flag (whether backfill has finished).
626                //    Decode from the back, since pk is variable length.
627                let vnode_is_finished = row.as_inner().get(row.len() - 2).unwrap();
628                let vnode_is_finished = vnode_is_finished.as_ref().unwrap();
629
630                // 5. Decode the `current_pos`.
631                let current_pos = row.as_inner().get(..row.len() - 2).unwrap();
632                let current_pos = current_pos.into_owned_row();
633
634                // 6. Construct the in-memory state per vnode, based on the decoded state.
635                if *vnode_is_finished.as_bool() {
636                    BackfillStatePerVnode::new(
637                        BackfillProgressPerVnode::Completed {
638                            current_pos: current_pos.clone(),
639                            snapshot_row_count,
640                        },
641                        BackfillProgressPerVnode::Completed {
642                            current_pos,
643                            snapshot_row_count,
644                        },
645                    )
646                } else {
647                    BackfillStatePerVnode::new(
648                        BackfillProgressPerVnode::InProgress {
649                            current_pos: current_pos.clone(),
650                            snapshot_row_count,
651                        },
652                        BackfillProgressPerVnode::InProgress {
653                            current_pos,
654                            snapshot_row_count,
655                        },
656                    )
657                }
658            }
659            // No state, means no progress made.
660            None => BackfillStatePerVnode::new(
661                BackfillProgressPerVnode::NotStarted,
662                BackfillProgressPerVnode::NotStarted,
663            ),
664        };
665        result.push((vnode, backfill_progress));
666    }
667    assert_eq!(result.len(), state_table.vnodes().count_ones());
668    Ok(result)
669}
670
671/// Update backfill pos by vnode.
672pub(crate) fn update_pos_by_vnode(
673    vnode: VirtualNode,
674    chunk: &StreamChunk,
675    pk_in_output_indices: &[usize],
676    backfill_state: &mut BackfillState,
677    snapshot_row_count_delta: u64,
678) -> StreamExecutorResult<()> {
679    let new_pos = get_new_pos(chunk, pk_in_output_indices);
680    assert_eq!(new_pos.len(), pk_in_output_indices.len());
681    backfill_state.update_progress(vnode, new_pos, snapshot_row_count_delta)?;
682    Ok(())
683}
684
685/// Get new backfill pos from the chunk. Since chunk should have ordered rows, we can just take the
686/// last row.
687pub(crate) fn get_new_pos(chunk: &StreamChunk, pk_in_output_indices: &[usize]) -> OwnedRow {
688    chunk
689        .rows()
690        .last()
691        .unwrap()
692        .1
693        .project(pk_in_output_indices)
694        .into_owned_row()
695}
696
697pub(crate) fn get_cdc_chunk_last_offset(
698    offset_parse_func: &CdcOffsetParseFunc,
699    chunk: &StreamChunk,
700) -> StreamExecutorResult<Option<CdcOffset>> {
701    let row = chunk.rows().last().unwrap().1;
702    let offset_col = row.iter().last().unwrap();
703    let output =
704        offset_col.map(|scalar| Ok::<_, ConnectorError>((*offset_parse_func)(scalar.into_utf8()))?);
705    output.transpose().map_err(|e| e.into())
706}
707
708// NOTE(kwannoel): ["None" ..] encoding should be appropriate to mark
709// the case where upstream snapshot is empty.
710// This is so we can persist backfill state as "finished".
711// It won't be confused with another case where pk position comprised of nulls,
712// because they both record that backfill is finished.
713pub(crate) fn construct_initial_finished_state(pos_len: usize) -> OwnedRow {
714    OwnedRow::new(vec![None; pos_len])
715}
716
717pub(crate) fn compute_bounds(
718    pk_indices: &[usize],
719    current_pos: Option<OwnedRow>,
720) -> Option<(Bound<OwnedRow>, Bound<OwnedRow>)> {
721    // `current_pos` is None means it needs to scan from the beginning, so we use Unbounded to
722    // scan. Otherwise, use Excluded.
723    if let Some(current_pos) = current_pos {
724        // If `current_pos` is an empty row which means upstream mv contains only one row and it
725        // has been consumed. The iter interface doesn't support
726        // `Excluded(empty_row)` range bound, so we can simply return `None`.
727        if current_pos.is_empty() {
728            assert!(pk_indices.is_empty());
729            return None;
730        }
731
732        Some((Bound::Excluded(current_pos), Bound::Unbounded))
733    } else {
734        Some((Bound::Unbounded, Bound::Unbounded))
735    }
736}
737
738#[try_stream(ok = StreamChunk, error = StreamExecutorError)]
739pub(crate) async fn iter_chunks<'a, S, E, R>(mut iter: S, builder: &'a mut DataChunkBuilder)
740where
741    StreamExecutorError: From<E>,
742    R: Row,
743    S: Stream<Item = Result<R, E>> + Unpin + 'a,
744{
745    while let Some(data_chunk) = collect_data_chunk_with_builder(&mut iter, builder)
746        .instrument_await("backfill_snapshot_read")
747        .await?
748    {
749        debug_assert!(data_chunk.cardinality() > 0);
750        let ops = vec![Op::Insert; data_chunk.capacity()];
751        let stream_chunk = StreamChunk::from_parts(ops, data_chunk);
752        yield stream_chunk;
753    }
754}
755
756/// Schema
757/// | vnode | pk | `backfill_finished` | `row_count` |
758/// Persists the state per vnode based on `BackfillState`.
759/// We track the current committed state via `committed_progress`
760/// so we know whether we need to persist the state or not.
761///
762/// The state is encoded as follows:
763/// `NotStarted`:
764/// - Not persist to store at all.
765///
766/// `InProgress`:
767/// - Format: | vnode | pk | false | `row_count` |
768/// - If change in current pos: Persist.
769/// - No change in current pos: Do not persist.
770///
771/// Completed
772/// - Format: | vnode | pk | true | `row_count` |
773/// - If previous state is `InProgress` / `NotStarted`: Persist.
774/// - If previous state is Completed: Do not persist.
775///
776/// TODO(kwannoel): we should check committed state to be all `finished` in the tests.
777/// TODO(kwannoel): Instead of persisting state per vnode each time,
778/// we can optimize by persisting state for a subset of vnodes which were updated.
779pub(crate) async fn persist_state_per_vnode<S: StateStore, const IS_REPLICATED: bool>(
780    epoch: EpochPair,
781    table: &mut StateTableInner<S, BasicSerde, IS_REPLICATED>,
782    backfill_state: &mut BackfillState,
783    #[cfg(debug_assertions)] state_len: usize,
784    vnodes: impl Iterator<Item = VirtualNode>,
785) -> StreamExecutorResult<()> {
786    for vnode in vnodes {
787        if !backfill_state.need_commit(&vnode) {
788            continue;
789        }
790        let (encoded_prev_state, encoded_current_state) =
791            match backfill_state.get_commit_state(&vnode) {
792                Some((old_state, new_state)) => (old_state, new_state),
793                None => continue,
794            };
795        if let Some(encoded_prev_state) = encoded_prev_state {
796            // There's some progress, update the state.
797            #[cfg(debug_assertions)]
798            {
799                let pk: &[Datum; 1] = &[Some(vnode.to_scalar().into())];
800                // old_row only contains the value segment.
801                let old_row = table.get_row(pk).await?;
802                match old_row {
803                    Some(old_row) => {
804                        let inner = old_row.as_inner();
805                        // value segment (without vnode) should be used for comparison
806                        assert_eq!(inner, &encoded_prev_state[1..]);
807                        assert_ne!(inner, &encoded_current_state[1..]);
808                        assert_eq!(old_row.len(), state_len - 1);
809                        assert_eq!(encoded_current_state.len(), state_len);
810                    }
811                    None => {
812                        bail!("row {:#?} not found", pk);
813                    }
814                }
815            }
816            table.write_record(Record::Update {
817                old_row: &encoded_prev_state[..],
818                new_row: &encoded_current_state[..],
819            });
820        } else {
821            // No existing state, create a new entry.
822            #[cfg(debug_assertions)]
823            {
824                let pk: &[Datum; 1] = &[Some(vnode.to_scalar().into())];
825                let row = table.get_row(pk).await?;
826                assert!(row.is_none(), "row {:#?}", row);
827                assert_eq!(encoded_current_state.len(), state_len);
828            }
829            table.write_record(Record::Insert {
830                new_row: &encoded_current_state[..],
831            });
832        }
833        backfill_state.mark_committed(vnode);
834    }
835
836    table.commit_assert_no_update_vnode_bitmap(epoch).await?;
837    Ok(())
838}
839
840/// Creates a data chunk builder for snapshot read.
841/// If the `rate_limit` is smaller than `chunk_size`, it will take precedence.
842/// This is so we can partition snapshot read into smaller chunks than chunk size.
843pub fn create_builder(
844    rate_limit: RateLimit,
845    chunk_size: usize,
846    data_types: Vec<DataType>,
847) -> DataChunkBuilder {
848    let batch_size = match rate_limit {
849        RateLimit::Disabled | RateLimit::Pause => chunk_size,
850        RateLimit::Fixed(limit) => min(limit.get() as usize, chunk_size),
851    };
852    // Ensure that the batch size is at least 2, to have enough space for two rows in a single update.
853    let batch_size = max(2, batch_size);
854    DataChunkBuilder::new(data_types, batch_size)
855}
856
857#[cfg(test)]
858mod tests {
859    use std::sync::Arc;
860
861    use super::*;
862
863    #[test]
864    fn test_normalizing_unmatched_updates() {
865        let ops = vec![
866            Op::UpdateDelete,
867            Op::UpdateInsert,
868            Op::UpdateDelete,
869            Op::UpdateInsert,
870        ];
871        let ops: Arc<[Op]> = ops.into();
872
873        {
874            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
875            let mut unmatched_update_delete = true;
876            let mut visible_update_delete = true;
877            let current_visibility = true;
878            normalize_unmatched_updates(
879                &mut new_ops,
880                &mut unmatched_update_delete,
881                &mut visible_update_delete,
882                current_visibility,
883                1,
884                &Op::UpdateInsert,
885            );
886            assert_eq!(
887                &new_ops[..],
888                vec![
889                    Op::UpdateDelete,
890                    Op::UpdateInsert,
891                    Op::UpdateDelete,
892                    Op::UpdateInsert
893                ]
894            );
895        }
896        {
897            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
898            let mut unmatched_update_delete = true;
899            let mut visible_update_delete = false;
900            let current_visibility = false;
901            normalize_unmatched_updates(
902                &mut new_ops,
903                &mut unmatched_update_delete,
904                &mut visible_update_delete,
905                current_visibility,
906                1,
907                &Op::UpdateInsert,
908            );
909            assert_eq!(
910                &new_ops[..],
911                vec![
912                    Op::UpdateDelete,
913                    Op::UpdateInsert,
914                    Op::UpdateDelete,
915                    Op::UpdateInsert
916                ]
917            );
918        }
919        {
920            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
921            let mut unmatched_update_delete = true;
922            let mut visible_update_delete = true;
923            let current_visibility = false;
924            normalize_unmatched_updates(
925                &mut new_ops,
926                &mut unmatched_update_delete,
927                &mut visible_update_delete,
928                current_visibility,
929                1,
930                &Op::UpdateInsert,
931            );
932            assert_eq!(
933                &new_ops[..],
934                vec![
935                    Op::Delete,
936                    Op::UpdateInsert,
937                    Op::UpdateDelete,
938                    Op::UpdateInsert
939                ]
940            );
941        }
942        {
943            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
944            let mut unmatched_update_delete = true;
945            let mut visible_update_delete = false;
946            let current_visibility = true;
947            normalize_unmatched_updates(
948                &mut new_ops,
949                &mut unmatched_update_delete,
950                &mut visible_update_delete,
951                current_visibility,
952                1,
953                &Op::UpdateInsert,
954            );
955            assert_eq!(
956                &new_ops[..],
957                vec![
958                    Op::UpdateDelete,
959                    Op::Insert,
960                    Op::UpdateDelete,
961                    Op::UpdateInsert
962                ]
963            );
964        }
965    }
966}