risingwave_stream/executor/backfill/cdc/
cdc_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::future::Future;
16use std::pin::Pin;
17
18use either::Either;
19use futures::stream;
20use futures::stream::select_with_strategy;
21use itertools::Itertools;
22use risingwave_common::array::DataChunk;
23use risingwave_common::bail;
24use risingwave_common::catalog::ColumnDesc;
25use risingwave_connector::parser::{
26    ByteStreamSourceParser, DebeziumParser, DebeziumProps, EncodingProperties, JsonProperties,
27    ProtocolProperties, SourceStreamChunkBuilder, SpecificParserConfig,
28};
29use risingwave_connector::source::cdc::external::{CdcOffset, ExternalTableReaderImpl};
30use risingwave_connector::source::{SourceColumnDesc, SourceContext, SourceCtrlOpts};
31use rw_futures_util::pausable;
32use thiserror_ext::AsReport;
33use tracing::Instrument;
34
35use crate::executor::UpdateMutation;
36use crate::executor::backfill::CdcScanOptions;
37use crate::executor::backfill::cdc::state::CdcBackfillState;
38use crate::executor::backfill::cdc::upstream_table::external::ExternalStorageTable;
39use crate::executor::backfill::cdc::upstream_table::snapshot::{
40    SnapshotReadArgs, UpstreamTableRead, UpstreamTableReader,
41};
42use crate::executor::backfill::utils::{
43    get_cdc_chunk_last_offset, get_new_pos, mapping_chunk, mapping_message, mark_cdc_chunk,
44};
45use crate::executor::monitor::CdcBackfillMetrics;
46use crate::executor::prelude::*;
47use crate::executor::source::get_infinite_backoff_strategy;
48use crate::task::CreateMviewProgressReporter;
49
50/// `split_id`, `is_finished`, `row_count`, `cdc_offset` all occupy 1 column each.
51const METADATA_STATE_LEN: usize = 4;
52
53pub struct CdcBackfillExecutor<S: StateStore> {
54    actor_ctx: ActorContextRef,
55
56    /// The external table to be backfilled
57    external_table: ExternalStorageTable,
58
59    /// Upstream changelog stream which may contain metadata columns, e.g. `_rw_offset`
60    upstream: Executor,
61
62    /// The column indices need to be forwarded to the downstream from the upstream and table scan.
63    output_indices: Vec<usize>,
64
65    /// The schema of output chunk, including additional columns if any
66    output_columns: Vec<ColumnDesc>,
67
68    /// State table of the `CdcBackfill` executor
69    state_impl: CdcBackfillState<S>,
70
71    // TODO: introduce a CdcBackfillProgress to report finish to Meta
72    // This object is just a stub right now
73    progress: Option<CreateMviewProgressReporter>,
74
75    metrics: CdcBackfillMetrics,
76
77    /// Rate limit in rows/s.
78    rate_limit_rps: Option<u32>,
79
80    options: CdcScanOptions,
81}
82
83impl<S: StateStore> CdcBackfillExecutor<S> {
84    #[allow(clippy::too_many_arguments)]
85    pub fn new(
86        actor_ctx: ActorContextRef,
87        external_table: ExternalStorageTable,
88        upstream: Executor,
89        output_indices: Vec<usize>,
90        output_columns: Vec<ColumnDesc>,
91        progress: Option<CreateMviewProgressReporter>,
92        metrics: Arc<StreamingMetrics>,
93        state_table: StateTable<S>,
94        rate_limit_rps: Option<u32>,
95        options: CdcScanOptions,
96    ) -> Self {
97        let pk_indices = external_table.pk_indices();
98        let upstream_table_id = external_table.table_id().table_id;
99        let state_impl = CdcBackfillState::new(
100            upstream_table_id,
101            state_table,
102            pk_indices.len() + METADATA_STATE_LEN,
103        );
104
105        let metrics = metrics.new_cdc_backfill_metrics(external_table.table_id(), actor_ctx.id);
106
107        Self {
108            actor_ctx,
109            external_table,
110            upstream,
111            output_indices,
112            output_columns,
113            state_impl,
114            progress,
115            metrics,
116            rate_limit_rps,
117            options,
118        }
119    }
120
121    fn report_metrics(
122        metrics: &CdcBackfillMetrics,
123        snapshot_processed_row_count: u64,
124        upstream_processed_row_count: u64,
125    ) {
126        metrics
127            .cdc_backfill_snapshot_read_row_count
128            .inc_by(snapshot_processed_row_count);
129
130        metrics
131            .cdc_backfill_upstream_output_row_count
132            .inc_by(upstream_processed_row_count);
133    }
134
135    #[try_stream(ok = Message, error = StreamExecutorError)]
136    async fn execute_inner(mut self) {
137        // The indices to primary key columns
138        let pk_indices = self.external_table.pk_indices().to_vec();
139        let pk_order = self.external_table.pk_order_types().to_vec();
140
141        let table_id = self.external_table.table_id().table_id;
142        let upstream_table_name = self.external_table.qualified_table_name();
143        let schema_table_name = self.external_table.schema_table_name().clone();
144        let external_database_name = self.external_table.database_name().to_owned();
145
146        let additional_columns = self
147            .output_columns
148            .iter()
149            .filter(|col| col.additional_column.column_type.is_some())
150            .cloned()
151            .collect_vec();
152
153        let mut upstream = self.upstream.execute();
154
155        // Current position of the upstream_table storage primary key.
156        // `None` means it starts from the beginning.
157        let mut current_pk_pos: Option<OwnedRow>;
158
159        // Poll the upstream to get the first barrier.
160        let first_barrier = expect_first_barrier(&mut upstream).await?;
161
162        let mut is_snapshot_paused = first_barrier.is_pause_on_startup();
163        let first_barrier_epoch = first_barrier.epoch;
164        // The first barrier message should be propagated.
165        yield Message::Barrier(first_barrier);
166        let mut rate_limit_to_zero = self.rate_limit_rps.is_some_and(|val| val == 0);
167
168        // Check whether this parallelism has been assigned splits,
169        // if not, we should bypass the backfill directly.
170        let mut state_impl = self.state_impl;
171
172        state_impl.init_epoch(first_barrier_epoch).await?;
173
174        // restore backfill state
175        let state = state_impl.restore_state().await?;
176        current_pk_pos = state.current_pk_pos.clone();
177
178        let need_backfill = !self.options.disable_backfill && !state.is_finished;
179
180        // Keep track of rows from the snapshot.
181        let mut total_snapshot_row_count = state.row_count as u64;
182
183        // After init the state table and forward the initial barrier to downstream,
184        // we now try to create the table reader with retry.
185        // If backfill hasn't finished, we can ignore upstream cdc events before we create the table reader;
186        // If backfill is finished, we should forward the upstream cdc events to downstream.
187        let mut table_reader: Option<ExternalTableReaderImpl> = None;
188        let external_table = self.external_table.clone();
189        let mut future = Box::pin(async move {
190            let backoff = get_infinite_backoff_strategy();
191            tokio_retry::Retry::spawn(backoff, || async {
192                match external_table.create_table_reader().await {
193                    Ok(reader) => Ok(reader),
194                    Err(e) => {
195                        tracing::warn!(error = %e.as_report(), "failed to create cdc table reader, retrying...");
196                        Err(e)
197                    }
198                }
199            })
200            .instrument(tracing::info_span!("create_cdc_table_reader_with_retry"))
201            .await
202            .expect("Retry create cdc table reader until success.")
203        });
204
205        // Make sure to use mapping_message after transform_upstream.
206        let mut upstream = transform_upstream(upstream, self.output_columns.clone()).boxed();
207        loop {
208            if let Some(msg) =
209                build_reader_and_poll_upstream(&mut upstream, &mut table_reader, &mut future)
210                    .await?
211            {
212                if let Some(msg) = mapping_message(msg, &self.output_indices) {
213                    match msg {
214                        Message::Barrier(barrier) => {
215                            // commit state to bump the epoch of state table
216                            state_impl.commit_state(barrier.epoch).await?;
217                            yield Message::Barrier(barrier);
218                        }
219                        Message::Chunk(chunk) => {
220                            if need_backfill {
221                                // ignore chunk if we need backfill, since we can read the data from the snapshot
222                            } else {
223                                // forward the chunk to downstream
224                                yield Message::Chunk(chunk);
225                            }
226                        }
227                        Message::Watermark(_) => {
228                            // ignore watermark
229                        }
230                    }
231                }
232            } else {
233                assert!(table_reader.is_some(), "table reader must created");
234                tracing::info!(
235                    table_id,
236                    upstream_table_name,
237                    "table reader created successfully"
238                );
239                break;
240            }
241        }
242
243        let upstream_table_reader = UpstreamTableReader::new(
244            self.external_table.clone(),
245            table_reader.expect("table reader must created"),
246        );
247
248        let mut upstream = upstream.peekable();
249        let mut last_binlog_offset: Option<CdcOffset> = state
250            .last_cdc_offset
251            .map_or(upstream_table_reader.current_cdc_offset().await?, Some);
252
253        let offset_parse_func = upstream_table_reader.reader.get_cdc_offset_parser();
254        let mut consumed_binlog_offset: Option<CdcOffset> = None;
255
256        tracing::info!(
257            table_id,
258            upstream_table_name,
259            initial_binlog_offset = ?last_binlog_offset,
260            ?current_pk_pos,
261            is_finished = state.is_finished,
262            is_snapshot_paused,
263            snapshot_row_count = total_snapshot_row_count,
264            rate_limit = self.rate_limit_rps,
265            disable_backfill = self.options.disable_backfill,
266            snapshot_interval = self.options.snapshot_interval,
267            snapshot_batch_size = self.options.snapshot_batch_size,
268            "start cdc backfill",
269        );
270
271        // CDC Backfill Algorithm:
272        //
273        // When the first barrier comes from upstream:
274        //  - read the current binlog offset as `binlog_low`
275        //  - start a snapshot read upon upstream table and iterate over the snapshot read stream
276        //  - buffer the changelog event from upstream
277        //
278        // When a new barrier comes from upstream:
279        //  - read the current binlog offset as `binlog_high`
280        //  - for each row of the upstream change log, forward it to downstream if it in the range
281        //    of [binlog_low, binlog_high] and its pk <= `current_pos`, otherwise ignore it
282        //  - reconstruct the whole backfill stream with upstream changelog and a new table snapshot
283        //
284        // When a chunk comes from snapshot, we forward it to the downstream and raise
285        // `current_pos`.
286        // When we reach the end of the snapshot read stream, it means backfill has been
287        // finished.
288        //
289        // Once the backfill loop ends, we forward the upstream directly to the downstream.
290        if need_backfill {
291            // drive the upstream changelog first to ensure we can receive timely changelog event,
292            // otherwise the upstream changelog may be blocked by the snapshot read stream
293            let _ = Pin::new(&mut upstream).peek().await;
294
295            // wait for a barrier to make sure the backfill starts after upstream source
296            #[for_await]
297            for msg in upstream.by_ref() {
298                match msg? {
299                    Message::Barrier(barrier) => {
300                        match barrier.mutation.as_deref() {
301                            Some(crate::executor::Mutation::Pause) => {
302                                is_snapshot_paused = true;
303                                tracing::info!(
304                                    table_id,
305                                    upstream_table_name,
306                                    "snapshot is paused by barrier"
307                                );
308                            }
309                            Some(crate::executor::Mutation::Resume) => {
310                                is_snapshot_paused = false;
311                                tracing::info!(
312                                    table_id,
313                                    upstream_table_name,
314                                    "snapshot is resumed by barrier"
315                                );
316                            }
317                            _ => {
318                                // ignore other mutations
319                            }
320                        }
321                        // commit state just to bump the epoch of state table
322                        state_impl.commit_state(barrier.epoch).await?;
323                        yield Message::Barrier(barrier);
324                        break;
325                    }
326                    Message::Chunk(ref chunk) => {
327                        last_binlog_offset = get_cdc_chunk_last_offset(&offset_parse_func, chunk)?;
328                    }
329                    Message::Watermark(_) => {
330                        // Ignore watermark
331                    }
332                }
333            }
334
335            tracing::info!(table_id,
336                upstream_table_name,
337                initial_binlog_offset = ?last_binlog_offset,
338                ?current_pk_pos,
339                is_snapshot_paused,
340                "start cdc backfill loop");
341
342            // the buffer will be drained when a barrier comes
343            let mut upstream_chunk_buffer: Vec<StreamChunk> = vec![];
344
345            'backfill_loop: loop {
346                let left_upstream = upstream.by_ref().map(Either::Left);
347
348                let mut snapshot_read_row_cnt: usize = 0;
349                let read_args = SnapshotReadArgs::new(
350                    current_pk_pos.clone(),
351                    self.rate_limit_rps,
352                    pk_indices.clone(),
353                    additional_columns.clone(),
354                    schema_table_name.clone(),
355                    external_database_name.clone(),
356                );
357
358                let right_snapshot = pin!(
359                    upstream_table_reader
360                        .snapshot_read_full_table(read_args, self.options.snapshot_batch_size)
361                        .map(Either::Right)
362                );
363
364                let (right_snapshot, snapshot_valve) = pausable(right_snapshot);
365                if is_snapshot_paused {
366                    snapshot_valve.pause();
367                }
368
369                // Prefer to select upstream, so we can stop snapshot stream when barrier comes.
370                let mut backfill_stream =
371                    select_with_strategy(left_upstream, right_snapshot, |_: &mut ()| {
372                        stream::PollNext::Left
373                    });
374
375                let mut cur_barrier_snapshot_processed_rows: u64 = 0;
376                let mut cur_barrier_upstream_processed_rows: u64 = 0;
377                let mut barrier_count: u32 = 0;
378                let mut pending_barrier = None;
379
380                #[for_await]
381                for either in &mut backfill_stream {
382                    match either {
383                        // Upstream
384                        Either::Left(msg) => {
385                            match msg? {
386                                Message::Barrier(barrier) => {
387                                    // increase the barrier count and check whether need to start a new snapshot
388                                    barrier_count += 1;
389                                    let can_start_new_snapshot =
390                                        barrier_count == self.options.snapshot_interval;
391
392                                    if let Some(mutation) = barrier.mutation.as_deref() {
393                                        use crate::executor::Mutation;
394                                        match mutation {
395                                            Mutation::Pause => {
396                                                is_snapshot_paused = true;
397                                                snapshot_valve.pause();
398                                            }
399                                            Mutation::Resume => {
400                                                is_snapshot_paused = false;
401                                                snapshot_valve.resume();
402                                            }
403                                            Mutation::Throttle(some) => {
404                                                if let Some(new_rate_limit) =
405                                                    some.get(&self.actor_ctx.id)
406                                                    && *new_rate_limit != self.rate_limit_rps
407                                                {
408                                                    self.rate_limit_rps = *new_rate_limit;
409                                                    rate_limit_to_zero = self
410                                                        .rate_limit_rps
411                                                        .is_some_and(|val| val == 0);
412
413                                                    // update and persist current backfill progress without draining the buffered upstream chunks
414                                                    state_impl
415                                                        .mutate_state(
416                                                            current_pk_pos.clone(),
417                                                            last_binlog_offset.clone(),
418                                                            total_snapshot_row_count,
419                                                            false,
420                                                        )
421                                                        .await?;
422                                                    state_impl.commit_state(barrier.epoch).await?;
423                                                    yield Message::Barrier(barrier);
424
425                                                    // rebuild the snapshot stream with new rate limit
426                                                    continue 'backfill_loop;
427                                                }
428                                            }
429                                            Mutation::Update(UpdateMutation {
430                                                dropped_actors,
431                                                ..
432                                            }) => {
433                                                if dropped_actors.contains(&self.actor_ctx.id) {
434                                                    // the actor has been dropped, exit the backfill loop
435                                                    tracing::info!(
436                                                        table_id,
437                                                        upstream_table_name,
438                                                        "CdcBackfill has been dropped due to config change"
439                                                    );
440                                                    yield Message::Barrier(barrier);
441                                                    break 'backfill_loop;
442                                                }
443                                            }
444                                            _ => (),
445                                        }
446                                    }
447
448                                    Self::report_metrics(
449                                        &self.metrics,
450                                        cur_barrier_snapshot_processed_rows,
451                                        cur_barrier_upstream_processed_rows,
452                                    );
453
454                                    // when processing a barrier, check whether can start a new snapshot
455                                    // if the number of barriers reaches the snapshot interval
456                                    if can_start_new_snapshot {
457                                        // staging the barrier
458                                        pending_barrier = Some(barrier);
459                                        tracing::debug!(
460                                            table_id,
461                                            ?current_pk_pos,
462                                            ?snapshot_read_row_cnt,
463                                            "Prepare to start a new snapshot"
464                                        );
465                                        // Break the loop for consuming snapshot and prepare to start a new snapshot
466                                        break;
467                                    } else {
468                                        // update and persist current backfill progress
469                                        state_impl
470                                            .mutate_state(
471                                                current_pk_pos.clone(),
472                                                last_binlog_offset.clone(),
473                                                total_snapshot_row_count,
474                                                false,
475                                            )
476                                            .await?;
477
478                                        state_impl.commit_state(barrier.epoch).await?;
479
480                                        // emit barrier and continue consume the backfill stream
481                                        yield Message::Barrier(barrier);
482                                    }
483                                }
484                                Message::Chunk(chunk) => {
485                                    // skip empty upstream chunk
486                                    if chunk.cardinality() == 0 {
487                                        continue;
488                                    }
489
490                                    let chunk_binlog_offset =
491                                        get_cdc_chunk_last_offset(&offset_parse_func, &chunk)?;
492
493                                    tracing::trace!(
494                                        "recv changelog chunk: chunk_offset {:?}, capactiy {}",
495                                        chunk_binlog_offset,
496                                        chunk.capacity()
497                                    );
498
499                                    // Since we don't need changelog before the
500                                    // `last_binlog_offset`, skip the chunk that *only* contains
501                                    // events before `last_binlog_offset`.
502                                    if let Some(last_binlog_offset) = last_binlog_offset.as_ref() {
503                                        if let Some(chunk_offset) = chunk_binlog_offset
504                                            && chunk_offset < *last_binlog_offset
505                                        {
506                                            tracing::trace!(
507                                                "skip changelog chunk: chunk_offset {:?}, capacity {}",
508                                                chunk_offset,
509                                                chunk.capacity()
510                                            );
511                                            continue;
512                                        }
513                                    }
514                                    // Buffer the upstream chunk.
515                                    upstream_chunk_buffer.push(chunk.compact());
516                                }
517                                Message::Watermark(_) => {
518                                    // Ignore watermark during backfill.
519                                }
520                            }
521                        }
522                        // Snapshot read
523                        Either::Right(msg) => {
524                            match msg? {
525                                None => {
526                                    tracing::info!(
527                                        table_id,
528                                        ?last_binlog_offset,
529                                        ?current_pk_pos,
530                                        "snapshot read stream ends"
531                                    );
532                                    // If the snapshot read stream ends, it means all historical
533                                    // data has been loaded.
534                                    // We should not mark the chunk anymore,
535                                    // otherwise, we will ignore some rows in the buffer.
536                                    for chunk in upstream_chunk_buffer.drain(..) {
537                                        yield Message::Chunk(mapping_chunk(
538                                            chunk,
539                                            &self.output_indices,
540                                        ));
541                                    }
542
543                                    // backfill has finished, exit the backfill loop and persist the state when we recv a barrier
544                                    break 'backfill_loop;
545                                }
546                                Some(chunk) => {
547                                    // Raise the current position.
548                                    // As snapshot read streams are ordered by pk, so we can
549                                    // just use the last row to update `current_pos`.
550                                    current_pk_pos = Some(get_new_pos(&chunk, &pk_indices));
551
552                                    tracing::trace!(
553                                        "got a snapshot chunk: len {}, current_pk_pos {:?}",
554                                        chunk.cardinality(),
555                                        current_pk_pos
556                                    );
557                                    let chunk_cardinality = chunk.cardinality() as u64;
558                                    cur_barrier_snapshot_processed_rows += chunk_cardinality;
559                                    total_snapshot_row_count += chunk_cardinality;
560                                    yield Message::Chunk(mapping_chunk(
561                                        chunk,
562                                        &self.output_indices,
563                                    ));
564                                }
565                            }
566                        }
567                    }
568                }
569
570                assert!(pending_barrier.is_some(), "pending_barrier must exist");
571                let pending_barrier = pending_barrier.unwrap();
572
573                // Here we have to ensure the snapshot stream is consumed at least once,
574                // since the barrier event can kick in anytime.
575                // Otherwise, the result set of the new snapshot stream may become empty.
576                // It maybe a cancellation bug of the mysql driver.
577                let (_, mut snapshot_stream) = backfill_stream.into_inner();
578
579                // skip consume the snapshot stream if it is paused or rate limit to 0
580                if !is_snapshot_paused
581                    && !rate_limit_to_zero
582                    && let Some(msg) = snapshot_stream
583                        .next()
584                        .instrument_await("consume_snapshot_stream_once")
585                        .await
586                {
587                    let Either::Right(msg) = msg else {
588                        bail!("BUG: snapshot_read contains upstream messages");
589                    };
590                    match msg? {
591                        None => {
592                            tracing::info!(
593                                table_id,
594                                ?last_binlog_offset,
595                                ?current_pk_pos,
596                                "snapshot read stream ends in the force emit branch"
597                            );
598                            // End of the snapshot read stream.
599                            // Consume the buffered upstream chunk without filtering by `binlog_low`.
600                            for chunk in upstream_chunk_buffer.drain(..) {
601                                yield Message::Chunk(mapping_chunk(chunk, &self.output_indices));
602                            }
603
604                            // mark backfill has finished
605                            state_impl
606                                .mutate_state(
607                                    current_pk_pos.clone(),
608                                    last_binlog_offset.clone(),
609                                    total_snapshot_row_count,
610                                    true,
611                                )
612                                .await?;
613
614                            // commit state because we have received a barrier message
615                            state_impl.commit_state(pending_barrier.epoch).await?;
616                            yield Message::Barrier(pending_barrier);
617                            // end of backfill loop, since backfill has finished
618                            break 'backfill_loop;
619                        }
620                        Some(chunk) => {
621                            // Raise the current pk position.
622                            current_pk_pos = Some(get_new_pos(&chunk, &pk_indices));
623
624                            let row_count = chunk.cardinality() as u64;
625                            cur_barrier_snapshot_processed_rows += row_count;
626                            total_snapshot_row_count += row_count;
627                            snapshot_read_row_cnt += row_count as usize;
628
629                            tracing::debug!(
630                                table_id,
631                                ?current_pk_pos,
632                                ?snapshot_read_row_cnt,
633                                "force emit a snapshot chunk"
634                            );
635                            yield Message::Chunk(mapping_chunk(chunk, &self.output_indices));
636                        }
637                    }
638                }
639
640                // If the number of barriers reaches the snapshot interval,
641                // consume the buffered upstream chunks.
642                if let Some(current_pos) = &current_pk_pos {
643                    for chunk in upstream_chunk_buffer.drain(..) {
644                        cur_barrier_upstream_processed_rows += chunk.cardinality() as u64;
645
646                        // record the consumed binlog offset that will be
647                        // persisted later
648                        consumed_binlog_offset =
649                            get_cdc_chunk_last_offset(&offset_parse_func, &chunk)?;
650
651                        yield Message::Chunk(mapping_chunk(
652                            mark_cdc_chunk(
653                                &offset_parse_func,
654                                chunk,
655                                current_pos,
656                                &pk_indices,
657                                &pk_order,
658                                last_binlog_offset.clone(),
659                            )?,
660                            &self.output_indices,
661                        ));
662                    }
663                } else {
664                    // If no current_pos, means we did not process any snapshot yet.
665                    // we can just ignore the upstream buffer chunk in that case.
666                    upstream_chunk_buffer.clear();
667                }
668
669                // Update last seen binlog offset
670                if consumed_binlog_offset.is_some() {
671                    last_binlog_offset.clone_from(&consumed_binlog_offset);
672                }
673
674                Self::report_metrics(
675                    &self.metrics,
676                    cur_barrier_snapshot_processed_rows,
677                    cur_barrier_upstream_processed_rows,
678                );
679
680                // update and persist current backfill progress
681                state_impl
682                    .mutate_state(
683                        current_pk_pos.clone(),
684                        last_binlog_offset.clone(),
685                        total_snapshot_row_count,
686                        false,
687                    )
688                    .await?;
689
690                state_impl.commit_state(pending_barrier.epoch).await?;
691                yield Message::Barrier(pending_barrier);
692            }
693        } else if self.options.disable_backfill {
694            // If backfill is disabled, we just mark the backfill as finished
695            tracing::info!(
696                table_id,
697                upstream_table_name,
698                "CdcBackfill has been disabled"
699            );
700            state_impl
701                .mutate_state(
702                    current_pk_pos.clone(),
703                    last_binlog_offset.clone(),
704                    total_snapshot_row_count,
705                    true,
706                )
707                .await?;
708        }
709
710        // drop reader to release db connection
711        drop(upstream_table_reader);
712
713        tracing::info!(
714            table_id,
715            upstream_table_name,
716            "CdcBackfill has already finished and will forward messages directly to the downstream"
717        );
718
719        // Wait for first barrier to come after backfill is finished.
720        // So we can update our progress + persist the status.
721        while let Some(Ok(msg)) = upstream.next().await {
722            if let Some(msg) = mapping_message(msg, &self.output_indices) {
723                // If not finished then we need to update state, otherwise no need.
724                if let Message::Barrier(barrier) = &msg {
725                    // finalized the backfill state
726                    // TODO: unify `mutate_state` and `commit_state` into one method
727                    state_impl
728                        .mutate_state(
729                            current_pk_pos.clone(),
730                            last_binlog_offset.clone(),
731                            total_snapshot_row_count,
732                            true,
733                        )
734                        .await?;
735                    state_impl.commit_state(barrier.epoch).await?;
736
737                    // mark progress as finished
738                    if let Some(progress) = self.progress.as_mut() {
739                        progress.finish(barrier.epoch, total_snapshot_row_count);
740                    }
741                    yield msg;
742                    // break after the state have been saved
743                    break;
744                }
745                yield msg;
746            }
747        }
748
749        // After backfill progress finished
750        // we can forward messages directly to the downstream,
751        // as backfill is finished.
752        #[for_await]
753        for msg in upstream {
754            // upstream offsets will be removed from the message before forwarding to
755            // downstream
756            if let Some(msg) = mapping_message(msg?, &self.output_indices) {
757                if let Message::Barrier(barrier) = &msg {
758                    // commit state just to bump the epoch of state table
759                    state_impl.commit_state(barrier.epoch).await?;
760                }
761                yield msg;
762            }
763        }
764    }
765}
766
767async fn build_reader_and_poll_upstream(
768    upstream: &mut BoxedMessageStream,
769    table_reader: &mut Option<ExternalTableReaderImpl>,
770    future: &mut Pin<Box<impl Future<Output = ExternalTableReaderImpl>>>,
771) -> StreamExecutorResult<Option<Message>> {
772    if table_reader.is_some() {
773        return Ok(None);
774    }
775    tokio::select! {
776        biased;
777        reader = &mut *future => {
778            *table_reader = Some(reader);
779            Ok(None)
780        }
781        msg = upstream.next() => {
782            msg.transpose()
783        }
784    }
785}
786
787#[try_stream(ok = Message, error = StreamExecutorError)]
788pub async fn transform_upstream(upstream: BoxedMessageStream, output_columns: Vec<ColumnDesc>) {
789    let props = SpecificParserConfig {
790        encoding_config: EncodingProperties::Json(JsonProperties {
791            use_schema_registry: false,
792            timestamptz_handling: None,
793        }),
794        // the cdc message is generated internally so the key must exist.
795        protocol_config: ProtocolProperties::Debezium(DebeziumProps::default()),
796    };
797
798    // convert to source column desc to feed into parser
799    let columns_with_meta = output_columns
800        .iter()
801        .map(SourceColumnDesc::from)
802        .collect_vec();
803
804    let mut parser = DebeziumParser::new(
805        props,
806        columns_with_meta.clone(),
807        Arc::new(SourceContext::dummy()),
808    )
809    .await
810    .map_err(StreamExecutorError::connector_error)?;
811
812    pin_mut!(upstream);
813    #[for_await]
814    for msg in upstream {
815        let mut msg = msg?;
816        if let Message::Chunk(chunk) = &mut msg {
817            let parsed_chunk = parse_debezium_chunk(&mut parser, chunk).await?;
818            let _ = std::mem::replace(chunk, parsed_chunk);
819        }
820        yield msg;
821    }
822}
823
824async fn parse_debezium_chunk(
825    parser: &mut DebeziumParser,
826    chunk: &StreamChunk,
827) -> StreamExecutorResult<StreamChunk> {
828    // here we transform the input chunk in `(payload varchar, _rw_offset varchar, _rw_table_name varchar)` schema
829    // to chunk with downstream table schema `info.schema` of MergeNode contains the schema of the
830    // table job with `_rw_offset` in the end
831    // see `gen_create_table_plan_for_cdc_source` for details
832
833    // use `SourceStreamChunkBuilder` for convenience
834    let mut builder = SourceStreamChunkBuilder::new(
835        parser.columns().to_vec(),
836        SourceCtrlOpts {
837            chunk_size: chunk.capacity(),
838            split_txn: false,
839        },
840    );
841
842    // The schema of input chunk `(payload varchar, _rw_offset varchar, _rw_table_name varchar, _row_id)`
843    // We should use the debezium parser to parse the first column,
844    // then chain the parsed row with `_rw_offset` row to get a new row.
845    let payloads = chunk.data_chunk().project(&[0]);
846    let offsets = chunk.data_chunk().project(&[1]).compact();
847
848    // TODO: preserve the transaction semantics
849    for payload in payloads.rows() {
850        let ScalarRefImpl::Jsonb(jsonb_ref) = payload.datum_at(0).expect("payload must exist")
851        else {
852            panic!("payload must be jsonb");
853        };
854
855        parser
856            .parse_inner(
857                None,
858                Some(jsonb_ref.to_string().as_bytes().to_vec()),
859                builder.row_writer(),
860            )
861            .await
862            .unwrap();
863    }
864    builder.finish_current_chunk();
865
866    let parsed_chunk = {
867        let mut iter = builder.consume_ready_chunks();
868        assert_eq!(1, iter.len());
869        iter.next().unwrap()
870    };
871    assert_eq!(parsed_chunk.capacity(), chunk.capacity()); // each payload is expected to generate one row
872    let (ops, mut columns, vis) = parsed_chunk.into_inner();
873    // note that `vis` is not necessarily the same as the original chunk's visibilities
874
875    // concat the rows in the parsed chunk with the `_rw_offset` column
876    columns.extend(offsets.into_parts().0);
877
878    Ok(StreamChunk::from_parts(
879        ops,
880        DataChunk::from_parts(columns.into(), vis),
881    ))
882}
883
884impl<S: StateStore> Execute for CdcBackfillExecutor<S> {
885    fn execute(self: Box<Self>) -> BoxedMessageStream {
886        self.execute_inner().boxed()
887    }
888}
889
890#[cfg(test)]
891mod tests {
892    use std::str::FromStr;
893
894    use futures::{StreamExt, pin_mut};
895    use risingwave_common::array::{Array, DataChunk, Op, StreamChunk};
896    use risingwave_common::catalog::{ColumnDesc, ColumnId, Field, Schema};
897    use risingwave_common::types::{DataType, Datum, JsonbVal};
898    use risingwave_common::util::epoch::test_epoch;
899    use risingwave_common::util::iter_util::ZipEqFast;
900    use risingwave_storage::memory::MemoryStateStore;
901
902    use crate::executor::backfill::cdc::cdc_backfill::transform_upstream;
903    use crate::executor::monitor::StreamingMetrics;
904    use crate::executor::prelude::StateTable;
905    use crate::executor::source::default_source_internal_table;
906    use crate::executor::test_utils::MockSource;
907    use crate::executor::{
908        ActorContext, Barrier, CdcBackfillExecutor, CdcScanOptions, ExternalStorageTable, Message,
909    };
910
911    #[tokio::test]
912    async fn test_transform_upstream_chunk() {
913        let schema = Schema::new(vec![
914            Field::unnamed(DataType::Jsonb),   // debezium json payload
915            Field::unnamed(DataType::Varchar), // _rw_offset
916            Field::unnamed(DataType::Varchar), // _rw_table_name
917        ]);
918        let pk_indices = vec![1];
919        let (mut tx, source) = MockSource::channel();
920        let source = source.into_executor(schema.clone(), pk_indices.clone());
921        // let payload = r#"{"before": null,"after":{"O_ORDERKEY": 5, "O_CUSTKEY": 44485, "O_ORDERSTATUS": "F", "O_TOTALPRICE": "144659.20", "O_ORDERDATE": "1994-07-30" },"source":{"version": "1.9.7.Final", "connector": "mysql", "name": "RW_CDC_1002", "ts_ms": 1695277757000, "snapshot": "last", "db": "mydb", "sequence": null, "table": "orders_new", "server_id": 0, "gtid": null, "file": "binlog.000008", "pos": 3693, "row": 0, "thread": null, "query": null},"op":"r","ts_ms":1695277757017,"transaction":null}"#.to_string();
922        let payload = r#"{ "payload": { "before": null, "after": { "O_ORDERKEY": 5, "O_CUSTKEY": 44485, "O_ORDERSTATUS": "F", "O_TOTALPRICE": "144659.20", "O_ORDERDATE": "1994-07-30" }, "source": { "version": "1.9.7.Final", "connector": "mysql", "name": "RW_CDC_1002", "ts_ms": 1695277757000, "snapshot": "last", "db": "mydb", "sequence": null, "table": "orders_new", "server_id": 0, "gtid": null, "file": "binlog.000008", "pos": 3693, "row": 0, "thread": null, "query": null }, "op": "r", "ts_ms": 1695277757017, "transaction": null } }"#;
923
924        let datums: Vec<Datum> = vec![
925            Some(JsonbVal::from_str(payload).unwrap().into()),
926            Some("file: 1.binlog, pos: 100".to_owned().into()),
927            Some("mydb.orders".to_owned().into()),
928        ];
929
930        println!("datums: {:?}", datums[1]);
931
932        let mut builders = schema.create_array_builders(8);
933        for (builder, datum) in builders.iter_mut().zip_eq_fast(datums.iter()) {
934            builder.append(datum.clone());
935        }
936        let columns = builders
937            .into_iter()
938            .map(|builder| builder.finish().into())
939            .collect();
940
941        // one row chunk
942        let chunk = StreamChunk::from_parts(vec![Op::Insert], DataChunk::new(columns, 1));
943
944        tx.push_chunk(chunk);
945        let upstream = Box::new(source).execute();
946
947        // schema to the debezium parser
948        let columns = vec![
949            ColumnDesc::named("O_ORDERKEY", ColumnId::new(1), DataType::Int64),
950            ColumnDesc::named("O_CUSTKEY", ColumnId::new(2), DataType::Int64),
951            ColumnDesc::named("O_ORDERSTATUS", ColumnId::new(3), DataType::Varchar),
952            ColumnDesc::named("O_TOTALPRICE", ColumnId::new(4), DataType::Decimal),
953            ColumnDesc::named("O_ORDERDATE", ColumnId::new(5), DataType::Date),
954            ColumnDesc::named("commit_ts", ColumnId::new(6), DataType::Timestamptz),
955        ];
956
957        let parsed_stream = transform_upstream(upstream, columns);
958        pin_mut!(parsed_stream);
959        // the output chunk must contain the offset column
960        if let Some(message) = parsed_stream.next().await {
961            println!("chunk: {:#?}", message.unwrap());
962        }
963    }
964
965    #[tokio::test]
966    async fn test_build_reader_and_poll_upstream() {
967        let actor_context = ActorContext::for_test(1);
968        let external_storage_table = ExternalStorageTable::for_test_undefined();
969        let schema = Schema::new(vec![
970            Field::unnamed(DataType::Jsonb),   // debezium json payload
971            Field::unnamed(DataType::Varchar), // _rw_offset
972            Field::unnamed(DataType::Varchar), // _rw_table_name
973        ]);
974        let pk_indices = vec![1];
975        let (mut tx, source) = MockSource::channel();
976        let source = source.into_executor(schema.clone(), pk_indices.clone());
977        let output_indices = vec![1, 0, 4]; //reorder
978        let output_columns = vec![
979            ColumnDesc::named("O_ORDERKEY", ColumnId::new(1), DataType::Int64),
980            ColumnDesc::named("O_CUSTKEY", ColumnId::new(2), DataType::Int64),
981            ColumnDesc::named("O_ORDERSTATUS", ColumnId::new(3), DataType::Varchar),
982            ColumnDesc::named("O_TOTALPRICE", ColumnId::new(4), DataType::Decimal),
983            ColumnDesc::named("O_DUMMY", ColumnId::new(5), DataType::Int64),
984            ColumnDesc::named("commit_ts", ColumnId::new(6), DataType::Timestamptz),
985        ];
986        let store = MemoryStateStore::new();
987        let state_table =
988            StateTable::from_table_catalog(&default_source_internal_table(0x2333), store, None)
989                .await;
990        let cdc = CdcBackfillExecutor::new(
991            actor_context,
992            external_storage_table,
993            source,
994            output_indices,
995            output_columns,
996            None,
997            StreamingMetrics::unused().into(),
998            state_table,
999            None,
1000            CdcScanOptions {
1001                // We want to mark backfill as finished. However it's not straightforward to do so.
1002                // Here we disable_backfill instead.
1003                disable_backfill: true,
1004                ..CdcScanOptions::default()
1005            },
1006        );
1007        // cdc.state_impl.init_epoch(EpochPair::new(test_epoch(4), test_epoch(3))).await.unwrap();
1008        // cdc.state_impl.mutate_state(None, None, 0, true).await.unwrap();
1009        // cdc.state_impl.commit_state(EpochPair::new(test_epoch(5), test_epoch(4))).await.unwrap();
1010        let s = cdc.execute_inner();
1011        pin_mut!(s);
1012
1013        // send first barrier
1014        tx.send_barrier(Barrier::new_test_barrier(test_epoch(8)));
1015        // send chunk
1016        {
1017            let payload = r#"{ "payload": { "before": null, "after": { "O_ORDERKEY": 5, "O_CUSTKEY": 44485, "O_ORDERSTATUS": "F", "O_TOTALPRICE": "144659.20", "O_DUMMY": 100 }, "source": { "version": "1.9.7.Final", "connector": "mysql", "name": "RW_CDC_1002", "ts_ms": 1695277757000, "snapshot": "last", "db": "mydb", "sequence": null, "table": "orders_new", "server_id": 0, "gtid": null, "file": "binlog.000008", "pos": 3693, "row": 0, "thread": null, "query": null }, "op": "r", "ts_ms": 1695277757017, "transaction": null } }"#;
1018            let datums: Vec<Datum> = vec![
1019                Some(JsonbVal::from_str(payload).unwrap().into()),
1020                Some("file: 1.binlog, pos: 100".to_owned().into()),
1021                Some("mydb.orders".to_owned().into()),
1022            ];
1023            let mut builders = schema.create_array_builders(8);
1024            for (builder, datum) in builders.iter_mut().zip_eq_fast(datums.iter()) {
1025                builder.append(datum.clone());
1026            }
1027            let columns = builders
1028                .into_iter()
1029                .map(|builder| builder.finish().into())
1030                .collect();
1031            // one row chunk
1032            let chunk = StreamChunk::from_parts(vec![Op::Insert], DataChunk::new(columns, 1));
1033
1034            tx.push_chunk(chunk);
1035        }
1036        let _first_barrier = s.next().await.unwrap();
1037        let upstream_change_log = s.next().await.unwrap().unwrap();
1038        let Message::Chunk(chunk) = upstream_change_log else {
1039            panic!("expect chunk");
1040        };
1041        assert_eq!(chunk.columns().len(), 3);
1042        assert_eq!(chunk.rows().count(), 1);
1043        assert_eq!(
1044            chunk.columns()[0].as_int64().iter().collect::<Vec<_>>(),
1045            vec![Some(44485)]
1046        );
1047        assert_eq!(
1048            chunk.columns()[1].as_int64().iter().collect::<Vec<_>>(),
1049            vec![Some(5)]
1050        );
1051        assert_eq!(
1052            chunk.columns()[2].as_int64().iter().collect::<Vec<_>>(),
1053            vec![Some(100)]
1054        );
1055    }
1056}