risingwave_stream/executor/source/source_backfill_executor.rs
1// Copyright 2024 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::cmp::Ordering;
16use std::collections::{HashMap, HashSet};
17use std::time::Instant;
18
19use anyhow::anyhow;
20use either::Either;
21use futures::stream::{PollNext, select_with_strategy};
22use itertools::Itertools;
23use risingwave_common::bitmap::BitmapBuilder;
24use risingwave_common::catalog::ColumnId;
25use risingwave_common::id::SourceId;
26use risingwave_common::metrics::{GLOBAL_ERROR_METRICS, LabelGuardedIntCounter};
27use risingwave_common::system_param::local_manager::SystemParamsReaderRef;
28use risingwave_common::system_param::reader::SystemParamsRead;
29use risingwave_common::types::JsonbVal;
30use risingwave_common::util::epoch::EpochPair;
31use risingwave_connector::source::reader::desc::{SourceDesc, SourceDescBuilder};
32use risingwave_connector::source::{
33 BackfillInfo, BoxSourceReaderEventStream, SourceContext, SourceCtrlOpts, SourceReaderEvent,
34 SplitId, SplitImpl, SplitMetaData,
35};
36use risingwave_hummock_sdk::HummockReadEpoch;
37use risingwave_pb::common::ThrottleType;
38use risingwave_storage::store::TryWaitEpochOptions;
39use serde::{Deserialize, Serialize};
40use thiserror_ext::AsReport;
41
42use super::executor_core::StreamSourceCore;
43use super::source_backfill_state_table::BackfillStateTableHandler;
44use super::{apply_rate_limit_to_source_reader_event, get_split_offset_col_idx};
45use crate::common::rate_limit::limited_chunk_size;
46use crate::executor::UpdateMutation;
47use crate::executor::prelude::*;
48use crate::executor::source::source_executor::WAIT_BARRIER_MULTIPLE_TIMES;
49use crate::task::CreateMviewProgressReporter;
50
51#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
52pub enum BackfillState {
53 /// `None` means not started yet. It's the initial state.
54 /// XXX: perhaps we can also set to low-watermark instead of `None`
55 Backfilling(Option<String>),
56 /// Backfill is stopped at this offset (inclusive). Source needs to filter out messages before this offset.
57 SourceCachingUp(String),
58 Finished,
59}
60pub type BackfillStates = HashMap<SplitId, BackfillStateWithProgress>;
61
62/// Only `state` field is the real state for fail-over.
63/// Other fields are for observability (but we still need to persist them).
64#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
65pub struct BackfillStateWithProgress {
66 pub state: BackfillState,
67 pub num_consumed_rows: u64,
68 /// The latest offset from upstream (inclusive). After we reach this offset, we can stop backfilling.
69 /// This is initialized with the latest available offset in the connector (if the connector provides the ability to fetch it)
70 /// so that we can finish backfilling even when upstream doesn't emit any data.
71 pub target_offset: Option<String>,
72}
73
74impl BackfillStateWithProgress {
75 pub fn encode_to_json(self) -> JsonbVal {
76 serde_json::to_value(self).unwrap().into()
77 }
78
79 pub fn restore_from_json(value: JsonbVal) -> anyhow::Result<Self> {
80 serde_json::from_value(value.take()).map_err(|e| anyhow!(e))
81 }
82}
83
84pub struct SourceBackfillExecutor<S: StateStore> {
85 pub inner: SourceBackfillExecutorInner<S>,
86 /// Upstream changelog stream which may contain metadata columns, e.g. `_rw_offset`
87 pub input: Executor,
88}
89
90pub struct SourceBackfillExecutorInner<S: StateStore> {
91 actor_ctx: ActorContextRef,
92 info: ExecutorInfo,
93
94 /// Streaming source for external
95 source_id: SourceId,
96 source_name: String,
97 column_ids: Vec<ColumnId>,
98 source_desc_builder: Option<SourceDescBuilder>,
99 backfill_state_store: BackfillStateTableHandler<S>,
100
101 /// Metrics for monitor.
102 metrics: Arc<StreamingMetrics>,
103 source_split_change_count: LabelGuardedIntCounter,
104
105 // /// Receiver of barrier channel.
106 // barrier_receiver: Option<UnboundedReceiver<Barrier>>,
107 /// System parameter reader to read barrier interval
108 system_params: SystemParamsReaderRef,
109
110 /// Rate limit in rows/s.
111 rate_limit_rps: Option<u32>,
112
113 progress: CreateMviewProgressReporter,
114}
115
116/// Local variables used in the backfill stage.
117///
118/// See <https://github.com/risingwavelabs/risingwave/issues/18299> for a state diagram about how it works.
119///
120/// Note: all off the fields should contain all available splits, and we can `unwrap()` safely when `get()`.
121#[derive(Debug)]
122struct BackfillStage {
123 states: BackfillStates,
124 /// A copy of all splits (incl unfinished and finished ones) assigned to the actor.
125 ///
126 /// Note: the offsets are not updated. Should use `state`'s offset to update before using it (`get_latest_unfinished_splits`).
127 splits: Vec<SplitImpl>,
128}
129
130enum ApplyMutationAfterBarrier {
131 SourceChangeSplit {
132 target_splits: Vec<SplitImpl>,
133 should_trim_state: bool,
134 },
135 ConnectorPropsChange,
136}
137
138impl BackfillStage {
139 fn total_backfilled_rows(&self) -> u64 {
140 self.states.values().map(|s| s.num_consumed_rows).sum()
141 }
142
143 fn debug_assert_consistent(&self) {
144 if cfg!(debug_assertions) {
145 let all_splits: HashSet<_> = self.splits.iter().map(|split| split.id()).collect();
146 assert_eq!(
147 self.states.keys().cloned().collect::<HashSet<_>>(),
148 all_splits
149 );
150 }
151 }
152
153 /// Get unfinished splits with latest offsets according to the backfill states.
154 fn get_latest_unfinished_splits(&self) -> StreamExecutorResult<Vec<SplitImpl>> {
155 let mut unfinished_splits = Vec::new();
156 for split in &self.splits {
157 let state = &self.states.get(split.id().as_ref()).unwrap().state;
158 match state {
159 BackfillState::Backfilling(Some(offset)) => {
160 let mut updated_split = split.clone();
161 updated_split.update_in_place(offset.clone())?;
162 unfinished_splits.push(updated_split);
163 }
164 BackfillState::Backfilling(None) => unfinished_splits.push(split.clone()),
165 BackfillState::SourceCachingUp(_) | BackfillState::Finished => {}
166 }
167 }
168 Ok(unfinished_splits)
169 }
170
171 /// Updates backfill states and `target_offsets` from upstream `SourceExecutor` chunks, and
172 /// returns whether the row is visible.
173 ///
174 /// Note that the online catch-up logic intentionally relies on the upstream chunk stream
175 /// carrying split/offset columns. We do not reconcile live upstream progress from source state
176 /// tables here, because source backfill is designed to advance according to the upstream data
177 /// stream instead of a side channel.
178 fn handle_upstream_row(&mut self, split_id: &str, offset: &str) -> bool {
179 let mut vis = false;
180 let state = self.states.get_mut(split_id).unwrap();
181 let state_inner = &mut state.state;
182 match state_inner {
183 BackfillState::Backfilling(None) => {
184 // backfilling for this split is not started yet. Ignore this row
185 }
186 BackfillState::Backfilling(Some(backfill_offset)) => {
187 match compare_kafka_offset(backfill_offset, offset) {
188 Ordering::Less => {
189 // continue backfilling. Ignore this row
190 }
191 Ordering::Equal => {
192 // backfilling for this split is finished just right.
193 *state_inner = BackfillState::Finished;
194 }
195 Ordering::Greater => {
196 // backfilling for this split produced more data than current source's progress.
197 // We should stop backfilling, and filter out rows from upstream with offset <= backfill_offset.
198 *state_inner = BackfillState::SourceCachingUp(backfill_offset.clone());
199 }
200 }
201 }
202 BackfillState::SourceCachingUp(backfill_offset) => {
203 match compare_kafka_offset(backfill_offset, offset) {
204 Ordering::Less => {
205 // Source caught up, but doesn't contain the last backfilled row.
206 // This may happen e.g., if Kafka performed compaction.
207 vis = true;
208 *state_inner = BackfillState::Finished;
209 }
210 Ordering::Equal => {
211 // Source just caught up with backfilling.
212 *state_inner = BackfillState::Finished;
213 }
214 Ordering::Greater => {
215 // Source is still behind backfilling.
216 }
217 }
218 }
219 BackfillState::Finished => {
220 vis = true;
221 // This split's backfilling is finished, we are waiting for other splits
222 }
223 }
224 if matches!(state_inner, BackfillState::Backfilling(_)) {
225 state.target_offset = Some(offset.to_owned());
226 }
227 if vis {
228 debug_assert_eq!(*state_inner, BackfillState::Finished);
229 }
230 vis
231 }
232
233 /// Updates backfill states and returns whether the row backfilled from external system is visible.
234 fn handle_backfill_row(&mut self, split_id: &str, offset: &str) -> bool {
235 let state = self.states.get_mut(split_id).unwrap();
236 state.num_consumed_rows += 1;
237 let state_inner = &mut state.state;
238 match state_inner {
239 BackfillState::Backfilling(_old_offset) => {
240 if let Some(target_offset) = &state.target_offset
241 && compare_kafka_offset(offset, target_offset).is_ge()
242 {
243 // Note1: If target_offset = offset, it seems we can mark the state as Finished without waiting for upstream to catch up
244 // and dropping duplicated messages.
245 // But it's not true if target_offset is fetched from other places, like Kafka high watermark.
246 // In this case, upstream hasn't reached the target_offset yet.
247 //
248 // Note2: after this, all following rows in the current chunk will be invisible.
249 //
250 // Note3: if target_offset is None (e.g., when upstream doesn't emit messages at all), we will
251 // keep backfilling.
252 *state_inner = BackfillState::SourceCachingUp(offset.to_owned());
253 } else {
254 *state_inner = BackfillState::Backfilling(Some(offset.to_owned()));
255 }
256 true
257 }
258 BackfillState::SourceCachingUp(_) | BackfillState::Finished => {
259 // backfilling stopped. ignore
260 false
261 }
262 }
263 }
264
265 /// Updates backfill state with split progress emitted by the backfill reader when there are no
266 /// corresponding visible rows.
267 ///
268 /// This is needed for connectors such as Kafka under `read_committed`, where the reader can
269 /// reach a later offset because of EOF/control records without yielding a data chunk. This
270 /// supplements `handle_backfill_row`, but does not replace the upstream-chunk-based progress
271 /// tracking in `handle_upstream_row`.
272 fn handle_backfill_progress(&mut self, split_id: &str, offset: &str) {
273 let Some(state) = self.states.get_mut(split_id) else {
274 return;
275 };
276 let state_inner = &mut state.state;
277 match state_inner {
278 BackfillState::Backfilling(_old_offset) => {
279 if let Some(target_offset) = &state.target_offset
280 && compare_kafka_offset(offset, target_offset).is_ge()
281 {
282 *state_inner = BackfillState::SourceCachingUp(offset.to_owned());
283 } else {
284 *state_inner = BackfillState::Backfilling(Some(offset.to_owned()));
285 }
286 }
287 // The backfill stopped emitting at `SourceCachingUp`: rows the reader read after that
288 // were dropped, so the upstream must still emit them. Moving the offset forward here
289 // would make the upstream drop them too.
290 BackfillState::SourceCachingUp(_) | BackfillState::Finished => {}
291 }
292 }
293}
294
295impl<S: StateStore> SourceBackfillExecutorInner<S> {
296 #[expect(clippy::too_many_arguments)]
297 pub fn new(
298 actor_ctx: ActorContextRef,
299 info: ExecutorInfo,
300 stream_source_core: StreamSourceCore<S>,
301 metrics: Arc<StreamingMetrics>,
302 system_params: SystemParamsReaderRef,
303 backfill_state_store: BackfillStateTableHandler<S>,
304 rate_limit_rps: Option<u32>,
305 progress: CreateMviewProgressReporter,
306 ) -> Self {
307 let StreamSourceCore {
308 source_id,
309 source_name,
310 column_ids,
311 source_desc_builder,
312 ..
313 } = stream_source_core;
314 let source_split_change_count = metrics
315 .source_split_change_count
316 .with_guarded_label_values(&[
317 &actor_ctx.id.to_string(),
318 &source_id.to_string(),
319 &source_name,
320 &actor_ctx.fragment_id.to_string(),
321 ]);
322
323 Self {
324 actor_ctx,
325 info,
326 source_id,
327 source_name,
328 column_ids,
329 source_desc_builder,
330 backfill_state_store,
331 metrics,
332 source_split_change_count,
333 system_params,
334 rate_limit_rps,
335 progress,
336 }
337 }
338
339 async fn build_stream_source_reader(
340 &self,
341 source_desc: &SourceDesc,
342 splits: Vec<SplitImpl>,
343 ) -> StreamExecutorResult<(BoxSourceReaderEventStream, HashMap<SplitId, BackfillInfo>)> {
344 let column_ids = source_desc
345 .columns
346 .iter()
347 .map(|column_desc| column_desc.column_id)
348 .collect_vec();
349 let source_ctx = SourceContext::new(
350 self.actor_ctx.id,
351 self.source_id,
352 self.actor_ctx.fragment_id,
353 self.source_name.clone(),
354 source_desc.metrics.clone(),
355 SourceCtrlOpts {
356 chunk_size: limited_chunk_size(self.rate_limit_rps),
357 split_txn: self.rate_limit_rps.is_some(), // when rate limiting, we may split txn
358 },
359 source_desc.source.config.clone(),
360 None,
361 );
362
363 // We will check watermark to decide whether we need to backfill.
364 // e.g., when there's a Kafka topic-partition without any data,
365 // we don't need to backfill at all. But if we do not check here,
366 // the executor can only know it's finished when data coming in.
367 // For blocking DDL, this would be annoying.
368
369 let (stream, res) = source_desc
370 .source
371 .build_stream(Some(splits), column_ids, Arc::new(source_ctx), false)
372 .await
373 .map_err(StreamExecutorError::connector_error)?;
374 Ok((
375 apply_rate_limit_to_source_reader_event(stream, self.rate_limit_rps).boxed(),
376 res.backfill_info,
377 ))
378 }
379
380 #[try_stream(ok = Message, error = StreamExecutorError)]
381 async fn execute(mut self, input: Executor) {
382 let mut input = input.execute();
383
384 // Poll the upstream to get the first barrier.
385 let barrier = expect_first_barrier(&mut input).await?;
386 let first_epoch = barrier.epoch;
387 let owned_splits = barrier
388 .initial_split_assignment(self.actor_ctx.id)
389 .unwrap_or(&[])
390 .to_vec();
391
392 let mut pause_control = PauseControl::new();
393 if barrier.is_backfill_pause_on_startup(self.actor_ctx.fragment_id) {
394 pause_control.backfill_pause();
395 }
396 if barrier.is_pause_on_startup() {
397 pause_control.command_pause();
398 }
399 yield Message::Barrier(barrier);
400
401 let source_desc_builder: SourceDescBuilder = self.source_desc_builder.take().unwrap();
402 let mut source_desc = source_desc_builder
403 .build()
404 .map_err(StreamExecutorError::connector_error)?;
405
406 // source backfill only applies to kafka, so we don't need to get pulsar's `message_id_data_idx`.
407 let (Some(split_idx), Some(offset_idx), _) = get_split_offset_col_idx(&source_desc.columns)
408 else {
409 unreachable!("Partition and offset columns must be set.");
410 };
411
412 self.backfill_state_store.init_epoch(first_epoch).await?;
413
414 let mut backfill_states: BackfillStates = HashMap::new();
415 {
416 let committed_reader = self
417 .backfill_state_store
418 .new_committed_reader(first_epoch)
419 .await?;
420 for split in &owned_splits {
421 let split_id = split.id();
422 let backfill_state = committed_reader
423 .try_recover_from_state_store(&split_id)
424 .await?
425 .unwrap_or(BackfillStateWithProgress {
426 state: BackfillState::Backfilling(None),
427 num_consumed_rows: 0,
428 target_offset: None, // init with None
429 });
430 backfill_states.insert(split_id, backfill_state);
431 }
432 }
433 let mut backfill_stage = BackfillStage {
434 states: backfill_states,
435 splits: owned_splits,
436 };
437 backfill_stage.debug_assert_consistent();
438
439 let (source_chunk_reader, backfill_info) = self
440 .build_stream_source_reader(
441 &source_desc,
442 backfill_stage.get_latest_unfinished_splits()?,
443 )
444 .instrument_await("source_build_reader")
445 .await?;
446 for (split_id, info) in &backfill_info {
447 let state = backfill_stage.states.get_mut(split_id).unwrap();
448 match info {
449 BackfillInfo::NoDataToBackfill => {
450 state.state = BackfillState::Finished;
451 }
452 BackfillInfo::HasDataToBackfill { latest_offset } => {
453 // Note: later we will override it with the offset from the source message, and it's possible to become smaller than this value.
454 state.target_offset = Some(latest_offset.clone());
455 }
456 }
457 }
458 tracing::debug!(?backfill_stage, "source backfill started");
459
460 fn select_strategy(_: &mut ()) -> PollNext {
461 futures::stream::PollNext::Left
462 }
463
464 // We choose "preferring upstream" strategy here, because:
465 // - When the upstream source's workload is high (i.e., Kafka has new incoming data), it just makes backfilling slower.
466 // For chunks from upstream, they are simply dropped, so there's no much overhead.
467 // So possibly this can also affect other running jobs less.
468 // - When the upstream Source's becomes less busy, SourceBackfill can begin to catch up.
469 let mut backfill_stream = select_with_strategy(
470 input.by_ref().map(Either::Left),
471 source_chunk_reader.map(Either::Right),
472 select_strategy,
473 );
474
475 type PausedReader = Option<impl Stream>;
476 let mut paused_reader: PausedReader = None;
477
478 macro_rules! pause_reader {
479 () => {
480 if !pause_control.reader_paused {
481 let (left, right) = backfill_stream.into_inner();
482 backfill_stream = select_with_strategy(
483 left,
484 futures::stream::pending().boxed().map(Either::Right),
485 select_strategy,
486 );
487 // XXX: do we have to store the original reader? Can we simply rebuild the reader later?
488 paused_reader = Some(right);
489 pause_control.reader_paused = true;
490 }
491 };
492 }
493
494 macro_rules! resume_reader {
495 () => {
496 if pause_control.reader_paused {
497 backfill_stream = select_with_strategy(
498 input.by_ref().map(Either::Left),
499 paused_reader
500 .take()
501 .expect("should have paused reader to resume"),
502 select_strategy,
503 );
504 pause_control.reader_paused = false;
505 }
506 };
507 }
508
509 if pause_control.is_paused() {
510 pause_reader!();
511 }
512
513 let state_store = self
514 .backfill_state_store
515 .state_store()
516 .state_store()
517 .clone();
518 let table_id = self.backfill_state_store.state_store().table_id();
519 let mut state_table_initialized = false;
520 {
521 let source_backfill_row_count = self
522 .metrics
523 .source_backfill_row_count
524 .with_guarded_label_values(&[
525 &self.actor_ctx.id.to_string(),
526 &self.source_id.to_string(),
527 &self.source_name,
528 &self.actor_ctx.fragment_id.to_string(),
529 ]);
530
531 // We allow data to flow for `WAIT_BARRIER_MULTIPLE_TIMES` * `expected_barrier_latency_ms`
532 // milliseconds, considering some other latencies like network and cost in Meta.
533 let mut max_wait_barrier_time_ms = self.system_params.load().barrier_interval_ms()
534 as u128
535 * WAIT_BARRIER_MULTIPLE_TIMES;
536 let mut last_barrier_time = Instant::now();
537
538 // The main logic of the loop is in handle_upstream_row and handle_backfill_row.
539 'backfill_loop: while let Some(either) = backfill_stream.next().await {
540 match either {
541 // Upstream
542 Either::Left(msg) => {
543 let Ok(msg) = msg else {
544 let e = msg.unwrap_err();
545 tracing::error!(
546 error = ?e.as_report(),
547 source_id = %self.source_id,
548 "stream source reader error",
549 );
550 GLOBAL_ERROR_METRICS.user_source_error.report([
551 "SourceReaderError".to_owned(),
552 self.source_id.to_string(),
553 self.source_name.clone(),
554 self.actor_ctx.fragment_id.to_string(),
555 ]);
556
557 let (reader, _backfill_info) = self
558 .build_stream_source_reader(
559 &source_desc,
560 backfill_stage.get_latest_unfinished_splits()?,
561 )
562 .await?;
563
564 backfill_stream = select_with_strategy(
565 input.by_ref().map(Either::Left),
566 reader.map(Either::Right),
567 select_strategy,
568 );
569 continue;
570 };
571 match msg {
572 Message::Barrier(barrier) => {
573 last_barrier_time = Instant::now();
574
575 if pause_control.self_resume() {
576 resume_reader!();
577 }
578
579 let mut maybe_mutation = None;
580 if let Some(ref mutation) = barrier.mutation.as_deref() {
581 match mutation {
582 Mutation::Pause => {
583 // pause_reader should not be invoked consecutively more than once.
584 pause_control.command_pause();
585 pause_reader!();
586 }
587 Mutation::Resume => {
588 // pause_reader.take should not be invoked consecutively more than once.
589 if pause_control.command_resume() {
590 resume_reader!();
591 }
592 }
593 Mutation::StartFragmentBackfill { fragment_ids } => {
594 if fragment_ids.contains(&self.actor_ctx.fragment_id)
595 && pause_control.backfill_resume()
596 {
597 resume_reader!();
598 }
599 }
600 Mutation::SourceChangeSplit(actor_splits) => {
601 tracing::info!(
602 actor_splits = ?actor_splits,
603 "source change split received"
604 );
605 maybe_mutation = actor_splits
606 .get(&self.actor_ctx.id)
607 .cloned()
608 .map(|target_splits| {
609 ApplyMutationAfterBarrier::SourceChangeSplit {
610 target_splits,
611 should_trim_state: true,
612 }
613 });
614 }
615 Mutation::Update(UpdateMutation {
616 actor_splits, ..
617 }) => {
618 maybe_mutation = actor_splits
619 .get(&self.actor_ctx.id)
620 .cloned()
621 .map(|target_splits| {
622 ApplyMutationAfterBarrier::SourceChangeSplit {
623 target_splits,
624 should_trim_state: false,
625 }
626 });
627 }
628 Mutation::ConnectorPropsChange(props_change) => {
629 if let Some(props_plaintext) =
630 props_change.get(&self.source_id.as_raw_id())
631 {
632 source_desc
633 .update_reader(props_plaintext.clone())?;
634
635 maybe_mutation = Some(
636 ApplyMutationAfterBarrier::ConnectorPropsChange,
637 );
638 }
639 }
640 Mutation::Throttle(fragment_to_apply) => {
641 if let Some(entry) =
642 fragment_to_apply.get(&self.actor_ctx.fragment_id)
643 && entry.throttle_type() == ThrottleType::Backfill
644 && entry.rate_limit != self.rate_limit_rps
645 {
646 tracing::info!(
647 "updating rate limit from {:?} to {:?}",
648 self.rate_limit_rps,
649 entry.rate_limit
650 );
651 self.rate_limit_rps = entry.rate_limit;
652 // rebuild reader
653 let (reader, _backfill_info) = self
654 .build_stream_source_reader(
655 &source_desc,
656 backfill_stage
657 .get_latest_unfinished_splits()?,
658 )
659 .await?;
660
661 backfill_stream = select_with_strategy(
662 input.by_ref().map(Either::Left),
663 reader.map(Either::Right),
664 select_strategy,
665 );
666 }
667 }
668 _ => {}
669 }
670 }
671 async fn rebuild_reader_on_split_changed(
672 this: &SourceBackfillExecutorInner<impl StateStore>,
673 backfill_stage: &BackfillStage,
674 source_desc: &SourceDesc,
675 ) -> StreamExecutorResult<BoxSourceReaderEventStream>
676 {
677 // rebuild backfill_stream
678 // Note: we don't put this part in a method, due to some complex lifetime issues.
679
680 let latest_unfinished_splits =
681 backfill_stage.get_latest_unfinished_splits()?;
682 tracing::info!(
683 "actor {:?} apply source split change to {:?}",
684 this.actor_ctx.id,
685 latest_unfinished_splits
686 );
687
688 // Replace the source reader with a new one of the new state.
689 let (reader, _backfill_info) = this
690 .build_stream_source_reader(
691 source_desc,
692 latest_unfinished_splits,
693 )
694 .await?;
695
696 Ok(reader)
697 }
698
699 self.backfill_state_store
700 .set_states(backfill_stage.states.clone())
701 .await?;
702 self.backfill_state_store.commit(barrier.epoch).await?;
703
704 if self.should_report_finished(&backfill_stage.states) {
705 // drop the backfill kafka consumers
706 backfill_stream = select_with_strategy(
707 input.by_ref().map(Either::Left),
708 futures::stream::pending().boxed().map(Either::Right),
709 select_strategy,
710 );
711
712 self.progress.finish(
713 barrier.epoch,
714 backfill_stage.total_backfilled_rows(),
715 );
716
717 let barrier_epoch = barrier.epoch;
718 let is_checkpoint = barrier.is_checkpoint();
719 // yield barrier after reporting progress
720 yield Message::Barrier(barrier);
721
722 if let Some(to_apply_mutation) = maybe_mutation {
723 self.apply_split_change_after_yield_barrier(
724 barrier_epoch,
725 &mut backfill_stage,
726 to_apply_mutation,
727 )
728 .await?;
729 }
730
731 if !state_table_initialized {
732 if is_checkpoint {
733 // This is for self.backfill_finished() to be safe: wait until this actor can read all actors' written data.
734 // We wait for 2nd epoch
735 let epoch = barrier_epoch.prev;
736 tracing::info!("waiting for epoch: {}", epoch);
737 state_store
738 .try_wait_epoch(
739 HummockReadEpoch::Committed(epoch),
740 TryWaitEpochOptions { table_id },
741 )
742 .await?;
743 tracing::info!("finished waiting for epoch: {}", epoch);
744 state_table_initialized = true;
745 }
746 } else {
747 // After we reported finished, we still don't exit the loop.
748 // Because we need to handle split migration.
749 assert!(
750 state_table_initialized,
751 "state table should be initialized before checking backfill finished"
752 );
753 if self.backfill_finished(&backfill_stage.states).await? {
754 tracing::info!("source backfill finished");
755 break 'backfill_loop;
756 }
757 }
758 } else {
759 self.progress.update_for_source_backfill(
760 barrier.epoch,
761 backfill_stage.total_backfilled_rows(),
762 );
763
764 let barrier_epoch = barrier.epoch;
765 // yield barrier after reporting progress
766 yield Message::Barrier(barrier);
767
768 if let Some(to_apply_mutation) = maybe_mutation
769 && self
770 .apply_split_change_after_yield_barrier(
771 barrier_epoch,
772 &mut backfill_stage,
773 to_apply_mutation,
774 )
775 .await?
776 {
777 let reader = rebuild_reader_on_split_changed(
778 &self,
779 &backfill_stage,
780 &source_desc,
781 )
782 .await?;
783
784 backfill_stream = select_with_strategy(
785 input.by_ref().map(Either::Left),
786 reader.map(Either::Right),
787 select_strategy,
788 );
789 }
790 }
791 }
792 Message::Chunk(chunk) => {
793 // We need to iterate over all rows because there might be multiple splits in a chunk.
794 // Note: We assume offset from the source is monotonically increasing for the algorithm to work correctly.
795 let mut new_vis = BitmapBuilder::zeroed(chunk.visibility().len());
796
797 for (i, (_, row)) in chunk.rows().enumerate() {
798 let split = row.datum_at(split_idx).unwrap().into_utf8();
799 let offset = row.datum_at(offset_idx).unwrap().into_utf8();
800 let vis = backfill_stage.handle_upstream_row(split, offset);
801 new_vis.set(i, vis);
802 }
803 // emit chunk if vis is not empty. i.e., some splits finished backfilling.
804 let new_vis = new_vis.finish();
805 if new_vis.count_ones() != 0 {
806 let new_chunk = chunk.clone_with_vis(new_vis);
807 yield Message::Chunk(new_chunk);
808 }
809 }
810 Message::Watermark(_) => {
811 // Ignore watermark during backfill.
812 }
813 }
814 }
815 // backfill
816 Either::Right(msg) => {
817 let chunk = match msg? {
818 SourceReaderEvent::DataChunk(chunk) => chunk,
819 SourceReaderEvent::SplitProgress(split_progress) => {
820 // `SplitProgress` is consumed only from the backfill reader side.
821 // The upstream side of source backfill still advances based on
822 // normal chunks with split/offset columns.
823 for (split_id, offset) in split_progress {
824 let previous_state =
825 backfill_stage.states.get(&split_id).cloned();
826 backfill_stage
827 .handle_backfill_progress(split_id.as_ref(), &offset);
828 let updated_state =
829 backfill_stage.states.get(&split_id).cloned();
830 if previous_state != updated_state {
831 tracing::info!(
832 actor_id = %self.actor_ctx.id,
833 fragment_id = %self.actor_ctx.fragment_id,
834 source_id = %self.source_id,
835 source_name = self.source_name,
836 split_id = %split_id,
837 applied_offset = %offset,
838 previous_state = ?previous_state,
839 updated_state = ?updated_state,
840 "source backfill executor applied split progress offset"
841 );
842 }
843 }
844 continue;
845 }
846 };
847
848 if last_barrier_time.elapsed().as_millis() > max_wait_barrier_time_ms {
849 // Pause to let barrier catch up via backpressure of snapshot stream.
850 pause_control.self_pause();
851 pause_reader!();
852
853 // Exceeds the max wait barrier time, the source will be paused.
854 // Currently we can guarantee the
855 // source is not paused since it received stream
856 // chunks.
857 tracing::warn!(
858 "source {} paused, wait barrier for {:?}",
859 self.info.identity,
860 last_barrier_time.elapsed()
861 );
862
863 // Only update `max_wait_barrier_time_ms` to capture
864 // `barrier_interval_ms`
865 // changes here to avoid frequently accessing the shared
866 // `system_params`.
867 max_wait_barrier_time_ms =
868 self.system_params.load().barrier_interval_ms() as u128
869 * WAIT_BARRIER_MULTIPLE_TIMES;
870 }
871 let mut new_vis = BitmapBuilder::zeroed(chunk.visibility().len());
872
873 for (i, (_, row)) in chunk.rows().enumerate() {
874 let split_id = row.datum_at(split_idx).unwrap().into_utf8();
875 let offset = row.datum_at(offset_idx).unwrap().into_utf8();
876 let vis = backfill_stage.handle_backfill_row(split_id, offset);
877 new_vis.set(i, vis);
878 }
879
880 let new_vis = new_vis.finish();
881 let card = new_vis.count_ones();
882 if card != 0 {
883 let new_chunk = chunk.clone_with_vis(new_vis);
884 yield Message::Chunk(new_chunk);
885 source_backfill_row_count.inc_by(card as u64);
886 }
887 }
888 }
889 }
890 }
891
892 std::mem::drop(backfill_stream);
893 let mut states = backfill_stage.states;
894 // Make sure `Finished` state is persisted.
895 self.backfill_state_store.set_states(states.clone()).await?;
896
897 // All splits finished backfilling. Now we only forward the source data.
898 #[for_await]
899 for msg in input {
900 let msg = msg?;
901 match msg {
902 Message::Barrier(barrier) => {
903 let mut split_changed = None;
904 if let Some(ref mutation) = barrier.mutation.as_deref() {
905 match mutation {
906 Mutation::Pause | Mutation::Resume => {
907 // We don't need to do anything. Handled by upstream.
908 }
909 Mutation::SourceChangeSplit(actor_splits) => {
910 tracing::info!(
911 actor_splits = ?actor_splits,
912 "source change split received"
913 );
914 split_changed = actor_splits
915 .get(&self.actor_ctx.id)
916 .cloned()
917 .map(|target_splits| (target_splits, &mut states, true));
918 }
919 Mutation::Update(UpdateMutation { actor_splits, .. }) => {
920 split_changed = actor_splits
921 .get(&self.actor_ctx.id)
922 .cloned()
923 .map(|target_splits| (target_splits, &mut states, false));
924 }
925 _ => {}
926 }
927 }
928 self.backfill_state_store.commit(barrier.epoch).await?;
929 let barrier_epoch = barrier.epoch;
930 yield Message::Barrier(barrier);
931
932 if let Some((target_splits, state, should_trim_state)) = split_changed {
933 self.apply_split_change_forward_stage_after_yield_barrier(
934 barrier_epoch,
935 target_splits,
936 state,
937 should_trim_state,
938 )
939 .await?;
940 }
941 }
942 Message::Chunk(chunk) => {
943 yield Message::Chunk(chunk);
944 }
945 Message::Watermark(watermark) => {
946 yield Message::Watermark(watermark);
947 }
948 }
949 }
950 }
951
952 /// When we should call `progress.finish()` to let blocking DDL return.
953 /// We report as soon as `SourceCachingUp`. Otherwise the DDL might be blocked forever until upstream messages come.
954 ///
955 /// Note: split migration (online scaling) is related with progress tracking.
956 /// - For foreground DDL, scaling is not allowed before progress is finished.
957 /// - For background DDL, scaling is skipped when progress is not finished, and can be triggered by recreating actors during recovery.
958 ///
959 /// See <https://github.com/risingwavelabs/risingwave/issues/18300> for more details.
960 fn should_report_finished(&self, states: &BackfillStates) -> bool {
961 states.values().all(|state| {
962 matches!(
963 state.state,
964 BackfillState::Finished | BackfillState::SourceCachingUp(_)
965 )
966 })
967 }
968
969 /// All splits entered `Finished` state.
970 ///
971 /// We check all splits for the source, including other actors' splits here, before going to the forward stage.
972 /// Otherwise if we `break` early, but after rescheduling, an unfinished split is migrated to
973 /// this actor, we still need to backfill it.
974 ///
975 /// Note: at the beginning, the actor will only read the state written by itself.
976 /// It needs to _wait until it can read all actors' written data_.
977 /// i.e., wait for the second checkpoint has been available.
978 ///
979 /// See <https://github.com/risingwavelabs/risingwave/issues/18300> for more details.
980 async fn backfill_finished(&self, states: &BackfillStates) -> StreamExecutorResult<bool> {
981 Ok(states
982 .values()
983 .all(|state| matches!(state.state, BackfillState::Finished))
984 && self
985 .backfill_state_store
986 .scan_may_stale()
987 .await?
988 .into_iter()
989 .all(|state| matches!(state.state, BackfillState::Finished)))
990 }
991
992 /// For newly added splits, we do not need to backfill and can directly forward from upstream.
993 async fn apply_split_change_after_yield_barrier(
994 &mut self,
995 barrier_epoch: EpochPair,
996 stage: &mut BackfillStage,
997 to_apply_mutation: ApplyMutationAfterBarrier,
998 ) -> StreamExecutorResult<bool> {
999 match to_apply_mutation {
1000 ApplyMutationAfterBarrier::SourceChangeSplit {
1001 target_splits,
1002 should_trim_state,
1003 } => {
1004 self.source_split_change_count.inc();
1005 {
1006 if self
1007 .update_state_if_changed(
1008 barrier_epoch,
1009 target_splits,
1010 stage,
1011 should_trim_state,
1012 )
1013 .await?
1014 {
1015 // Note: we don't rebuild backfill_stream here, due to some complex lifetime issues.
1016 Ok(true)
1017 } else {
1018 Ok(false)
1019 }
1020 }
1021 }
1022 ApplyMutationAfterBarrier::ConnectorPropsChange => Ok(true),
1023 }
1024 }
1025
1026 /// Returns `true` if split changed. Otherwise `false`.
1027 async fn update_state_if_changed(
1028 &mut self,
1029 barrier_epoch: EpochPair,
1030 target_splits: Vec<SplitImpl>,
1031 stage: &mut BackfillStage,
1032 should_trim_state: bool,
1033 ) -> StreamExecutorResult<bool> {
1034 let mut target_state: BackfillStates = HashMap::with_capacity(target_splits.len());
1035
1036 let mut split_changed = false;
1037 // Take out old states (immutable, only used to build target_state and check for added/dropped splits).
1038 // Will be set to target_state in the end.
1039 let old_states = std::mem::take(&mut stage.states);
1040 let committed_reader = self
1041 .backfill_state_store
1042 .new_committed_reader(barrier_epoch)
1043 .await?;
1044 // Iterate over the target (assigned) splits
1045 // - check if any new splits are added
1046 // - build target_state
1047 for split in &target_splits {
1048 let split_id = split.id();
1049 if let Some(s) = old_states.get(&split_id) {
1050 target_state.insert(split_id, s.clone());
1051 } else {
1052 split_changed = true;
1053
1054 let backfill_state = committed_reader
1055 .try_recover_from_state_store(&split_id)
1056 .await?;
1057 match backfill_state {
1058 None => {
1059 // Newly added split. We don't need to backfill.
1060 // Note that this branch is different from the initial barrier (BackfillStateInner::Backfilling(None) there).
1061 target_state.insert(
1062 split_id,
1063 BackfillStateWithProgress {
1064 state: BackfillState::Finished,
1065 num_consumed_rows: 0,
1066 target_offset: None,
1067 },
1068 );
1069 }
1070 Some(backfill_state) => {
1071 // Migrated split. Backfill if unfinished.
1072 target_state.insert(split_id, backfill_state);
1073 }
1074 }
1075 }
1076 }
1077
1078 // Checks dropped splits
1079 for existing_split_id in old_states.keys() {
1080 if !target_state.contains_key(existing_split_id) {
1081 tracing::info!("split dropping detected: {}", existing_split_id);
1082 split_changed = true;
1083 }
1084 }
1085
1086 if split_changed {
1087 let dropped_splits = stage
1088 .states
1089 .extract_if(|split_id, _| !target_state.contains_key(split_id))
1090 .map(|(split_id, _)| split_id);
1091
1092 if should_trim_state {
1093 // trim dropped splits' state
1094 self.backfill_state_store.trim_state(dropped_splits).await?;
1095 }
1096 tracing::info!(old_state=?old_states, new_state=?target_state, "finish split change");
1097 } else {
1098 debug_assert_eq!(old_states, target_state);
1099 }
1100 stage.states = target_state;
1101 stage.splits = target_splits;
1102 stage.debug_assert_consistent();
1103 Ok(split_changed)
1104 }
1105
1106 /// For split change during forward stage, all newly added splits should be already finished.
1107 // We just need to update the state store if necessary.
1108 async fn apply_split_change_forward_stage_after_yield_barrier(
1109 &mut self,
1110 barrier_epoch: EpochPair,
1111 target_splits: Vec<SplitImpl>,
1112 states: &mut BackfillStates,
1113 should_trim_state: bool,
1114 ) -> StreamExecutorResult<()> {
1115 self.source_split_change_count.inc();
1116 {
1117 self.update_state_if_changed_forward_stage(
1118 barrier_epoch,
1119 target_splits,
1120 states,
1121 should_trim_state,
1122 )
1123 .await?;
1124 }
1125
1126 Ok(())
1127 }
1128
1129 async fn update_state_if_changed_forward_stage(
1130 &mut self,
1131 barrier_epoch: EpochPair,
1132 target_splits: Vec<SplitImpl>,
1133 states: &mut BackfillStates,
1134 should_trim_state: bool,
1135 ) -> StreamExecutorResult<()> {
1136 let target_splits: HashSet<SplitId> =
1137 target_splits.into_iter().map(|split| split.id()).collect();
1138
1139 let mut split_changed = false;
1140 let mut newly_added_splits = vec![];
1141
1142 let committed_reader = self
1143 .backfill_state_store
1144 .new_committed_reader(barrier_epoch)
1145 .await?;
1146
1147 // Checks added splits
1148 for split_id in &target_splits {
1149 if !states.contains_key(split_id) {
1150 split_changed = true;
1151
1152 let backfill_state = committed_reader
1153 .try_recover_from_state_store(split_id)
1154 .await?;
1155 match &backfill_state {
1156 None => {
1157 // Newly added split. We don't need to backfill!
1158 newly_added_splits.push(split_id.clone());
1159 }
1160 Some(backfill_state) => {
1161 // Migrated split. It should also be finished since we are in forwarding stage.
1162 match backfill_state.state {
1163 BackfillState::Finished => {}
1164 _ => {
1165 return Err(anyhow::anyhow!(
1166 "Unexpected backfill state: {:?}",
1167 backfill_state
1168 )
1169 .into());
1170 }
1171 }
1172 }
1173 }
1174 states.insert(
1175 split_id.clone(),
1176 backfill_state.unwrap_or(BackfillStateWithProgress {
1177 state: BackfillState::Finished,
1178 num_consumed_rows: 0,
1179 target_offset: None,
1180 }),
1181 );
1182 }
1183 }
1184
1185 // Checks dropped splits
1186 for existing_split_id in states.keys() {
1187 if !target_splits.contains(existing_split_id) {
1188 tracing::info!("split dropping detected: {}", existing_split_id);
1189 split_changed = true;
1190 }
1191 }
1192
1193 if split_changed {
1194 tracing::info!(
1195 target_splits = ?target_splits,
1196 "apply split change"
1197 );
1198
1199 let dropped_splits = states.extract_if(|split_id, _| !target_splits.contains(split_id));
1200
1201 if should_trim_state {
1202 // trim dropped splits' state
1203 self.backfill_state_store
1204 .trim_state(dropped_splits.map(|(k, _v)| k))
1205 .await?;
1206 }
1207
1208 // For migrated splits, and existing splits, we do not need to update
1209 // state store, but only for newly added splits.
1210 self.backfill_state_store
1211 .set_states(
1212 newly_added_splits
1213 .into_iter()
1214 .map(|split_id| {
1215 (
1216 split_id,
1217 BackfillStateWithProgress {
1218 state: BackfillState::Finished,
1219 num_consumed_rows: 0,
1220 target_offset: None,
1221 },
1222 )
1223 })
1224 .collect(),
1225 )
1226 .await?;
1227 }
1228
1229 Ok(())
1230 }
1231}
1232
1233fn compare_kafka_offset(a: &str, b: &str) -> Ordering {
1234 let a = a.parse::<i64>().unwrap();
1235 let b = b.parse::<i64>().unwrap();
1236 a.cmp(&b)
1237}
1238
1239impl<S: StateStore> Execute for SourceBackfillExecutor<S> {
1240 fn execute(self: Box<Self>) -> BoxedMessageStream {
1241 self.inner.execute(self.input).boxed()
1242 }
1243}
1244
1245impl<S: StateStore> Debug for SourceBackfillExecutorInner<S> {
1246 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1247 f.debug_struct("SourceBackfillExecutor")
1248 .field("source_id", &self.source_id)
1249 .field("column_ids", &self.column_ids)
1250 .field("stream_key", &self.info.stream_key)
1251 .finish()
1252 }
1253}
1254
1255struct PauseControl {
1256 // Paused due to backfill order control
1257 backfill_paused: bool,
1258 // Paused due to self-pause, e.g. let barrier catch up
1259 self_paused: bool,
1260 // Paused due to Pause command from meta, pause_on_next_bootstrap
1261 command_paused: bool,
1262 // reader paused
1263 reader_paused: bool,
1264}
1265
1266impl PauseControl {
1267 fn new() -> Self {
1268 Self {
1269 backfill_paused: false,
1270 self_paused: false,
1271 command_paused: false,
1272 reader_paused: false,
1273 }
1274 }
1275
1276 fn is_paused(&self) -> bool {
1277 self.backfill_paused || self.command_paused || self.self_paused
1278 }
1279
1280 /// returns whether we need to pause the reader.
1281 fn backfill_pause(&mut self) {
1282 if self.backfill_paused {
1283 tracing::warn!("backfill_pause invoked twice");
1284 }
1285 self.backfill_paused = true;
1286 }
1287
1288 /// returns whether we need to resume the reader.
1289 /// same precedence as command.
1290 fn backfill_resume(&mut self) -> bool {
1291 if !self.backfill_paused {
1292 tracing::warn!("backfill_resume invoked twice");
1293 }
1294 !self.command_paused
1295 }
1296
1297 /// returns whether we need to pause the reader.
1298 fn self_pause(&mut self) {
1299 assert!(
1300 !self.backfill_paused,
1301 "backfill stream should not be read when backfill_pause is set"
1302 );
1303 assert!(
1304 !self.command_paused,
1305 "backfill stream should not be read when command_pause is set"
1306 );
1307 if self.self_paused {
1308 tracing::warn!("self_pause invoked twice");
1309 }
1310 self.self_paused = true;
1311 }
1312
1313 /// returns whether we need to resume the reader.
1314 /// `self_resume` has the lowest precedence,
1315 /// it can only resume if we are not paused due to `backfill_paused` or `command_paused`.
1316 fn self_resume(&mut self) -> bool {
1317 self.self_paused = false;
1318 !(self.backfill_paused || self.command_paused)
1319 }
1320
1321 /// returns whether we need to pause the reader.
1322 fn command_pause(&mut self) {
1323 if self.command_paused {
1324 tracing::warn!("command_pause invoked twice");
1325 }
1326 self.command_paused = true;
1327 }
1328
1329 /// returns whether we need to resume the reader.
1330 /// same precedence as backfill.
1331 fn command_resume(&mut self) -> bool {
1332 if !self.command_paused {
1333 tracing::warn!("command_resume invoked twice");
1334 }
1335 self.command_paused = false;
1336 !self.backfill_paused
1337 }
1338}
1339
1340#[cfg(test)]
1341mod tests {
1342 use super::*;
1343
1344 fn stage(state: BackfillState, target_offset: &str) -> BackfillStage {
1345 BackfillStage {
1346 states: HashMap::from([(
1347 SplitId::from("0"),
1348 BackfillStateWithProgress {
1349 state,
1350 num_consumed_rows: 0,
1351 target_offset: Some(target_offset.to_owned()),
1352 },
1353 )]),
1354 splits: vec![],
1355 }
1356 }
1357
1358 fn state(stage: &BackfillStage) -> &BackfillState {
1359 &stage.states.get("0").unwrap().state
1360 }
1361
1362 #[test]
1363 fn test_progress_after_source_caching_up_keeps_dropped_rows_for_upstream() {
1364 let mut stage = stage(BackfillState::Backfilling(Some("108".to_owned())), "109");
1365
1366 assert!(stage.handle_backfill_row("0", "110"));
1367 assert!(!stage.handle_backfill_row("0", "111"));
1368 stage.handle_backfill_progress("0", "219");
1369 assert_eq!(
1370 *state(&stage),
1371 BackfillState::SourceCachingUp("110".to_owned())
1372 );
1373
1374 assert!(!stage.handle_upstream_row("0", "110"));
1375 assert!(stage.handle_upstream_row("0", "111"));
1376 assert!(stage.handle_upstream_row("0", "218"));
1377 }
1378
1379 #[test]
1380 fn test_progress_over_control_record_finishes_backfill() {
1381 let mut stage = stage(BackfillState::Backfilling(Some("108".to_owned())), "109");
1382
1383 stage.handle_backfill_progress("0", "109");
1384 assert_eq!(
1385 *state(&stage),
1386 BackfillState::SourceCachingUp("109".to_owned())
1387 );
1388
1389 assert!(stage.handle_upstream_row("0", "110"));
1390 assert_eq!(*state(&stage), BackfillState::Finished);
1391 }
1392}