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::{Ordering, 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, DatumRef, ScalarRefImpl};
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, 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    pk_needs_unsigned_i64_compare: &[bool],
307    last_cdc_offset: Option<CdcOffset>,
308) -> StreamExecutorResult<StreamChunk> {
309    let chunk = chunk.compact_vis();
310    mark_cdc_chunk_inner(
311        offset_parse_func,
312        chunk,
313        current_pos,
314        last_cdc_offset,
315        pk_in_output_indices,
316        pk_order,
317        pk_needs_unsigned_i64_compare,
318    )
319}
320
321/// Compare two primary-key rows column by column, recovering the upstream unsigned order
322/// for `BIGINT UNSIGNED` pk columns.
323///
324/// `pk_needs_unsigned_i64_compare[i]` is true only for upstream `BIGINT UNSIGNED`. Frontend
325/// up-casts narrower unsigned integers so they stay non-negative in RisingWave, and unsigned
326/// float/double/decimal types must keep their native comparison semantics. Only `BIGINT UNSIGNED`
327/// can overflow into a negative `i64`, so we reinterpret both sides as `u64` to restore upstream
328/// MySQL ordering. The `ScalarRefImpl::Int64` match below is a defensive guard for that contract.
329pub(crate) fn cmp_pk_unsigned_aware<'a>(
330    lhs: impl Iterator<Item = DatumRef<'a>>,
331    rhs: impl Iterator<Item = DatumRef<'a>>,
332    pk_order: &[OrderType],
333    pk_needs_unsigned_i64_compare: &[bool],
334) -> Ordering {
335    for (((l, r), order), &needs_unsigned_i64_compare) in lhs
336        .zip_eq_debug(rhs)
337        .zip_eq_debug(pk_order.iter())
338        .zip_eq_debug(pk_needs_unsigned_i64_compare.iter())
339    {
340        let ord = match (needs_unsigned_i64_compare, l, r) {
341            (true, Some(ScalarRefImpl::Int64(a)), Some(ScalarRefImpl::Int64(b))) => {
342                let ord = (a as u64).cmp(&(b as u64));
343                // Apply the column's sort direction, matching `cmp_datum`. CDC backfill always
344                // reads the snapshot ascending, so the descending branch is only for parity.
345                if order.is_descending() {
346                    ord.reverse()
347                } else {
348                    ord
349                }
350            }
351            // Signed column, NULL, up-cast unsigned integer, or non-integer unsigned column:
352            // the original comparison is already correct.
353            _ => cmp_datum(l, r, *order),
354        };
355        if ord != Ordering::Equal {
356            return ord;
357        }
358    }
359    Ordering::Equal
360}
361
362/// Mark chunk:
363/// For each row of the chunk, forward it to downstream if its pk <= `current_pos` for the
364/// corresponding `vnode`, otherwise ignore it.
365/// We implement it by changing the visibility bitmap.
366pub(crate) fn mark_chunk_ref_by_vnode<S: StateStore, SD: ValueRowSerde>(
367    chunk: &StreamChunk,
368    backfill_state: &BackfillState,
369    pk_in_output_indices: &[usize],
370    upstream_table: &ReplicatedStateTable<S, SD>,
371    pk_order: &[OrderType],
372) -> StreamExecutorResult<StreamChunk> {
373    let chunk = chunk.clone();
374    let (data, ops) = chunk.into_parts();
375    let mut new_visibility = BitmapBuilder::with_capacity(ops.len());
376
377    let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
378    let mut unmatched_update_delete = false;
379    let mut visible_update_delete = false;
380    for (i, (op, row)) in ops.iter().zip_eq_debug(data.rows()).enumerate() {
381        let pk = row.project(pk_in_output_indices);
382        let vnode = upstream_table.compute_vnode_by_pk(pk);
383        let visible = match backfill_state.get_progress(&vnode)? {
384            // We want to just forward the row, if the vnode has finished backfill.
385            BackfillProgressPerVnode::Completed { .. } => true,
386            // If not started, no need to forward.
387            BackfillProgressPerVnode::NotStarted => false,
388            // If in progress, we need to check row <= current_pos.
389            BackfillProgressPerVnode::InProgress { current_pos, .. } => {
390                cmp_datum_iter(pk.iter(), current_pos.iter(), pk_order.iter().copied()).is_le()
391            }
392        };
393        if !visible {
394            tracing::trace!(
395                source = "upstream",
396                state = "process_barrier",
397                action = "mark_chunk",
398                ?vnode,
399                ?op,
400                ?pk,
401                ?row,
402                "update_filtered",
403            );
404        }
405        new_visibility.append(visible);
406
407        normalize_unmatched_updates(
408            &mut new_ops,
409            &mut unmatched_update_delete,
410            &mut visible_update_delete,
411            visible,
412            i,
413            op,
414        );
415    }
416    let (columns, _) = data.into_parts();
417    let chunk = StreamChunk::with_visibility(new_ops, columns, new_visibility.finish());
418    Ok(chunk)
419}
420
421/// We will rewrite unmatched U-/U+ into +/- ops.
422/// They can be unmatched because while they will always have the same stream key,
423/// their storage pk might be different. Here we use storage pk (`current_pos`) to filter them,
424/// as such, a U+ might be filtered out, but their corresponding U- could be kept, and vice versa.
425///
426/// This hanging U-/U+ can lead to issues downstream, since we work with an assumption in the
427/// system that there's never hanging U-/U+.
428fn normalize_unmatched_updates(
429    normalized_ops: &mut Cow<'_, [Op]>,
430    unmatched_update_delete: &mut bool,
431    visible_update_delete: &mut bool,
432    current_visibility: bool,
433    current_op_index: usize,
434    current_op: &Op,
435) {
436    if *unmatched_update_delete {
437        assert_eq!(*current_op, Op::UpdateInsert);
438        let visible_update_insert = current_visibility;
439        match (visible_update_delete, visible_update_insert) {
440            (true, false) => {
441                // Lazily clone the ops here.
442                let ops = normalized_ops.to_mut();
443                ops[current_op_index - 1] = Op::Delete;
444            }
445            (false, true) => {
446                // Lazily clone the ops here.
447                let ops = normalized_ops.to_mut();
448                ops[current_op_index] = Op::Insert;
449            }
450            (true, true) | (false, false) => {}
451        }
452        *unmatched_update_delete = false;
453    } else {
454        match current_op {
455            Op::UpdateDelete => {
456                *unmatched_update_delete = true;
457                *visible_update_delete = current_visibility;
458            }
459            Op::UpdateInsert => {
460                unreachable!("UpdateInsert should not be present without UpdateDelete")
461            }
462            _ => {}
463        }
464    }
465}
466
467fn mark_cdc_chunk_inner(
468    offset_parse_func: &CdcOffsetParseFunc,
469    chunk: StreamChunk,
470    current_pos: &OwnedRow,
471    last_cdc_offset: Option<CdcOffset>,
472    pk_in_output_indices: &[usize],
473    pk_order: &[OrderType],
474    pk_needs_unsigned_i64_compare: &[bool],
475) -> StreamExecutorResult<StreamChunk> {
476    let (data, ops) = chunk.into_parts();
477    let mut new_visibility = BitmapBuilder::with_capacity(ops.len());
478
479    // `_rw_offset` must be placed at the last column right now
480    let offset_col_idx = data.dimension() - 1;
481    for v in data.rows().map(|row| {
482        let offset_datum = row.datum_at(offset_col_idx).unwrap();
483        let event_offset = (*offset_parse_func)(offset_datum.into_utf8())?;
484        let visible = {
485            // filter changelog events with binlog range
486            let in_binlog_range = if let Some(binlog_low) = &last_cdc_offset {
487                binlog_low <= &event_offset
488            } else {
489                true
490            };
491
492            if in_binlog_range {
493                let lhs = row.project(pk_in_output_indices);
494                let rhs = current_pos;
495                cmp_pk_unsigned_aware(
496                    lhs.iter(),
497                    rhs.iter(),
498                    pk_order,
499                    pk_needs_unsigned_i64_compare,
500                )
501                .is_le()
502            } else {
503                false
504            }
505        };
506        Ok::<_, ConnectorError>(visible)
507    }) {
508        new_visibility.append(v?);
509    }
510
511    let (columns, _) = data.into_parts();
512    Ok(StreamChunk::with_visibility(
513        ops,
514        columns,
515        new_visibility.finish(),
516    ))
517}
518
519/// Builds a new stream chunk with `output_indices`.
520pub(crate) fn mapping_chunk(chunk: StreamChunk, output_indices: &[usize]) -> StreamChunk {
521    let (ops, columns, visibility) = chunk.into_inner();
522    let mapped_columns = output_indices.iter().map(|&i| columns[i].clone()).collect();
523    StreamChunk::with_visibility(ops, mapped_columns, visibility)
524}
525
526fn mapping_watermark(watermark: Watermark, upstream_indices: &[usize]) -> Option<Watermark> {
527    watermark.transform_with_indices(upstream_indices)
528}
529
530pub(crate) fn mapping_message(msg: Message, upstream_indices: &[usize]) -> Option<Message> {
531    match msg {
532        Message::Barrier(_) => Some(msg),
533        Message::Watermark(watermark) => {
534            mapping_watermark(watermark, upstream_indices).map(Message::Watermark)
535        }
536        Message::Chunk(chunk) => Some(Message::Chunk(mapping_chunk(chunk, upstream_indices))),
537    }
538}
539
540fn same_key_columns(lhs: &[usize], rhs: &[usize]) -> bool {
541    lhs.len() == rhs.len() && lhs.iter().all(|idx| rhs.contains(idx))
542}
543
544/// Rewrites upstream updates when the input stream key is not the same column
545/// set as the current executor stream key.
546///
547/// If an upstream update keeps the input stream key unchanged but changes the
548/// current executor stream key, downstream state keyed by the current stream key
549/// must see it as a delete followed by an insert.
550pub(super) struct UpstreamStreamKeyUpdateNormalizer {
551    current_stream_key_indices: Option<Vec<usize>>,
552}
553
554impl UpstreamStreamKeyUpdateNormalizer {
555    /// Creates a normalizer for chunks with the given schema.
556    ///
557    /// `input_stream_key_indices` are the stream-key column indices of the input
558    /// executor in the incoming chunk schema.
559    ///
560    /// `current_stream_key_indices` are the stream-key column indices of the
561    /// current executor in the same incoming chunk schema.
562    ///
563    /// For example, if an upstream MV has input stream key `[k]` but the current
564    /// executor stream key is `[k, ts]`, then an update from
565    /// `(k = 1, ts = 10)` to `(k = 1, ts = 20)` is rewritten as
566    /// `Delete(k = 1, ts = 10)` plus `Insert(k = 1, ts = 20)`. If the two stream
567    /// keys are the same column set, or if an update does not change current
568    /// stream-key values, it is left unchanged.
569    pub(super) fn new(
570        input_stream_key_indices: &[usize],
571        current_stream_key_indices: Vec<usize>,
572    ) -> Self {
573        let current_stream_key_indices =
574            (!same_key_columns(input_stream_key_indices, &current_stream_key_indices))
575                .then_some(current_stream_key_indices);
576        Self {
577            current_stream_key_indices,
578        }
579    }
580
581    pub(super) fn normalize_chunk(&self, chunk: StreamChunk) -> Option<StreamChunk> {
582        if let Some(current_stream_key_indices) = &self.current_stream_key_indices {
583            normalize_update_chunk_by_key(chunk, current_stream_key_indices)
584        } else {
585            Some(chunk)
586        }
587    }
588
589    pub(super) fn normalize_message(&self, msg: Message) -> Option<Message> {
590        match msg {
591            Message::Chunk(chunk) => self.normalize_chunk(chunk).map(Message::Chunk),
592            msg => Some(msg),
593        }
594    }
595}
596
597fn normalize_update_chunk_by_key(chunk: StreamChunk, key_indices: &[usize]) -> Option<StreamChunk> {
598    let (data_chunk, ops) = chunk.into_parts();
599    let mut update_indices = vec![];
600    let mut row_idx = data_chunk.next_visible_row_idx(0);
601    while let Some(idx) = row_idx {
602        let row = data_chunk.row_at_unchecked_vis(idx);
603        match ops[idx] {
604            Op::UpdateDelete => {
605                let next_idx = data_chunk
606                    .next_visible_row_idx(idx + 1)
607                    .unwrap_or_else(|| panic!("expect a U+ after U-\nU- row: {}", row.display()));
608                let next_row = data_chunk.row_at_unchecked_vis(next_idx);
609                debug_assert_eq!(
610                    ops[next_idx],
611                    Op::UpdateInsert,
612                    "expect a U+ after U-\nU- row: {}\nrow after U-: {}",
613                    row.display(),
614                    next_row.display()
615                );
616                if row.project(key_indices) != next_row.project(key_indices) {
617                    update_indices.push((idx, next_idx));
618                }
619                row_idx = data_chunk.next_visible_row_idx(next_idx + 1);
620            }
621            Op::UpdateInsert => panic!("expect a U- before U+\nU+ row: {}", row.display()),
622            Op::Insert | Op::Delete => {
623                row_idx = data_chunk.next_visible_row_idx(idx + 1);
624            }
625        }
626    }
627
628    if update_indices.is_empty() {
629        return Some(StreamChunk::from_parts(ops, data_chunk));
630    }
631
632    let (columns, visibility) = data_chunk.into_parts();
633    let mut ops = ops.to_vec();
634    for (delete_idx, insert_idx) in update_indices {
635        ops[delete_idx] = Op::Delete;
636        ops[insert_idx] = Op::Insert;
637    }
638    Some(StreamChunk::from_parts(
639        ops,
640        DataChunk::new(columns, visibility),
641    ))
642}
643
644/// Recovers progress per vnode, so we know which to backfill.
645/// See how it decodes the state with the inline comments.
646pub(crate) async fn get_progress_per_vnode<S: StateStore, const IS_REPLICATED: bool>(
647    state_table: &StateTableInner<S, BasicSerde, IS_REPLICATED>,
648) -> StreamExecutorResult<Vec<(VirtualNode, BackfillStatePerVnode)>> {
649    debug_assert!(!state_table.vnodes().is_empty());
650    let vnodes = state_table.vnodes().iter_vnodes();
651    let mut result = Vec::with_capacity(state_table.vnodes().len());
652    // 1. Get the vnode keys, so we can get the state per vnode.
653    let vnode_keys = vnodes.map(|vnode| {
654        let datum: [Datum; 1] = [Some(vnode.to_scalar().into())];
655        datum
656    });
657    let tasks = vnode_keys.map(|vnode_key| state_table.get_row(vnode_key));
658    // 2. Fetch the state for each vnode.
659    //    It should have the following schema, it should not contain vnode:
660    //    | pk | `backfill_finished` | `row_count` |
661    let state_for_vnodes = try_join_all(tasks).await?;
662    for (vnode, state_for_vnode) in state_table
663        .vnodes()
664        .iter_vnodes()
665        .zip_eq_debug(state_for_vnodes)
666    {
667        let backfill_progress = match state_for_vnode {
668            // There's some state, means there was progress made. It's either finished / in progress.
669            Some(row) => {
670                // 3. Decode the `snapshot_row_count`. Decode from the back, since
671                //    pk is variable length.
672                let snapshot_row_count = row.as_inner().get(row.len() - 1).unwrap();
673                let snapshot_row_count = (*snapshot_row_count.as_ref().unwrap().as_int64()) as u64;
674
675                // 4. Decode the `is_finished` flag (whether backfill has finished).
676                //    Decode from the back, since pk is variable length.
677                let vnode_is_finished = row.as_inner().get(row.len() - 2).unwrap();
678                let vnode_is_finished = vnode_is_finished.as_ref().unwrap();
679
680                // 5. Decode the `current_pos`.
681                let current_pos = row.as_inner().get(..row.len() - 2).unwrap();
682                let current_pos = current_pos.into_owned_row();
683
684                // 6. Construct the in-memory state per vnode, based on the decoded state.
685                if *vnode_is_finished.as_bool() {
686                    BackfillStatePerVnode::new(
687                        BackfillProgressPerVnode::Completed {
688                            current_pos: current_pos.clone(),
689                            snapshot_row_count,
690                        },
691                        BackfillProgressPerVnode::Completed {
692                            current_pos,
693                            snapshot_row_count,
694                        },
695                    )
696                } else {
697                    BackfillStatePerVnode::new(
698                        BackfillProgressPerVnode::InProgress {
699                            current_pos: current_pos.clone(),
700                            snapshot_row_count,
701                        },
702                        BackfillProgressPerVnode::InProgress {
703                            current_pos,
704                            snapshot_row_count,
705                        },
706                    )
707                }
708            }
709            // No state, means no progress made.
710            None => BackfillStatePerVnode::new(
711                BackfillProgressPerVnode::NotStarted,
712                BackfillProgressPerVnode::NotStarted,
713            ),
714        };
715        result.push((vnode, backfill_progress));
716    }
717    assert_eq!(result.len(), state_table.vnodes().count_ones());
718    Ok(result)
719}
720
721/// Update backfill pos by vnode.
722pub(crate) fn update_pos_by_vnode(
723    vnode: VirtualNode,
724    chunk: &StreamChunk,
725    pk_in_output_indices: &[usize],
726    backfill_state: &mut BackfillState,
727    snapshot_row_count_delta: u64,
728) -> StreamExecutorResult<()> {
729    let new_pos = get_new_pos(chunk, pk_in_output_indices);
730    assert_eq!(new_pos.len(), pk_in_output_indices.len());
731    backfill_state.update_progress(vnode, new_pos, snapshot_row_count_delta)?;
732    Ok(())
733}
734
735/// Get new backfill pos from the chunk. Since chunk should have ordered rows, we can just take the
736/// last row.
737pub(crate) fn get_new_pos(chunk: &StreamChunk, pk_in_output_indices: &[usize]) -> OwnedRow {
738    chunk
739        .rows()
740        .last()
741        .unwrap()
742        .1
743        .project(pk_in_output_indices)
744        .into_owned_row()
745}
746
747pub(crate) fn get_cdc_chunk_last_offset(
748    offset_parse_func: &CdcOffsetParseFunc,
749    chunk: &StreamChunk,
750) -> StreamExecutorResult<Option<CdcOffset>> {
751    let row = chunk.rows().last().unwrap().1;
752    let offset_col = row.iter().last().unwrap();
753    let output =
754        offset_col.map(|scalar| Ok::<_, ConnectorError>((*offset_parse_func)(scalar.into_utf8()))?);
755    output.transpose().map_err(|e| e.into())
756}
757
758// NOTE(kwannoel): ["None" ..] encoding should be appropriate to mark
759// the case where upstream snapshot is empty.
760// This is so we can persist backfill state as "finished".
761// It won't be confused with another case where pk position comprised of nulls,
762// because they both record that backfill is finished.
763pub(crate) fn construct_initial_finished_state(pos_len: usize) -> OwnedRow {
764    OwnedRow::new(vec![None; pos_len])
765}
766
767pub(crate) fn compute_bounds(
768    pk_indices: &[usize],
769    current_pos: Option<OwnedRow>,
770) -> Option<(Bound<OwnedRow>, Bound<OwnedRow>)> {
771    // `current_pos` is None means it needs to scan from the beginning, so we use Unbounded to
772    // scan. Otherwise, use Excluded.
773    if let Some(current_pos) = current_pos {
774        // If `current_pos` is an empty row which means upstream mv contains only one row and it
775        // has been consumed. The iter interface doesn't support
776        // `Excluded(empty_row)` range bound, so we can simply return `None`.
777        if current_pos.is_empty() {
778            assert!(pk_indices.is_empty());
779            return None;
780        }
781
782        Some((Bound::Excluded(current_pos), Bound::Unbounded))
783    } else {
784        Some((Bound::Unbounded, Bound::Unbounded))
785    }
786}
787
788#[try_stream(ok = StreamChunk, error = StreamExecutorError)]
789pub(crate) async fn iter_chunks<'a, S, E, R>(mut iter: S, builder: &'a mut DataChunkBuilder)
790where
791    StreamExecutorError: From<E>,
792    R: Row,
793    S: Stream<Item = Result<R, E>> + Unpin + 'a,
794{
795    while let Some(data_chunk) = collect_data_chunk_with_builder(&mut iter, builder)
796        .instrument_await("backfill_snapshot_read")
797        .await?
798    {
799        debug_assert!(data_chunk.cardinality() > 0);
800        let ops = vec![Op::Insert; data_chunk.capacity()];
801        let stream_chunk = StreamChunk::from_parts(ops, data_chunk);
802        yield stream_chunk;
803    }
804}
805
806/// Schema
807/// | vnode | pk | `backfill_finished` | `row_count` |
808/// Persists the state per vnode based on `BackfillState`.
809/// We track the current committed state via `committed_progress`
810/// so we know whether we need to persist the state or not.
811///
812/// The state is encoded as follows:
813/// `NotStarted`:
814/// - Not persist to store at all.
815///
816/// `InProgress`:
817/// - Format: | vnode | pk | false | `row_count` |
818/// - If change in current pos: Persist.
819/// - No change in current pos: Do not persist.
820///
821/// Completed
822/// - Format: | vnode | pk | true | `row_count` |
823/// - If previous state is `InProgress` / `NotStarted`: Persist.
824/// - If previous state is Completed: Do not persist.
825///
826/// TODO(kwannoel): we should check committed state to be all `finished` in the tests.
827/// TODO(kwannoel): Instead of persisting state per vnode each time,
828/// we can optimize by persisting state for a subset of vnodes which were updated.
829pub(crate) async fn persist_state_per_vnode<S: StateStore, const IS_REPLICATED: bool>(
830    epoch: EpochPair,
831    table: &mut StateTableInner<S, BasicSerde, IS_REPLICATED>,
832    backfill_state: &mut BackfillState,
833    #[cfg(debug_assertions)] state_len: usize,
834    vnodes: impl Iterator<Item = VirtualNode>,
835) -> StreamExecutorResult<()> {
836    for vnode in vnodes {
837        if !backfill_state.need_commit(&vnode) {
838            continue;
839        }
840        let (encoded_prev_state, encoded_current_state) =
841            match backfill_state.get_commit_state(&vnode) {
842                Some((old_state, new_state)) => (old_state, new_state),
843                None => continue,
844            };
845        if let Some(encoded_prev_state) = encoded_prev_state {
846            // There's some progress, update the state.
847            #[cfg(debug_assertions)]
848            {
849                let pk: &[Datum; 1] = &[Some(vnode.to_scalar().into())];
850                // old_row only contains the value segment.
851                let old_row = table.get_row(pk).await?;
852                match old_row {
853                    Some(old_row) => {
854                        let inner = old_row.as_inner();
855                        // value segment (without vnode) should be used for comparison
856                        assert_eq!(inner, &encoded_prev_state[1..]);
857                        assert_ne!(inner, &encoded_current_state[1..]);
858                        assert_eq!(old_row.len(), state_len - 1);
859                        assert_eq!(encoded_current_state.len(), state_len);
860                    }
861                    None => {
862                        bail!("row {:#?} not found", pk);
863                    }
864                }
865            }
866            table.write_record(Record::Update {
867                old_row: &encoded_prev_state[..],
868                new_row: &encoded_current_state[..],
869            });
870        } else {
871            // No existing state, create a new entry.
872            #[cfg(debug_assertions)]
873            {
874                let pk: &[Datum; 1] = &[Some(vnode.to_scalar().into())];
875                let row = table.get_row(pk).await?;
876                assert!(row.is_none(), "row {:#?}", row);
877                assert_eq!(encoded_current_state.len(), state_len);
878            }
879            table.write_record(Record::Insert {
880                new_row: &encoded_current_state[..],
881            });
882        }
883        backfill_state.mark_committed(vnode);
884    }
885
886    table.commit_assert_no_update_vnode_bitmap(epoch).await?;
887    Ok(())
888}
889
890/// Creates a data chunk builder for snapshot read.
891/// If the `rate_limit` is smaller than `chunk_size`, it will take precedence.
892/// This is so we can partition snapshot read into smaller chunks than chunk size.
893pub fn create_builder(
894    rate_limit: RateLimit,
895    chunk_size: usize,
896    data_types: Vec<DataType>,
897) -> DataChunkBuilder {
898    let batch_size = match rate_limit {
899        RateLimit::Disabled | RateLimit::Pause => chunk_size,
900        RateLimit::Fixed(limit) => min(limit.get() as usize, chunk_size),
901    };
902    // Ensure that the batch size is at least 2, to have enough space for two rows in a single update.
903    let batch_size = max(2, batch_size);
904    DataChunkBuilder::new(data_types, batch_size)
905}
906
907#[cfg(test)]
908mod tests {
909    use std::sync::Arc;
910
911    use super::*;
912
913    #[test]
914    fn test_normalizing_unmatched_updates() {
915        let ops = vec![
916            Op::UpdateDelete,
917            Op::UpdateInsert,
918            Op::UpdateDelete,
919            Op::UpdateInsert,
920        ];
921        let ops: Arc<[Op]> = ops.into();
922
923        {
924            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
925            let mut unmatched_update_delete = true;
926            let mut visible_update_delete = true;
927            let current_visibility = true;
928            normalize_unmatched_updates(
929                &mut new_ops,
930                &mut unmatched_update_delete,
931                &mut visible_update_delete,
932                current_visibility,
933                1,
934                &Op::UpdateInsert,
935            );
936            assert_eq!(
937                &new_ops[..],
938                vec![
939                    Op::UpdateDelete,
940                    Op::UpdateInsert,
941                    Op::UpdateDelete,
942                    Op::UpdateInsert
943                ]
944            );
945        }
946        {
947            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
948            let mut unmatched_update_delete = true;
949            let mut visible_update_delete = false;
950            let current_visibility = false;
951            normalize_unmatched_updates(
952                &mut new_ops,
953                &mut unmatched_update_delete,
954                &mut visible_update_delete,
955                current_visibility,
956                1,
957                &Op::UpdateInsert,
958            );
959            assert_eq!(
960                &new_ops[..],
961                vec![
962                    Op::UpdateDelete,
963                    Op::UpdateInsert,
964                    Op::UpdateDelete,
965                    Op::UpdateInsert
966                ]
967            );
968        }
969        {
970            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
971            let mut unmatched_update_delete = true;
972            let mut visible_update_delete = true;
973            let current_visibility = false;
974            normalize_unmatched_updates(
975                &mut new_ops,
976                &mut unmatched_update_delete,
977                &mut visible_update_delete,
978                current_visibility,
979                1,
980                &Op::UpdateInsert,
981            );
982            assert_eq!(
983                &new_ops[..],
984                vec![
985                    Op::Delete,
986                    Op::UpdateInsert,
987                    Op::UpdateDelete,
988                    Op::UpdateInsert
989                ]
990            );
991        }
992        {
993            let mut new_ops: Cow<'_, [Op]> = Cow::Borrowed(ops.as_ref());
994            let mut unmatched_update_delete = true;
995            let mut visible_update_delete = false;
996            let current_visibility = true;
997            normalize_unmatched_updates(
998                &mut new_ops,
999                &mut unmatched_update_delete,
1000                &mut visible_update_delete,
1001                current_visibility,
1002                1,
1003                &Op::UpdateInsert,
1004            );
1005            assert_eq!(
1006                &new_ops[..],
1007                vec![
1008                    Op::UpdateDelete,
1009                    Op::Insert,
1010                    Op::UpdateDelete,
1011                    Op::UpdateInsert
1012                ]
1013            );
1014        }
1015    }
1016}