Skip to main content

risingwave_stream/executor/backfill/cdc/
cdc_backill_v2.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16
17use either::Either;
18use futures::stream;
19use futures::stream::select_with_strategy;
20use itertools::Itertools;
21use risingwave_common::bitmap::BitmapBuilder;
22use risingwave_common::catalog::{ColumnDesc, Field};
23use risingwave_common::row::RowDeserializer;
24use risingwave_common::util::iter_util::ZipEqFast;
25use risingwave_common::util::sort_util::{OrderType, cmp_datum};
26use risingwave_connector::source::cdc::CdcScanOptions;
27use risingwave_connector::source::cdc::external::{CdcOffset, ExternalCdcTableType};
28use risingwave_connector::source::{CdcTableSnapshotSplit, CdcTableSnapshotSplitRaw};
29use rw_futures_util::pausable;
30use thiserror_ext::AsReport;
31
32use crate::executor::backfill::cdc::cdc_backfill::transform_upstream;
33use crate::executor::backfill::cdc::state_v2::{CdcStateRecord, ParallelizedCdcBackfillState};
34use crate::executor::backfill::cdc::upstream_table::external::ExternalStorageTable;
35use crate::executor::backfill::cdc::upstream_table::reader::{
36    build_reader_and_poll_upstream, create_table_reader_with_retry,
37};
38use crate::executor::backfill::cdc::upstream_table::snapshot::{
39    SplitSnapshotReadArgs, UpstreamTableRead, UpstreamTableReader,
40};
41use crate::executor::backfill::utils::{get_cdc_chunk_last_offset, mapping_chunk, mapping_message};
42use crate::executor::prelude::*;
43use crate::task::ActorId;
44use crate::task::cdc_progress::CdcProgressReporter;
45
46pub struct ParallelizedCdcBackfillExecutor<S: StateStore> {
47    actor_ctx: ActorContextRef,
48
49    /// The external table to be backfilled
50    external_table: ExternalStorageTable,
51
52    /// Upstream changelog stream which may contain metadata columns, e.g. `_rw_offset`
53    upstream: Executor,
54
55    /// The column indices need to be forwarded to the downstream from the upstream and table scan.
56    output_indices: Vec<usize>,
57
58    /// The schema of output chunk, including additional columns if any
59    output_columns: Vec<ColumnDesc>,
60
61    /// Rate limit in rows/s.
62    rate_limit_rps: Option<u32>,
63
64    options: CdcScanOptions,
65
66    state_table: StateTable<S>,
67
68    properties: BTreeMap<String, String>,
69
70    progress: Option<CdcProgressReporter>,
71}
72
73enum SnapshotAttemptState {
74    Reading,
75    Failed,
76    Finished(CdcOffset),
77}
78
79impl<S: StateStore> ParallelizedCdcBackfillExecutor<S> {
80    #[expect(clippy::too_many_arguments)]
81    pub fn new(
82        actor_ctx: ActorContextRef,
83        external_table: ExternalStorageTable,
84        upstream: Executor,
85        output_indices: Vec<usize>,
86        output_columns: Vec<ColumnDesc>,
87        _metrics: Arc<StreamingMetrics>,
88        state_table: StateTable<S>,
89        rate_limit_rps: Option<u32>,
90        options: CdcScanOptions,
91        properties: BTreeMap<String, String>,
92        progress: Option<CdcProgressReporter>,
93    ) -> Self {
94        Self {
95            actor_ctx,
96            external_table,
97            upstream,
98            output_indices,
99            output_columns,
100            rate_limit_rps,
101            options,
102            state_table,
103            properties,
104            progress,
105        }
106    }
107
108    #[try_stream(ok = Message, error = StreamExecutorError)]
109    async fn execute_inner(mut self) {
110        assert!(!self.options.disable_backfill);
111        // The indices to primary key columns
112        let pk_indices = self.external_table.pk_indices().to_vec();
113        let table_id = self.external_table.table_id();
114        let upstream_table_name = self.external_table.qualified_table_name();
115        let schema_table_name = self.external_table.schema_table_name().clone();
116        let external_database_name = self.external_table.database_name().to_owned();
117        let additional_columns = self
118            .output_columns
119            .iter()
120            .filter(|col| col.additional_column.column_type.is_some())
121            .cloned()
122            .collect_vec();
123        assert!(
124            (self.options.backfill_split_pk_column_index as usize) < pk_indices.len(),
125            "split pk column index {} out of bound",
126            self.options.backfill_split_pk_column_index
127        );
128        let snapshot_split_column_index =
129            pk_indices[self.options.backfill_split_pk_column_index as usize];
130        let snapshot_split_column_in_output_index = self
131            .output_indices
132            .iter()
133            .position(|&idx| idx == snapshot_split_column_index)
134            .expect("snapshot split column must be present in CDC backfill output");
135        let cdc_table_snapshot_split_column =
136            vec![self.external_table.schema().fields[snapshot_split_column_index].clone()];
137
138        let mut upstream = self.upstream.execute();
139        // Poll the upstream to get the first barrier.
140        let first_barrier = expect_first_barrier(&mut upstream).await?;
141        // Make sure to use mapping_message after transform_upstream.
142
143        // If user sets debezium.time.precision.mode to "connect", it means the user can guarantee
144        // that the upstream data precision is MilliSecond. In this case, we don't use GuessNumberUnit
145        // mode to guess precision, but use Milli mode directly, which can handle extreme timestamps.
146        // Only postgres-cdc connector may trigger TOAST.
147        let handle_postgres_toast_columns: bool =
148            self.external_table.table_type() == &ExternalCdcTableType::Postgres;
149        let mut upstream = transform_upstream(
150            upstream,
151            self.output_columns.clone(),
152            self.properties.clone(),
153            handle_postgres_toast_columns,
154        )
155        .boxed();
156        let mut next_reset_barrier = Some(first_barrier);
157        let mut is_reset = false;
158        let mut state_impl = ParallelizedCdcBackfillState::new(self.state_table);
159        // The buffered chunks have already been mapped.
160        let mut upstream_chunk_buffer: Vec<StreamChunk> = vec![];
161
162        // Need reset on CDC table snapshot splits reschedule.
163        'with_cdc_table_snapshot_splits: loop {
164            assert!(upstream_chunk_buffer.is_empty());
165            let reset_barrier = next_reset_barrier.take().unwrap();
166            let all_snapshot_splits = match reset_barrier.mutation.as_deref() {
167                Some(Mutation::Add(add)) => &add.actor_cdc_table_snapshot_splits.splits,
168
169                Some(Mutation::Update(update)) => &update.actor_cdc_table_snapshot_splits.splits,
170                _ => {
171                    return Err(anyhow::anyhow!("ParallelizedCdcBackfillExecutor expects either Mutation::Add or Mutation::Update to initialize CDC table snapshot splits.").into());
172                }
173            };
174            let mut actor_snapshot_splits = vec![];
175            let mut generation = None;
176            // TODO(zw): optimization: remove consumed splits to reduce barrier size for downstream.
177            if let Some((splits, snapshot_generation)) = all_snapshot_splits.get(&self.actor_ctx.id)
178            {
179                actor_snapshot_splits = splits
180                    .iter()
181                    .map(|s: &CdcTableSnapshotSplitRaw| {
182                        let de = RowDeserializer::new(
183                            cdc_table_snapshot_split_column
184                                .iter()
185                                .map(Field::data_type)
186                                .collect_vec(),
187                        );
188                        let left_bound_inclusive =
189                            de.deserialize(s.left_bound_inclusive.as_ref()).unwrap();
190                        let right_bound_exclusive =
191                            de.deserialize(s.right_bound_exclusive.as_ref()).unwrap();
192                        CdcTableSnapshotSplit {
193                            split_id: s.split_id,
194                            left_bound_inclusive,
195                            right_bound_exclusive,
196                        }
197                    })
198                    .collect();
199                generation = Some(*snapshot_generation);
200            }
201            tracing::debug!(?actor_snapshot_splits, ?generation, "actor splits");
202            assert_consecutive_splits(&actor_snapshot_splits);
203
204            let mut is_snapshot_paused = reset_barrier.is_pause_on_startup();
205            let barrier_epoch = reset_barrier.epoch;
206            yield Message::Barrier(reset_barrier);
207            if !is_reset {
208                state_impl.init_epoch(barrier_epoch).await?;
209                is_reset = true;
210                tracing::info!(%table_id, "Initialize executor.");
211            } else {
212                tracing::info!(%table_id, "Reset executor.");
213            }
214
215            let mut current_actor_bounds = None;
216            let mut actor_cdc_offset_high: Option<CdcOffset> = None;
217            let mut actor_cdc_offset_low: Option<CdcOffset> = None;
218            let mut split_states = Vec::with_capacity(actor_snapshot_splits.len());
219
220            for split in &actor_snapshot_splits {
221                let state = state_impl.restore_state(split.split_id).await?;
222                extends_current_actor_bound(&mut current_actor_bounds, split);
223
224                if state.is_finished {
225                    if let Some(cdc_offset) = state.cdc_offset_low.as_ref()
226                        && actor_cdc_offset_low
227                            .as_ref()
228                            .is_none_or(|current| current > cdc_offset)
229                    {
230                        actor_cdc_offset_low = Some(cdc_offset.clone());
231                    }
232
233                    if let Some(cdc_offset) = state.cdc_offset_high.as_ref()
234                        && actor_cdc_offset_high
235                            .as_ref()
236                            .is_none_or(|current| current < cdc_offset)
237                    {
238                        actor_cdc_offset_high = Some(cdc_offset.clone());
239                    }
240                }
241
242                split_states.push(state);
243            }
244
245            let next_split_idx = split_states.iter().position(|state| !state.is_finished);
246            let finished_prefix_len = next_split_idx.unwrap_or(actor_snapshot_splits.len());
247            let mut should_report_actor_backfill_progress = (finished_prefix_len > 0).then(|| {
248                (
249                    actor_snapshot_splits[0].split_id,
250                    actor_snapshot_splits[finished_prefix_len - 1].split_id,
251                )
252            });
253
254            for split in &actor_snapshot_splits {
255                // Initialize state so that overall progress can be measured.
256                state_impl.init_state_if_absent(split.split_id).await?;
257            }
258
259            let offset_parse_func = self.external_table.table_type().get_cdc_offset_parser()?;
260
261            // A reader is only needed while at least one assigned snapshot split is unfinished.
262            // Once all splits are complete, the executor only forwards the table-filtered CDC
263            // stream and must not depend on the upstream snapshot table still existing.
264            if let Some(next_split_idx) = next_split_idx {
265                let external_table = self.external_table.clone();
266                let actor_id = self.actor_ctx.id;
267                let fragment_id = self.actor_ctx.fragment_id;
268                let mut future = Box::pin(create_table_reader_with_retry(
269                    external_table,
270                    actor_id,
271                    fragment_id,
272                ));
273
274                let table_reader = loop {
275                    match build_reader_and_poll_upstream(&mut upstream, &mut future).await? {
276                        Either::Left(msg) => match msg {
277                            Message::Barrier(barrier) => {
278                                for chunk in &upstream_chunk_buffer {
279                                    yield Message::Chunk(chunk.clone());
280                                }
281
282                                state_impl.commit_state(barrier.epoch).await?;
283
284                                if let Some(mutation) = barrier.mutation.as_deref() {
285                                    match mutation {
286                                        Mutation::Pause => {
287                                            is_snapshot_paused = true;
288                                        }
289                                        Mutation::Resume => {
290                                            is_snapshot_paused = false;
291                                        }
292                                        Mutation::Throttle(_) => {
293                                            if let Some(entry) = mutation.backfill_throttle_config(
294                                                self.actor_ctx.fragment_id,
295                                            ) {
296                                                self.rate_limit_rps = entry.rate_limit;
297                                            }
298                                        }
299                                        _ => (),
300                                    }
301                                }
302
303                                if is_reset_barrier(&barrier, self.actor_ctx.id) {
304                                    upstream_chunk_buffer.clear();
305                                    next_reset_barrier = Some(barrier);
306                                    continue 'with_cdc_table_snapshot_splits;
307                                }
308                                yield Message::Barrier(barrier);
309                            }
310                            Message::Chunk(chunk) => {
311                                if !chunk.has_visible_rows() {
312                                    continue;
313                                }
314
315                                let chunk = mapping_chunk(chunk, &self.output_indices);
316                                let (forwarded_chunk, buffered_chunk) = route_cdc_chunk(
317                                    chunk,
318                                    &actor_snapshot_splits,
319                                    &split_states,
320                                    next_split_idx,
321                                    snapshot_split_column_in_output_index,
322                                );
323
324                                if let Some(forwarded_chunk) = forwarded_chunk {
325                                    yield Message::Chunk(forwarded_chunk);
326                                }
327
328                                if let Some(buffered_chunk) = buffered_chunk {
329                                    upstream_chunk_buffer.push(buffered_chunk);
330                                }
331                            }
332                            Message::Watermark(_) => {
333                                // Ignore watermark, like the `CdcBackfillExecutor`.
334                            }
335                        },
336                        Either::Right(table_reader) => break table_reader,
337                    }
338                };
339                tracing::info!(
340                    %table_id,
341                    upstream_table_name,
342                    "table reader created successfully"
343                );
344
345                let mut upstream_table_reader =
346                    UpstreamTableReader::new(self.external_table.clone(), table_reader);
347
348                // Backfill snapshot splits sequentially.
349                for (split_idx, (split, restored_state)) in actor_snapshot_splits
350                    .iter()
351                    .zip_eq_fast(split_states.iter())
352                    .enumerate()
353                    .skip(next_split_idx)
354                {
355                    if restored_state.is_finished {
356                        extend_backfill_progress(
357                            &mut should_report_actor_backfill_progress,
358                            split.split_id,
359                        );
360
361                        continue;
362                    }
363                    tracing::info!(
364                        %table_id,
365                        upstream_table_name,
366                        ?split,
367                        is_snapshot_paused,
368                        "start cdc backfill split"
369                    );
370                    let mut durable_row_count = restored_state.row_count as u64;
371                    let mut split_cdc_offset_low = restored_state.cdc_offset_low.clone();
372
373                    let split_cdc_offset_high = 'backfill_loop: loop {
374                        // A rebuilt reader restarts this split from its lower bound, so count each
375                        // snapshot attempt independently instead of accumulating duplicate reads.
376                        let mut attempt_row_count = 0_u64;
377
378                        if split_cdc_offset_low.is_none() {
379                            static CDC_CONN_SEMAPHORE: tokio::sync::Semaphore =
380                                tokio::sync::Semaphore::const_new(10);
381                            let _permit = CDC_CONN_SEMAPHORE.acquire().await.unwrap();
382                            split_cdc_offset_low =
383                                upstream_table_reader.current_cdc_offset().await?;
384                        }
385
386                        if let Some(ref cdc_offset) = split_cdc_offset_low
387                            && actor_cdc_offset_low
388                                .as_ref()
389                                .is_none_or(|cur| cur > cdc_offset)
390                        {
391                            actor_cdc_offset_low = split_cdc_offset_low.clone();
392                        }
393
394                        let attempt_state = {
395                            let left_upstream = upstream.by_ref().map(Either::Left);
396                            let read_args = SplitSnapshotReadArgs::new(
397                                split.left_bound_inclusive.clone(),
398                                split.right_bound_exclusive.clone(),
399                                cdc_table_snapshot_split_column.clone(),
400                                self.rate_limit_rps,
401                                additional_columns.clone(),
402                                schema_table_name.clone(),
403                                external_database_name.clone(),
404                            );
405                            let right_snapshot = pin!(
406                                upstream_table_reader
407                                    .snapshot_read_table_split(read_args)
408                                    .map(Either::Right)
409                            );
410                            let (right_snapshot, snapshot_valve) = pausable(right_snapshot);
411
412                            if is_snapshot_paused {
413                                snapshot_valve.pause();
414                            }
415
416                            let mut backfill_stream = select_with_strategy(
417                                left_upstream,
418                                right_snapshot,
419                                |_: &mut ()| stream::PollNext::Left,
420                            );
421                            let mut attempt_state = SnapshotAttemptState::Reading;
422
423                            #[for_await]
424                            'backfill_stream: for either in &mut backfill_stream {
425                                match either {
426                                    Either::Left(upstream_message) => match upstream_message? {
427                                        Message::Barrier(barrier) => {
428                                            // The source offset advances with this barrier, so make
429                                            // every buffered change durable first. Keep the buffer
430                                            // because a later snapshot row may still overwrite it.
431                                            for chunk in &upstream_chunk_buffer {
432                                                yield Message::Chunk(chunk.clone());
433                                            }
434
435                                            durable_row_count =
436                                                durable_row_count.max(attempt_row_count);
437
438                                            state_impl
439                                                .mutate_state(
440                                                    split.split_id,
441                                                    false,
442                                                    durable_row_count,
443                                                    split_cdc_offset_low.clone(),
444                                                    None,
445                                                )
446                                                .await?;
447                                            state_impl.commit_state(barrier.epoch).await?;
448
449                                            if let Some(mutation) = barrier.mutation.as_deref() {
450                                                use crate::executor::Mutation;
451                                                match mutation {
452                                                    Mutation::Pause => {
453                                                        is_snapshot_paused = true;
454                                                        snapshot_valve.pause();
455                                                    }
456                                                    Mutation::Resume => {
457                                                        is_snapshot_paused = false;
458                                                        snapshot_valve.resume();
459                                                    }
460                                                    Mutation::Throttle(_) => {
461                                                        // TODO(zw): optimization: improve throttle.
462                                                        // 1. Handle rate limit 0. Currently, to resume the process, the actor must be rebuilt.
463                                                        // 2. Apply new rate limit immediately.
464                                                        if let Some(entry) = mutation
465                                                            .backfill_throttle_config(
466                                                                self.actor_ctx.fragment_id,
467                                                            )
468                                                        {
469                                                            // The new rate limit will take effect since next split.
470                                                            self.rate_limit_rps = entry.rate_limit;
471                                                        }
472                                                    }
473                                                    mutation
474                                                        if mutation.is_stop(self.actor_ctx.id) =>
475                                                    {
476                                                        tracing::info!(
477                                                            %table_id,
478                                                            upstream_table_name,
479                                                            "CdcBackfill has been dropped due to config change"
480                                                        );
481
482                                                        yield Message::Barrier(barrier);
483
484                                                        let () = futures::future::pending().await;
485                                                        unreachable!();
486                                                    }
487                                                    _ => (),
488                                                }
489                                            }
490
491                                            if is_reset_barrier(&barrier, self.actor_ctx.id) {
492                                                // the cdc events belonging to this split no longer matters,
493                                                // since a new snapshot will cover the latest state
494                                                upstream_chunk_buffer.clear();
495                                                next_reset_barrier = Some(barrier);
496
497                                                // restart to apply new split state
498                                                continue 'with_cdc_table_snapshot_splits;
499                                            }
500
501                                            if let (Some(split_range), Some(progress)) = (
502                                                should_report_actor_backfill_progress.take(),
503                                                self.progress.as_ref(),
504                                            ) {
505                                                progress.update(
506                                                    self.actor_ctx.fragment_id,
507                                                    self.actor_ctx.id,
508                                                    barrier.epoch,
509                                                    generation.expect("should have set generation when having progress to report"),
510                                                    split_range,
511                                                );
512                                            }
513
514                                            yield Message::Barrier(barrier);
515
516                                            if matches!(attempt_state, SnapshotAttemptState::Failed)
517                                            {
518                                                break 'backfill_stream;
519                                            }
520                                        }
521                                        Message::Chunk(chunk) => {
522                                            if !chunk.has_visible_rows() {
523                                                continue 'backfill_stream;
524                                            }
525
526                                            // TODO(zw): re-enable
527                                            // let chunk_cdc_offset =
528                                            //     get_cdc_chunk_last_offset(&offset_parse_func, &chunk)?;
529                                            // if *self.external_table.table_type()
530                                            //     == ExternalCdcTableType::Postgres
531                                            //     && let Some(cur) = actor_cdc_offset_low.as_ref()
532                                            //     && let Some(chunk_offset) = chunk_cdc_offset
533                                            //     && chunk_offset < *cur
534                                            // {
535                                            //     continue;
536                                            // }
537
538                                            // emit chunks belonging to past splits which are processed
539                                            let chunk = mapping_chunk(chunk, &self.output_indices);
540                                            let (forwarded_chunk, buffered_chunk) = route_cdc_chunk(
541                                                chunk,
542                                                &actor_snapshot_splits,
543                                                &split_states,
544                                                split_idx,
545                                                snapshot_split_column_in_output_index,
546                                            );
547
548                                            if let Some(forwarded_chunk) = forwarded_chunk {
549                                                yield Message::Chunk(forwarded_chunk);
550                                            }
551
552                                            if let Some(buffered_chunk) = buffered_chunk {
553                                                upstream_chunk_buffer.push(buffered_chunk);
554                                            }
555                                        }
556                                        Message::Watermark(_) => {
557                                            // ignore watermark during backfill
558                                        }
559                                    },
560                                    Either::Right(snapshot) => {
561                                        // if snapshot already failed, continue polling upstream until barrier arrives to reconstruct reader
562                                        if matches!(attempt_state, SnapshotAttemptState::Failed) {
563                                            continue 'backfill_stream;
564                                        }
565
566                                        match snapshot {
567                                            Ok(None) => {
568                                                tracing::info!(
569                                                    %table_id,
570                                                    split_id = split.split_id,
571                                                    "snapshot read stream ends"
572                                                );
573
574                                                for chunk in upstream_chunk_buffer.drain(..) {
575                                                    yield Message::Chunk(chunk);
576                                                }
577
578                                                // This attempt scanned the whole split, so its count
579                                                // is exact even if earlier attempts read duplicate rows.
580                                                durable_row_count = attempt_row_count;
581
582                                                // Limit concurrent CDC connections globally to 10 using a semaphore.
583                                                static CDC_CONN_SEMAPHORE: tokio::sync::Semaphore =
584                                                    tokio::sync::Semaphore::const_new(10);
585                                                let _permit =
586                                                    CDC_CONN_SEMAPHORE.acquire().await.unwrap();
587                                                let high = upstream_table_reader
588                                                .current_cdc_offset()
589                                                .await?
590                                                .expect(
591                                                    "CDC offset must be available after snapshot completion",
592                                                );
593                                                attempt_state =
594                                                    SnapshotAttemptState::Finished(high);
595
596                                                break 'backfill_stream;
597                                            }
598                                            Ok(Some(chunk)) => {
599                                                attempt_row_count = attempt_row_count
600                                                    .saturating_add(chunk.cardinality() as u64);
601
602                                                yield Message::Chunk(mapping_chunk(
603                                                    chunk,
604                                                    &self.output_indices,
605                                                ));
606                                            }
607                                            Err(error) => {
608                                                attempt_state = SnapshotAttemptState::Failed;
609                                                tracing::warn!(
610                                                    error = %error.as_report(),
611                                                    %table_id,
612                                                    upstream_table_name,
613                                                    "failed to read CDC snapshot; rebuilding reader after a barrier"
614                                                );
615                                            }
616                                        }
617                                    }
618                                }
619                            }
620                            attempt_state
621                        };
622
623                        match attempt_state {
624                            SnapshotAttemptState::Finished(split_cdc_offset_high) => {
625                                break 'backfill_loop split_cdc_offset_high;
626                            }
627                            SnapshotAttemptState::Failed => {
628                                if let Err(error) = upstream_table_reader.disconnect().await {
629                                    tracing::warn!(
630                                        error = %error.as_report(),
631                                        %table_id,
632                                        upstream_table_name,
633                                        "failed to disconnect CDC snapshot reader; continuing with rebuild"
634                                    );
635                                }
636
637                                let mut future = Box::pin(create_table_reader_with_retry(
638                                    self.external_table.clone(),
639                                    self.actor_ctx.id,
640                                    self.actor_ctx.fragment_id,
641                                ));
642                                let table_reader = loop {
643                                    match build_reader_and_poll_upstream(&mut upstream, &mut future)
644                                        .await?
645                                    {
646                                        Either::Left(msg) => match msg {
647                                            Message::Barrier(barrier) => {
648                                                for chunk in &upstream_chunk_buffer {
649                                                    yield Message::Chunk(chunk.clone());
650                                                }
651
652                                                state_impl.commit_state(barrier.epoch).await?;
653
654                                                if let Some(mutation) = barrier.mutation.as_deref()
655                                                {
656                                                    use crate::executor::Mutation;
657                                                    match mutation {
658                                                        Mutation::Pause => {
659                                                            is_snapshot_paused = true;
660                                                        }
661                                                        Mutation::Resume => {
662                                                            is_snapshot_paused = false;
663                                                        }
664                                                        Mutation::Throttle(_) => {
665                                                            if let Some(entry) = mutation
666                                                                .backfill_throttle_config(
667                                                                    self.actor_ctx.fragment_id,
668                                                                )
669                                                            {
670                                                                self.rate_limit_rps =
671                                                                    entry.rate_limit;
672                                                            }
673                                                        }
674                                                        mutation
675                                                            if mutation
676                                                                .is_stop(self.actor_ctx.id) =>
677                                                        {
678                                                            yield Message::Barrier(barrier);
679                                                            let () =
680                                                                futures::future::pending().await;
681                                                            unreachable!();
682                                                        }
683                                                        _ => (),
684                                                    }
685                                                }
686
687                                                if is_reset_barrier(&barrier, self.actor_ctx.id) {
688                                                    upstream_chunk_buffer.clear();
689                                                    next_reset_barrier = Some(barrier);
690
691                                                    continue 'with_cdc_table_snapshot_splits;
692                                                }
693
694                                                yield Message::Barrier(barrier);
695                                            }
696                                            Message::Chunk(chunk) => {
697                                                let chunk =
698                                                    mapping_chunk(chunk, &self.output_indices);
699                                                let (forwarded_chunk, buffered_chunk) =
700                                                    route_cdc_chunk(
701                                                        chunk,
702                                                        &actor_snapshot_splits,
703                                                        &split_states,
704                                                        split_idx,
705                                                        snapshot_split_column_in_output_index,
706                                                    );
707
708                                                if let Some(forwarded_chunk) = forwarded_chunk {
709                                                    yield Message::Chunk(forwarded_chunk);
710                                                }
711
712                                                if let Some(buffered_chunk) = buffered_chunk {
713                                                    upstream_chunk_buffer.push(buffered_chunk);
714                                                }
715                                            }
716                                            Message::Watermark(_) => {}
717                                        },
718                                        Either::Right(table_reader) => {
719                                            break table_reader;
720                                        }
721                                    }
722                                };
723
724                                upstream_table_reader = UpstreamTableReader::new(
725                                    self.external_table.clone(),
726                                    table_reader,
727                                );
728
729                                tracing::info!(
730                                    %table_id,
731                                    upstream_table_name,
732                                    "CDC table reader rebuilt successfully"
733                                );
734
735                                continue 'backfill_loop;
736                            }
737                            SnapshotAttemptState::Reading => {
738                                unreachable!(
739                                    "backfill stream must not end while the snapshot attempt is still reading"
740                                );
741                            }
742                        }
743                    };
744
745                    if actor_cdc_offset_high
746                        .as_ref()
747                        .is_none_or(|cur| cur < &split_cdc_offset_high)
748                    {
749                        actor_cdc_offset_high = Some(split_cdc_offset_high.clone());
750                    }
751
752                    // Mark current split backfill as finished. The state will be persisted by next barrier.
753                    state_impl
754                        .mutate_state(
755                            split.split_id,
756                            true,
757                            durable_row_count,
758                            split_cdc_offset_low.clone(),
759                            Some(split_cdc_offset_high),
760                        )
761                        .await?;
762
763                    extend_backfill_progress(
764                        &mut should_report_actor_backfill_progress,
765                        split.split_id,
766                    );
767                }
768
769                upstream_table_reader.disconnect().await?;
770            }
771            tracing::info!(
772                %table_id,
773                upstream_table_name,
774                "CdcBackfill has already finished and will forward messages directly to the downstream"
775            );
776
777            let mut should_report_actor_backfill_done = false;
778            // After backfill progress finished
779            // we can forward messages directly to the downstream,
780            // as backfill is finished.
781            #[for_await]
782            for msg in &mut upstream {
783                let msg = msg?;
784                match msg {
785                    Message::Barrier(barrier) => {
786                        state_impl.commit_state(barrier.epoch).await?;
787                        if is_reset_barrier(&barrier, self.actor_ctx.id) {
788                            next_reset_barrier = Some(barrier);
789                            continue 'with_cdc_table_snapshot_splits;
790                        }
791                        if let Some(split_range) = should_report_actor_backfill_progress.take()
792                            && let Some(ref progress) = self.progress
793                        {
794                            progress.update(
795                                self.actor_ctx.fragment_id,
796                                self.actor_ctx.id,
797                                barrier.epoch,
798                                generation.expect(
799                                    "should have set generation when having progress to report",
800                                ),
801                                split_range,
802                            );
803                        }
804                        if should_report_actor_backfill_done {
805                            should_report_actor_backfill_done = false;
806                            assert!(!actor_snapshot_splits.is_empty());
807                            if let Some(ref progress) = self.progress {
808                                progress.finish(
809                                    self.actor_ctx.fragment_id,
810                                    self.actor_ctx.id,
811                                    barrier.epoch,
812                                    generation.expect(
813                                        "should have set generation when having progress to report",
814                                    ),
815                                    (
816                                        actor_snapshot_splits[0].split_id,
817                                        actor_snapshot_splits[actor_snapshot_splits.len() - 1]
818                                            .split_id,
819                                    ),
820                                );
821                            }
822                        }
823                        yield Message::Barrier(barrier);
824                    }
825                    Message::Chunk(chunk) => {
826                        if actor_snapshot_splits.is_empty() || !chunk.has_visible_rows() {
827                            continue;
828                        }
829
830                        let chunk_cdc_offset =
831                            get_cdc_chunk_last_offset(&offset_parse_func, &chunk)?;
832                        // // TODO(zw): re-enable
833                        // if *self.external_table.table_type() == ExternalCdcTableType::Postgres
834                        //     && let Some(cur) = actor_cdc_offset_low.as_ref()
835                        //     && let Some(ref chunk_offset) = chunk_cdc_offset
836                        //     && *chunk_offset < *cur
837                        // {
838                        //     continue;
839                        // }
840
841                        // should_report_actor_backfill_done is set to true at most once.
842                        if let Some(high) = actor_cdc_offset_high.as_ref() {
843                            if state_impl.is_legacy_state() {
844                                // Since the legacy state does not track CDC offsets, report backfill completion immediately.
845                                actor_cdc_offset_high = None;
846                                should_report_actor_backfill_done = true;
847                            } else if let Some(ref chunk_offset) = chunk_cdc_offset
848                                && *chunk_offset >= *high
849                            {
850                                // Report backfill completion once the latest CDC offset exceeds the highest offset tracked during the backfill.
851                                actor_cdc_offset_high = None;
852                                should_report_actor_backfill_done = true;
853                            }
854                        }
855                        let chunk = mapping_chunk(chunk, &self.output_indices);
856                        if let Some(filtered_chunk) = filter_stream_chunk(
857                            chunk,
858                            &current_actor_bounds,
859                            snapshot_split_column_in_output_index,
860                        ) {
861                            yield Message::Chunk(filtered_chunk);
862                        }
863                    }
864                    msg @ Message::Watermark(_) => {
865                        if let Some(msg) = mapping_message(msg, &self.output_indices) {
866                            yield msg;
867                        }
868                    }
869                }
870            }
871        }
872    }
873}
874
875/// Splits CDC rows into chunks to forward immediately or buffer for replay.
876/// Returns `None` for either result when it contains no rows.
877///
878/// Rows in the active split are always buffered because later snapshot rows may overwrite them.
879///
880/// Rows in inactive splits are routed according to their durable snapshot progress:
881/// - not started: discard, because a future snapshot will observe the latest state;
882/// - finished: forward, because no future snapshot will cover the change;
883/// - partially written: forward, because some rows may already exist downstream and, without a
884///   cursor, we cannot determine which side of the durable snapshot progress contains this row.
885fn route_cdc_chunk(
886    chunk: StreamChunk,
887    splits: &[CdcTableSnapshotSplit],
888    states: &[CdcStateRecord],
889    current_split_idx: usize,
890    snapshot_split_column_index: usize,
891) -> (Option<StreamChunk>, Option<StreamChunk>) {
892    let mut forwarded = BitmapBuilder::zeroed(chunk.capacity());
893    let mut buffered = BitmapBuilder::zeroed(chunk.capacity());
894
895    for (_, row) in chunk.rows() {
896        let split_key = row.datum_at(snapshot_split_column_index);
897
898        let Ok(split_idx) = splits.binary_search_by(|split| {
899            let right_bound_le_key = !is_rightmost_bound(&split.right_bound_exclusive)
900                && cmp_datum(
901                    split.right_bound_exclusive.datum_at(0),
902                    split_key,
903                    OrderType::ascending_nulls_first(),
904                )
905                .is_le();
906
907            let left_bound_gt_key = !is_leftmost_bound(&split.left_bound_inclusive)
908                && cmp_datum(
909                    split.left_bound_inclusive.datum_at(0),
910                    split_key,
911                    OrderType::ascending_nulls_first(),
912                )
913                .is_gt();
914
915            if right_bound_le_key {
916                // The split is entirely before the key, so search to the right.
917                std::cmp::Ordering::Less
918            } else if left_bound_gt_key {
919                // The split is entirely after the key, so search to the left.
920                std::cmp::Ordering::Greater
921            } else {
922                // The split contains the key: left <= key < right.
923                std::cmp::Ordering::Equal
924            }
925        }) else {
926            // The key is outside the assigned split ranges or lies in a gap.
927            continue;
928        };
929
930        // Buffer rows in the active split for replay after any later snapshot output.
931        if split_idx == current_split_idx {
932            buffered.set(row.index(), true);
933            continue;
934        }
935
936        let state = &states[split_idx];
937        // A split before the active split is finished by construction. Splits after it may also
938        // be finished or partially written after scaling, for example
939        // [finished, active, finished, partially written, not started].
940        let is_completed = split_idx < current_split_idx || state.is_finished;
941        let is_partially_completed = state.row_count > 0;
942        if is_completed || is_partially_completed {
943            forwarded.set(row.index(), true);
944        }
945
946        // Otherwise leave both bits unset. The split has no durable snapshot output, so its future
947        // full snapshot will cover the change.
948    }
949
950    let forwarded = forwarded.finish();
951    let forwarded_chunk = forwarded
952        .any()
953        .then(|| chunk.clone_with_vis(forwarded).compact_vis());
954
955    let buffered = buffered.finish();
956    let buffered_chunk = buffered
957        .any()
958        .then(|| chunk.clone_with_vis(buffered).compact_vis());
959
960    (forwarded_chunk, buffered_chunk)
961}
962
963fn extend_backfill_progress(progress: &mut Option<(i64, i64)>, split_id: i64) {
964    if let Some((_, right)) = progress {
965        assert!(*right < split_id);
966        *right = split_id;
967    } else {
968        *progress = Some((split_id, split_id));
969    }
970}
971
972/// Keep rows whose snapshot split-column value falls within `bound`'s half-open range
973/// `[left, right)`, preserving their operations and relative order through a visibility bitmap.
974/// Returns `None` when no bounds are supplied or no visible rows fall within the range.
975///
976/// For example, filtering split keys `[50, 100, 150, 200]` with bounds `[100, 200)` keeps
977/// `[100, 150]`: the left bound is inclusive and the right bound is exclusive.
978fn filter_stream_chunk(
979    chunk: StreamChunk,
980    bound: &Option<(OwnedRow, OwnedRow)>,
981    snapshot_split_column_index: usize,
982) -> Option<StreamChunk> {
983    let Some((left, right)) = bound else {
984        return None;
985    };
986    assert_eq!(left.len(), 1, "multiple split columns is not supported yet");
987    assert_eq!(
988        right.len(),
989        1,
990        "multiple split columns is not supported yet"
991    );
992    let left_split_key = left.datum_at(0);
993    let right_split_key = right.datum_at(0);
994    let is_leftmost_bound = is_leftmost_bound(left);
995    let is_rightmost_bound = is_rightmost_bound(right);
996    if is_leftmost_bound && is_rightmost_bound {
997        return chunk.has_visible_rows().then_some(chunk);
998    }
999    let mut new_bitmap = BitmapBuilder::with_capacity(chunk.capacity());
1000    let (ops, columns, visibility) = chunk.into_inner();
1001    for (row_split_key, v) in columns[snapshot_split_column_index]
1002        .iter()
1003        .zip_eq_fast(visibility.iter())
1004    {
1005        if !v {
1006            new_bitmap.append(false);
1007            continue;
1008        }
1009        let mut is_in_range = true;
1010        if !is_leftmost_bound {
1011            is_in_range = cmp_datum(
1012                row_split_key,
1013                left_split_key,
1014                OrderType::ascending_nulls_first(),
1015            )
1016            .is_ge();
1017        }
1018        if is_in_range && !is_rightmost_bound {
1019            is_in_range = cmp_datum(
1020                row_split_key,
1021                right_split_key,
1022                OrderType::ascending_nulls_first(),
1023            )
1024            .is_lt();
1025        }
1026        if !is_in_range {
1027            tracing::trace!(?row_split_key, ?left_split_key, ?right_split_key, snapshot_split_column_index, data_type = ?columns[snapshot_split_column_index].data_type(), "filter out row")
1028        }
1029        new_bitmap.append(is_in_range);
1030    }
1031
1032    let visibility = new_bitmap.finish();
1033
1034    visibility
1035        .any()
1036        .then_some(StreamChunk::with_visibility(ops, columns, visibility))
1037}
1038
1039// has no left bound, e.g. [-inf, N)
1040fn is_leftmost_bound(row: &OwnedRow) -> bool {
1041    row.iter().all(|d| d.is_none())
1042}
1043
1044// has no right bound, e.g. [N, inf)
1045fn is_rightmost_bound(row: &OwnedRow) -> bool {
1046    row.iter().all(|d| d.is_none())
1047}
1048
1049impl<S: StateStore> Execute for ParallelizedCdcBackfillExecutor<S> {
1050    fn execute(self: Box<Self>) -> BoxedMessageStream {
1051        self.execute_inner().boxed()
1052    }
1053}
1054
1055fn extends_current_actor_bound(
1056    current: &mut Option<(OwnedRow, OwnedRow)>,
1057    split: &CdcTableSnapshotSplit,
1058) {
1059    if current.is_none() {
1060        *current = Some((
1061            split.left_bound_inclusive.clone(),
1062            split.right_bound_exclusive.clone(),
1063        ));
1064    } else {
1065        current.as_mut().unwrap().1 = split.right_bound_exclusive.clone();
1066    }
1067}
1068
1069fn is_reset_barrier(barrier: &Barrier, actor_id: ActorId) -> bool {
1070    match barrier.mutation.as_deref() {
1071        Some(Mutation::Update(update)) => update
1072            .actor_cdc_table_snapshot_splits
1073            .splits
1074            .contains_key(&actor_id),
1075        _ => false,
1076    }
1077}
1078
1079fn assert_consecutive_splits(actor_snapshot_splits: &[CdcTableSnapshotSplit]) {
1080    for i in 1..actor_snapshot_splits.len() {
1081        assert_eq!(
1082            actor_snapshot_splits[i].split_id,
1083            actor_snapshot_splits[i - 1].split_id + 1,
1084            "{:?}",
1085            actor_snapshot_splits
1086        );
1087        assert!(
1088            cmp_datum(
1089                actor_snapshot_splits[i - 1]
1090                    .right_bound_exclusive
1091                    .datum_at(0),
1092                actor_snapshot_splits[i].right_bound_exclusive.datum_at(0),
1093                OrderType::ascending_nulls_last(),
1094            )
1095            .is_lt()
1096        );
1097    }
1098}
1099
1100#[cfg(test)]
1101mod tests {
1102    use std::collections::BTreeMap;
1103    use std::sync::Arc;
1104    use std::time::Duration;
1105
1106    use futures::StreamExt;
1107    use risingwave_common::array::StreamChunk;
1108    use risingwave_common::catalog::{
1109        CdcKeyComparison, ColumnDesc, ColumnId, Field, Schema, TableId,
1110    };
1111    use risingwave_common::row::{OwnedRow, Row};
1112    use risingwave_common::types::{DataType, ScalarImpl};
1113    use risingwave_common::util::epoch::{EpochExt, test_epoch};
1114    use risingwave_common::util::sort_util::OrderType;
1115    use risingwave_connector::source::CdcTableSnapshotSplitRaw;
1116    use risingwave_connector::source::cdc::external::{
1117        ExternalCdcTableType, ExternalTableConfig, SchemaTableName,
1118    };
1119    use risingwave_connector::source::cdc::{
1120        CdcScanOptions, CdcTableSnapshotSplitAssignmentWithGeneration,
1121    };
1122    use risingwave_storage::memory::MemoryStateStore;
1123
1124    use super::*;
1125    use crate::common::table::state_table::StateTable;
1126    use crate::common::table::test_utils::gen_pbtable;
1127    use crate::executor::monitor::StreamingMetrics;
1128    use crate::executor::test_utils::MockSource;
1129    use crate::executor::{AddMutation, Execute, Mutation};
1130
1131    async fn create_parallel_cdc_state_table(
1132        store: MemoryStateStore,
1133    ) -> StateTable<MemoryStateStore> {
1134        let state_schema = Schema::new(vec![
1135            Field::with_name(DataType::Int64, "split_id"),
1136            Field::with_name(DataType::Boolean, "backfill_finished"),
1137            Field::with_name(DataType::Int64, "row_count"),
1138            Field::with_name(DataType::Jsonb, "cdc_offset_low"),
1139            Field::with_name(DataType::Jsonb, "cdc_offset_high"),
1140        ]);
1141        let column_descs = state_schema
1142            .fields
1143            .iter()
1144            .enumerate()
1145            .map(|(idx, field)| {
1146                ColumnDesc::unnamed(ColumnId::new(idx as i32), field.data_type.clone())
1147            })
1148            .collect();
1149
1150        StateTable::from_table_catalog(
1151            &gen_pbtable(
1152                TableId::new(0x42),
1153                column_descs,
1154                vec![OrderType::ascending()],
1155                vec![0],
1156                0,
1157            ),
1158            store,
1159            None,
1160        )
1161        .await
1162    }
1163
1164    #[tokio::test(start_paused = true)]
1165    async fn test_rebuilds_reader_after_snapshot_error() {
1166        let (mut tx, source) = MockSource::channel();
1167
1168        let source = source.into_executor(
1169            Schema::new(vec![
1170                Field::unnamed(DataType::Jsonb),
1171                Field::unnamed(DataType::Varchar),
1172            ]),
1173            vec![0],
1174        );
1175        let external_table = ExternalStorageTable::new(
1176            TableId::new(1234),
1177            SchemaTableName {
1178                schema_name: "public".to_owned(),
1179                table_name: "mock_table".to_owned(),
1180            },
1181            "mydb".to_owned(),
1182            ExternalTableConfig::default(),
1183            ExternalCdcTableType::Mock,
1184            Schema::new(vec![
1185                Field::with_name(DataType::Int64, "id"),
1186                Field::with_name(DataType::Float64, "price"),
1187            ]),
1188            vec![OrderType::ascending()],
1189            Some(vec![CdcKeyComparison::Native]),
1190            vec![0],
1191        )
1192        .with_mock_snapshot_errors([1, 0]);
1193        let external_table_for_assertion = external_table.clone();
1194
1195        let state_table = create_parallel_cdc_state_table(MemoryStateStore::new()).await;
1196
1197        let actor_id = 0x1a.into();
1198        let mut executor = ParallelizedCdcBackfillExecutor::new(
1199            ActorContext::for_test(actor_id),
1200            external_table,
1201            source,
1202            vec![0, 1],
1203            vec![
1204                ColumnDesc::named("id", ColumnId::new(1), DataType::Int64),
1205                ColumnDesc::named("price", ColumnId::new(2), DataType::Float64),
1206            ],
1207            Arc::new(StreamingMetrics::unused()),
1208            state_table,
1209            Some(4),
1210            CdcScanOptions {
1211                backfill_parallelism: 1,
1212                backfill_num_rows_per_split: 100,
1213                ..Default::default()
1214            },
1215            BTreeMap::new(),
1216            None,
1217        )
1218        .boxed()
1219        .execute();
1220
1221        let mut curr_epoch = test_epoch(1);
1222        let snapshot_splits = [(
1223            actor_id,
1224            (
1225                vec![CdcTableSnapshotSplitRaw {
1226                    split_id: 1,
1227                    left_bound_inclusive: OwnedRow::new(vec![Some(ScalarImpl::Int64(1))])
1228                        .value_serialize(),
1229                    right_bound_exclusive: OwnedRow::new(vec![Some(ScalarImpl::Int64(10))])
1230                        .value_serialize(),
1231                }],
1232                10,
1233            ),
1234        )]
1235        .into_iter()
1236        .collect();
1237
1238        // Assign the split to this actor on the initial barrier.
1239        tx.send_barrier(
1240            Barrier::new_test_barrier(curr_epoch).with_mutation(Mutation::Add(AddMutation {
1241                actor_cdc_table_snapshot_splits: CdcTableSnapshotSplitAssignmentWithGeneration {
1242                    splits: snapshot_splits,
1243                },
1244                ..Default::default()
1245            })),
1246        );
1247
1248        assert!(matches!(
1249            executor.next().await.unwrap().unwrap(),
1250            Message::Barrier(Barrier { epoch, .. }) if epoch.curr == curr_epoch
1251        ));
1252
1253        // This poll creates reader 1 and starts the snapshot, consuming its injected error. The
1254        // executor then keeps polling the CDC upstream until a barrier provides a safe recovery
1255        // boundary.
1256        assert!(
1257            tokio::time::timeout(Duration::from_millis(50), executor.next())
1258                .await
1259                .is_err()
1260        );
1261        assert_eq!(external_table_for_assertion.mock_reader_create_count(), 1);
1262
1263        curr_epoch.inc_epoch();
1264        tx.push_barrier(curr_epoch, false);
1265        assert!(matches!(
1266            executor.next().await.unwrap().unwrap(),
1267            Message::Barrier(Barrier { epoch, .. }) if epoch.curr == curr_epoch
1268        ));
1269
1270        // Resuming after the barrier creates reader 2 and produces a snapshot chunk.
1271        assert!(matches!(
1272            executor.next().await.unwrap().unwrap(),
1273            Message::Chunk(_)
1274        ));
1275
1276        assert_eq!(external_table_for_assertion.mock_reader_create_count(), 2);
1277    }
1278
1279    #[test]
1280    fn test_filter_stream_chunk() {
1281        use risingwave_common::array::StreamChunkTestExt;
1282        let chunk = StreamChunk::from_pretty(
1283            "  I I
1284             + 1 6
1285             - 2 .
1286            U- 3 7
1287            U+ 4 .",
1288        );
1289        let bound = None;
1290        let c = filter_stream_chunk(chunk.clone(), &bound, 0);
1291        assert!(c.is_none());
1292
1293        let bound = Some((OwnedRow::new(vec![None]), OwnedRow::new(vec![None])));
1294        let c = filter_stream_chunk(chunk.clone(), &bound, 0);
1295        assert_eq!(c.unwrap().compact_vis(), chunk);
1296
1297        let bound = Some((
1298            OwnedRow::new(vec![None]),
1299            OwnedRow::new(vec![Some(ScalarImpl::Int64(3))]),
1300        ));
1301        let c = filter_stream_chunk(chunk.clone(), &bound, 0);
1302        assert_eq!(
1303            c.unwrap().compact_vis(),
1304            StreamChunk::from_pretty(
1305                "  I I
1306             + 1 6
1307             - 2 .",
1308            )
1309        );
1310
1311        let bound = Some((
1312            OwnedRow::new(vec![Some(ScalarImpl::Int64(3))]),
1313            OwnedRow::new(vec![None]),
1314        ));
1315        let c = filter_stream_chunk(chunk.clone(), &bound, 0);
1316        assert_eq!(
1317            c.unwrap().compact_vis(),
1318            StreamChunk::from_pretty(
1319                "  I I
1320            U- 3 7
1321            U+ 4 .",
1322            )
1323        );
1324
1325        let bound = Some((
1326            OwnedRow::new(vec![Some(ScalarImpl::Int64(2))]),
1327            OwnedRow::new(vec![Some(ScalarImpl::Int64(4))]),
1328        ));
1329        let c = filter_stream_chunk(chunk.clone(), &bound, 0);
1330        assert_eq!(
1331            c.unwrap().compact_vis(),
1332            StreamChunk::from_pretty(
1333                "  I I
1334             - 2 .
1335            U- 3 7",
1336            )
1337        );
1338
1339        // Test NULL value.
1340        let bound = None;
1341        let c = filter_stream_chunk(chunk.clone(), &bound, 1);
1342        assert!(c.is_none());
1343
1344        let bound = Some((OwnedRow::new(vec![None]), OwnedRow::new(vec![None])));
1345        let c = filter_stream_chunk(chunk.clone(), &bound, 1);
1346        assert_eq!(c.unwrap().compact_vis(), chunk);
1347
1348        let bound = Some((
1349            OwnedRow::new(vec![None]),
1350            OwnedRow::new(vec![Some(ScalarImpl::Int64(7))]),
1351        ));
1352        let c = filter_stream_chunk(chunk.clone(), &bound, 1);
1353        assert_eq!(
1354            c.unwrap().compact_vis(),
1355            StreamChunk::from_pretty(
1356                "  I I
1357             + 1 6
1358             - 2 .
1359            U+ 4 .",
1360            )
1361        );
1362
1363        let bound = Some((
1364            OwnedRow::new(vec![Some(ScalarImpl::Int64(7))]),
1365            OwnedRow::new(vec![None]),
1366        ));
1367        let c = filter_stream_chunk(chunk, &bound, 1);
1368        assert_eq!(
1369            c.unwrap().compact_vis(),
1370            StreamChunk::from_pretty(
1371                "  I I
1372            U- 3 7",
1373            )
1374        );
1375    }
1376
1377    #[test]
1378    fn test_route_cdc_chunk() {
1379        use risingwave_common::array::StreamChunkTestExt;
1380
1381        let bound = |value: i64| OwnedRow::new(vec![Some(value.into())]);
1382        let splits = [(0, 100), (100, 200), (200, 300), (300, 400), (400, 500)]
1383            .into_iter()
1384            .enumerate()
1385            .map(|(idx, (left, right))| CdcTableSnapshotSplit {
1386                split_id: idx as i64,
1387                left_bound_inclusive: bound(left),
1388                right_bound_exclusive: bound(right),
1389            })
1390            .collect_vec();
1391
1392        // [finished, active, finished, partially written, not started]
1393        let states = [
1394            CdcStateRecord {
1395                is_finished: true,
1396                ..Default::default()
1397            },
1398            CdcStateRecord {
1399                row_count: 1,
1400                ..Default::default()
1401            },
1402            CdcStateRecord {
1403                is_finished: true,
1404                ..Default::default()
1405            },
1406            CdcStateRecord {
1407                row_count: 1,
1408                ..Default::default()
1409            },
1410            CdcStateRecord::default(),
1411        ];
1412
1413        // splits: [0, 100), [100, 200), [200, 300), [300, 400), [400, 500)
1414        // status: finished, active,       finished,     partial,      not started
1415        //
1416        // chunk       expected     split         status
1417        // + -1  1     dropped      outside       N/A
1418        // + 50  5     forwarded    [0, 100)      finished
1419        // + 150 15    buffered     [100, 200)    active
1420        // - 151 16    buffered     [100, 200)    active
1421        // - 250 25    forwarded    [200, 300)    finished
1422        // - 350 35    forwarded    [300, 400)    partially written
1423        // + 450 45    dropped      [400, 500)    not started
1424        // + 500 50    dropped      outside       N/A
1425        let chunk = StreamChunk::from_pretty(
1426            "  I I
1427             + -1 1
1428             + 50 5
1429             + 150 15
1430             - 151 16
1431             - 250 25
1432             - 350 35
1433             + 450 45
1434             + 500 50",
1435        );
1436        let (forwarded_chunk, buffered_chunk) = route_cdc_chunk(chunk, &splits, &states, 1, 0);
1437
1438        assert_eq!(
1439            forwarded_chunk.unwrap(),
1440            StreamChunk::from_pretty(
1441                "  I I
1442                 + 50 5
1443                 - 250 25
1444                 - 350 35",
1445            )
1446        );
1447
1448        assert_eq!(
1449            buffered_chunk.unwrap(),
1450            StreamChunk::from_pretty(
1451                "  I I
1452                 + 150 15
1453                 - 151 16",
1454            )
1455        );
1456    }
1457}