Skip to main content

risingwave_stream/task/barrier_worker/
managed_state.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, BTreeSet, HashMap, HashSet, VecDeque};
16use std::fmt::{Debug, Display, Formatter};
17use std::future::{Future, pending, poll_fn};
18use std::mem::replace;
19use std::sync::Arc;
20use std::task::{Context, Poll};
21use std::time::{Duration, Instant};
22
23use anyhow::anyhow;
24use futures::future::BoxFuture;
25use futures::stream::{FuturesOrdered, FuturesUnordered};
26use futures::{FutureExt, StreamExt};
27use prometheus::HistogramTimer;
28use risingwave_common::catalog::TableId;
29use risingwave_common::id::{SinkId, SourceId};
30use risingwave_common::metrics::{LabelGuardedHistogram, LabelGuardedIntCounter};
31use risingwave_common::util::epoch::EpochPair;
32use risingwave_pb::connector_service::SinkMetadata;
33use risingwave_pb::stream_plan::barrier::BarrierKind;
34use risingwave_pb::stream_service::barrier_complete_response::{
35    IcebergPkIndexSinkMetadata as PbIcebergPkIndexSinkMetadata, PbCdcSourceOffsetUpdated,
36    PbListFinishedSource, PbLoadFinishedSource, PbRefreshFinishedActor,
37};
38use risingwave_storage::StateStoreImpl;
39use tokio::sync::mpsc;
40use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
41use tokio::task::JoinHandle;
42
43use crate::error::{StreamError, StreamResult};
44use crate::executor::Barrier;
45use crate::executor::exchange::permit::Receiver;
46use crate::executor::monitor::StreamingMetrics;
47use crate::task::progress::{BackfillState, TableChangeLogProgress};
48use crate::task::{
49    ActorId, LocalBarrierEvent, LocalBarrierManager, NewOutputRequest, PartialGraphId,
50    StreamActorManager, UpDownActorIds,
51};
52
53struct IssuedState {
54    /// Actor ids remaining to be collected.
55    pub remaining_actors: BTreeSet<ActorId>,
56
57    pub barrier_inflight_latency: HistogramTimer,
58}
59
60impl Debug for IssuedState {
61    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62        f.debug_struct("IssuedState")
63            .field("remaining_actors", &self.remaining_actors)
64            .finish()
65    }
66}
67
68/// The state machine of local barrier manager.
69#[derive(Debug)]
70enum ManagedBarrierStateInner {
71    /// Meta service has issued a `send_barrier` request. We're collecting barriers now.
72    Issued(IssuedState),
73
74    /// The barrier has been collected by all remaining actors
75    AllCollected(EpochBarrierEvent),
76}
77
78#[derive(Debug)]
79struct BarrierState {
80    barrier: Barrier,
81    /// Only be `Some(_)` when `barrier.kind` is `Checkpoint`
82    table_ids: Option<HashSet<TableId>>,
83    inner: ManagedBarrierStateInner,
84}
85
86use risingwave_common::must_match;
87use risingwave_pb::id::FragmentId;
88use risingwave_pb::stream_service::{InjectBarrierRequest, PbIcebergPkIndexSinkRole};
89
90use crate::task::barrier_worker::ScoredStreamError;
91use crate::task::barrier_worker::await_epoch_completed_future::AwaitEpochCompletedFuture;
92use crate::task::cdc_progress::CdcTableBackfillState;
93
94pub(super) struct ManagedBarrierStateDebugInfo<'a> {
95    running_actors: BTreeSet<ActorId>,
96    graph_state: &'a PartialGraphManagedBarrierState,
97}
98
99impl Display for ManagedBarrierStateDebugInfo<'_> {
100    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
101        write!(f, "running_actors: ")?;
102        for actor_id in &self.running_actors {
103            write!(f, "{}, ", actor_id)?;
104        }
105        {
106            writeln!(f, "graph states")?;
107            write!(f, "{}", self.graph_state)?;
108        }
109        Ok(())
110    }
111}
112
113impl Display for &'_ PartialGraphManagedBarrierState {
114    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
115        let mut prev_epoch = 0u64;
116        for (epoch, barrier_state) in &self.epoch_barrier_state_map {
117            write!(f, "> Epoch {}: ", epoch)?;
118            match &barrier_state.inner {
119                ManagedBarrierStateInner::Issued(state) => {
120                    write!(
121                        f,
122                        "Issued [{:?}]. Remaining actors: [",
123                        barrier_state.barrier.kind
124                    )?;
125                    let mut is_prev_epoch_issued = false;
126                    if prev_epoch != 0 {
127                        let bs = &self.epoch_barrier_state_map[&prev_epoch];
128                        if let ManagedBarrierStateInner::Issued(IssuedState {
129                            remaining_actors: remaining_actors_prev,
130                            ..
131                        }) = &bs.inner
132                        {
133                            // Only show the actors that are not in the previous epoch.
134                            is_prev_epoch_issued = true;
135                            let mut duplicates = 0usize;
136                            for actor_id in &state.remaining_actors {
137                                if !remaining_actors_prev.contains(actor_id) {
138                                    write!(f, "{}, ", actor_id)?;
139                                } else {
140                                    duplicates += 1;
141                                }
142                            }
143                            if duplicates > 0 {
144                                write!(f, "...and {} actors in prev epoch", duplicates)?;
145                            }
146                        }
147                    }
148                    if !is_prev_epoch_issued {
149                        for actor_id in &state.remaining_actors {
150                            write!(f, "{}, ", actor_id)?;
151                        }
152                    }
153                    write!(f, "]")?;
154                }
155                ManagedBarrierStateInner::AllCollected(_) => {
156                    write!(f, "AllCollected")?;
157                }
158            }
159            prev_epoch = *epoch;
160            writeln!(f)?;
161        }
162
163        if self
164            .barrier_events
165            .values()
166            .any(|event| !event.create_mview_progress.is_empty())
167        {
168            writeln!(f, "Create MView Progress:")?;
169            for (epoch, event) in self
170                .barrier_events
171                .iter()
172                .filter(|(_, event)| !event.create_mview_progress.is_empty())
173            {
174                write!(f, "> Epoch {}:", epoch)?;
175                for (actor_id, (_, state)) in &event.create_mview_progress {
176                    write!(f, ">> Actor {}: {}, ", actor_id, state)?;
177                }
178            }
179        }
180
181        Ok(())
182    }
183}
184
185enum InflightActorStatus {
186    /// The actor has been issued some barriers, but has not collected the first barrier
187    IssuedFirst(Vec<Barrier>),
188    /// The actor has been issued some barriers, and has collected the first barrier
189    Running(u64),
190}
191
192impl InflightActorStatus {
193    fn max_issued_epoch(&self) -> u64 {
194        match self {
195            InflightActorStatus::Running(epoch) => *epoch,
196            InflightActorStatus::IssuedFirst(issued_barriers) => {
197                issued_barriers.last().expect("non-empty").epoch.prev
198            }
199        }
200    }
201}
202
203pub(crate) struct InflightActorState {
204    actor_id: ActorId,
205    barrier_senders: Vec<mpsc::UnboundedSender<Barrier>>,
206    /// `prev_epoch`. `push_back` and `pop_front`
207    pub(in crate::task) inflight_barriers: VecDeque<u64>,
208    status: InflightActorStatus,
209    /// Whether the actor has been issued a stop barrier
210    is_stopping: bool,
211
212    new_output_request_tx: UnboundedSender<(ActorId, NewOutputRequest)>,
213    join_handle: JoinHandle<()>,
214    monitor_task_handle: Option<JoinHandle<()>>,
215}
216
217impl InflightActorState {
218    pub(super) fn start(
219        actor_id: ActorId,
220        initial_barrier: &Barrier,
221        new_output_request_tx: UnboundedSender<(ActorId, NewOutputRequest)>,
222        join_handle: JoinHandle<()>,
223        monitor_task_handle: Option<JoinHandle<()>>,
224    ) -> Self {
225        Self {
226            actor_id,
227            barrier_senders: vec![],
228            inflight_barriers: VecDeque::from_iter([initial_barrier.epoch.prev]),
229            status: InflightActorStatus::IssuedFirst(vec![initial_barrier.clone()]),
230            is_stopping: false,
231            new_output_request_tx,
232            join_handle,
233            monitor_task_handle,
234        }
235    }
236
237    pub(super) fn issue_barrier(&mut self, barrier: &Barrier, is_stop: bool) -> StreamResult<()> {
238        assert!(barrier.epoch.prev > self.status.max_issued_epoch());
239
240        for barrier_sender in &self.barrier_senders {
241            barrier_sender.send(barrier.clone()).map_err(|_| {
242                StreamError::barrier_send(
243                    barrier.clone(),
244                    self.actor_id,
245                    "failed to send to registered sender",
246                )
247            })?;
248        }
249
250        if let Some(prev_epoch) = self.inflight_barriers.back() {
251            assert!(*prev_epoch < barrier.epoch.prev);
252        }
253        self.inflight_barriers.push_back(barrier.epoch.prev);
254
255        match &mut self.status {
256            InflightActorStatus::IssuedFirst(pending_barriers) => {
257                pending_barriers.push(barrier.clone());
258            }
259            InflightActorStatus::Running(prev_epoch) => {
260                *prev_epoch = barrier.epoch.prev;
261            }
262        };
263
264        if is_stop {
265            assert!(!self.is_stopping, "stopped actor should not issue barrier");
266            self.is_stopping = true;
267        }
268        Ok(())
269    }
270
271    pub(super) fn collect(&mut self, epoch: EpochPair) -> bool {
272        let prev_epoch = self.inflight_barriers.pop_front().expect("should exist");
273        assert_eq!(prev_epoch, epoch.prev);
274        match &self.status {
275            InflightActorStatus::IssuedFirst(pending_barriers) => {
276                assert_eq!(
277                    prev_epoch,
278                    pending_barriers.first().expect("non-empty").epoch.prev
279                );
280                self.status = InflightActorStatus::Running(
281                    pending_barriers.last().expect("non-empty").epoch.prev,
282                );
283            }
284            InflightActorStatus::Running(_) => {}
285        }
286
287        self.inflight_barriers.is_empty() && self.is_stopping
288    }
289}
290
291/// Part of [`PartialGraphState`]
292#[derive(Debug)]
293pub(crate) struct EpochBarrierEvent {
294    /// The full epoch pair is retained while the map is keyed by `epoch.curr`, so callers that
295    /// report an event for the same current epoch can be checked for a matching previous epoch.
296    pub(crate) epoch: EpochPair,
297    /// Creation progress reported by each backfill actor.
298    pub(crate) create_mview_progress: HashMap<ActorId, (FragmentId, BackfillState)>,
299    /// Change-log retention progress reported by snapshot-backfill actors.
300    pub(crate) table_change_log_progress: Vec<TableChangeLogProgress>,
301    /// Source-list completion reports for refreshable batch sources.
302    pub(crate) list_finished_source_ids: Vec<PbListFinishedSource>,
303    /// Source-load completion reports for refreshable batch sources.
304    pub(crate) load_finished_source_ids: Vec<PbLoadFinishedSource>,
305    /// CDC table-backfill progress reported by each actor.
306    pub(crate) cdc_table_backfill_progress: HashMap<ActorId, CdcTableBackfillState>,
307    /// Reports that a CDC source has updated its offset at least once.
308    pub(crate) cdc_source_offset_updated: Vec<PbCdcSourceOffsetUpdated>,
309    /// Iceberg pk-index sink metadata reports.
310    pub(crate) iceberg_pk_index_sink_metadata: Vec<PbIcebergPkIndexSinkMetadata>,
311    /// Materialize actors that have finished their part of a table refresh.
312    pub(crate) refresh_finished_actors: Vec<PbRefreshFinishedActor>,
313}
314
315impl EpochBarrierEvent {
316    fn new(epoch: EpochPair) -> Self {
317        Self {
318            epoch,
319            create_mview_progress: Default::default(),
320            table_change_log_progress: Default::default(),
321            list_finished_source_ids: Default::default(),
322            load_finished_source_ids: Default::default(),
323            cdc_table_backfill_progress: Default::default(),
324            cdc_source_offset_updated: Default::default(),
325            iceberg_pk_index_sink_metadata: Default::default(),
326            refresh_finished_actors: Default::default(),
327        }
328    }
329}
330
331pub(crate) struct PartialGraphManagedBarrierState {
332    /// Record barrier state for each epoch of concurrent checkpoints.
333    ///
334    /// The key is `prev_epoch`, and the first value is `curr_epoch`
335    epoch_barrier_state_map: BTreeMap<u64, BarrierState>,
336
337    prev_barrier_table_ids: Option<(EpochPair, HashSet<TableId>)>,
338
339    /// Reports emitted by actors while processing each epoch of concurrent checkpoints.
340    ///
341    /// The process of reporting is as follows:
342    /// 1. updated by local barrier events from actors
343    /// 2. converted to [`ManagedBarrierStateInner`] in [`Self::may_have_collected_all`]
344    /// 3. handled by [`Self::pop_barrier_to_complete`]
345    /// 4. put in [`crate::task::barrier_worker::BarrierCompleteResult`] and reported to meta.
346    barrier_events: HashMap<u64, EpochBarrierEvent>,
347
348    state_store: StateStoreImpl,
349
350    barrier_inflight_latency: LabelGuardedHistogram,
351    barrier_sync_latency: LabelGuardedHistogram,
352    barrier_manager_progress: LabelGuardedIntCounter,
353}
354
355impl PartialGraphManagedBarrierState {
356    pub(super) fn new(
357        actor_manager: &StreamActorManager,
358        partial_graph_id: PartialGraphId,
359    ) -> Self {
360        Self::new_inner(
361            actor_manager.env.state_store(),
362            actor_manager.streaming_metrics.clone(),
363            partial_graph_id,
364        )
365    }
366
367    fn new_inner(
368        state_store: StateStoreImpl,
369        streaming_metrics: Arc<StreamingMetrics>,
370        partial_graph_id: PartialGraphId,
371    ) -> Self {
372        fn partial_graph_name(partial_graph_id: PartialGraphId) -> String {
373            // HACK: The partial graph ID encoding is owned by meta and intentionally not exposed to
374            // compute nodes. Decode it locally only for the human-readable metrics label.
375            let raw_partial_graph_id = partial_graph_id.as_raw_id();
376            let database_id = raw_partial_graph_id >> 32;
377            let raw_job_id = raw_partial_graph_id as u32;
378            if raw_job_id == u32::MAX {
379                format!("database {database_id}")
380            } else {
381                format!("database {database_id} job {raw_job_id}")
382            }
383        }
384
385        let partial_graph_name = partial_graph_name(partial_graph_id);
386        let barrier_inflight_latency = streaming_metrics
387            .barrier_inflight_latency
388            .with_guarded_label_values(&[&partial_graph_name]);
389        let barrier_sync_latency = streaming_metrics
390            .barrier_sync_latency
391            .with_guarded_label_values(&[&partial_graph_name]);
392        let barrier_manager_progress = streaming_metrics
393            .barrier_manager_progress
394            .with_guarded_label_values(&[&partial_graph_name]);
395        Self {
396            epoch_barrier_state_map: Default::default(),
397            prev_barrier_table_ids: None,
398            barrier_events: Default::default(),
399            state_store,
400            barrier_inflight_latency,
401            barrier_sync_latency,
402            barrier_manager_progress,
403        }
404    }
405
406    #[cfg(test)]
407    pub(crate) fn for_test() -> Self {
408        Self::new_inner(
409            StateStoreImpl::for_test(),
410            Arc::new(StreamingMetrics::unused()),
411            PartialGraphId::new(0),
412        )
413    }
414
415    pub(crate) fn event_mut(&mut self, epoch: EpochPair) -> &mut EpochBarrierEvent {
416        let event = self
417            .barrier_events
418            .entry(epoch.curr)
419            .or_insert_with(|| EpochBarrierEvent::new(epoch));
420        assert_eq!(
421            event.epoch, epoch,
422            "events for the same current epoch must have the same previous epoch"
423        );
424        event
425    }
426
427    pub(super) fn is_empty(&self) -> bool {
428        self.epoch_barrier_state_map.is_empty()
429    }
430}
431
432pub(crate) struct SuspendedPartialGraphState {
433    pub(super) suspend_time: Instant,
434    inner: PartialGraphState,
435    failure: Option<(Option<ActorId>, StreamError)>,
436}
437
438impl SuspendedPartialGraphState {
439    fn new(
440        state: PartialGraphState,
441        failure: Option<(Option<ActorId>, StreamError)>,
442        _completing_futures: Option<FuturesOrdered<AwaitEpochCompletedFuture>>, /* discard the completing futures */
443    ) -> Self {
444        Self {
445            suspend_time: Instant::now(),
446            inner: state,
447            failure,
448        }
449    }
450
451    async fn reset(mut self) -> ResetPartialGraphOutput {
452        let root_err = self.inner.try_find_root_actor_failure(self.failure).await;
453        self.inner.abort_and_wait_actors().await;
454        ResetPartialGraphOutput { root_err }
455    }
456}
457
458pub(crate) struct ResetPartialGraphOutput {
459    pub(crate) root_err: Option<ScoredStreamError>,
460}
461
462pub(in crate::task) enum PartialGraphStatus {
463    ReceivedExchangeRequest(Vec<(String, UpDownActorIds, NewOutputRequest)>),
464    Running(PartialGraphState),
465    Suspended(SuspendedPartialGraphState),
466    Resetting,
467    /// temporary place holder
468    Unspecified,
469}
470
471impl PartialGraphStatus {
472    pub(crate) async fn abort(&mut self) {
473        match self {
474            PartialGraphStatus::ReceivedExchangeRequest(pending_requests) => {
475                for (_, _, request) in pending_requests.drain(..) {
476                    request.reject(anyhow!("partial graph aborted").into());
477                }
478            }
479            PartialGraphStatus::Running(state) => {
480                state.abort_and_wait_actors().await;
481            }
482            PartialGraphStatus::Suspended(SuspendedPartialGraphState { inner: state, .. }) => {
483                state.abort_and_wait_actors().await;
484            }
485            PartialGraphStatus::Resetting => {}
486            PartialGraphStatus::Unspecified => {
487                unreachable!()
488            }
489        }
490    }
491
492    pub(crate) fn state_for_request(&mut self) -> Option<&mut PartialGraphState> {
493        match self {
494            PartialGraphStatus::ReceivedExchangeRequest(_) => {
495                unreachable!("should not handle request")
496            }
497            PartialGraphStatus::Running(state) => Some(state),
498            PartialGraphStatus::Suspended(_) => None,
499            PartialGraphStatus::Resetting => {
500                unreachable!("should not receive further request during cleaning")
501            }
502            PartialGraphStatus::Unspecified => {
503                unreachable!()
504            }
505        }
506    }
507
508    pub(super) fn poll_next_event(
509        &mut self,
510        cx: &mut Context<'_>,
511    ) -> Poll<ManagedBarrierStateEvent> {
512        match self {
513            PartialGraphStatus::ReceivedExchangeRequest(_) => Poll::Pending,
514            PartialGraphStatus::Running(state) => state.poll_next_event(cx),
515            PartialGraphStatus::Suspended(_) | PartialGraphStatus::Resetting => Poll::Pending,
516            PartialGraphStatus::Unspecified => {
517                unreachable!()
518            }
519        }
520    }
521
522    pub(super) fn suspend(
523        &mut self,
524        failed_actor: Option<ActorId>,
525        err: StreamError,
526        completing_futures: Option<FuturesOrdered<AwaitEpochCompletedFuture>>,
527    ) {
528        let state = must_match!(replace(self, PartialGraphStatus::Unspecified), PartialGraphStatus::Running(state) => state);
529        *self = PartialGraphStatus::Suspended(SuspendedPartialGraphState::new(
530            state,
531            Some((failed_actor, err)),
532            completing_futures,
533        ));
534    }
535
536    pub(super) fn start_reset(
537        &mut self,
538        partial_graph_id: PartialGraphId,
539        completing_futures: Option<FuturesOrdered<AwaitEpochCompletedFuture>>,
540        table_ids_to_clear: &mut HashSet<TableId>,
541    ) -> BoxFuture<'static, ResetPartialGraphOutput> {
542        match replace(self, PartialGraphStatus::Resetting) {
543            PartialGraphStatus::ReceivedExchangeRequest(pending_requests) => {
544                for (_, _, request) in pending_requests {
545                    request.reject(anyhow!("partial graph reset").into());
546                }
547                async move { ResetPartialGraphOutput { root_err: None } }.boxed()
548            }
549            PartialGraphStatus::Running(state) => {
550                assert_eq!(partial_graph_id, state.partial_graph_id);
551                info!(
552                    %partial_graph_id,
553                    "start partial graph reset from Running"
554                );
555                table_ids_to_clear.extend(state.table_ids.iter().copied());
556                SuspendedPartialGraphState::new(state, None, completing_futures)
557                    .reset()
558                    .boxed()
559            }
560            PartialGraphStatus::Suspended(state) => {
561                assert!(
562                    completing_futures.is_none(),
563                    "should have been clear when suspended"
564                );
565                assert_eq!(partial_graph_id, state.inner.partial_graph_id);
566                info!(
567                    %partial_graph_id,
568                    suspend_elapsed = ?state.suspend_time.elapsed(),
569                    "start partial graph reset after suspended"
570                );
571                table_ids_to_clear.extend(state.inner.table_ids.iter().copied());
572                state.reset().boxed()
573            }
574            PartialGraphStatus::Resetting => {
575                unreachable!("should not reset for twice");
576            }
577            PartialGraphStatus::Unspecified => {
578                unreachable!()
579            }
580        }
581    }
582}
583
584#[derive(Default)]
585pub(in crate::task) struct ManagedBarrierState {
586    pub(super) partial_graphs: HashMap<PartialGraphId, PartialGraphStatus>,
587    pub(super) resetting_graphs:
588        FuturesUnordered<JoinHandle<Vec<(PartialGraphId, ResetPartialGraphOutput)>>>,
589}
590
591pub(super) enum ManagedBarrierStateEvent {
592    BarrierCollected {
593        partial_graph_id: PartialGraphId,
594        barrier: Barrier,
595    },
596    ActorError {
597        partial_graph_id: PartialGraphId,
598        actor_id: ActorId,
599        err: StreamError,
600    },
601    PartialGraphsReset(Vec<(PartialGraphId, ResetPartialGraphOutput)>),
602    RegisterLocalUpstreamOutput {
603        actor_id: ActorId,
604        upstream_actor_id: ActorId,
605        upstream_partial_graph_id: PartialGraphId,
606        term_id: String,
607        result_sender: tokio::sync::oneshot::Sender<StreamResult<Receiver>>,
608    },
609}
610
611impl ManagedBarrierState {
612    pub(super) fn next_event(&mut self) -> impl Future<Output = ManagedBarrierStateEvent> + '_ {
613        poll_fn(|cx| {
614            for graph in self.partial_graphs.values_mut() {
615                if let Poll::Ready(event) = graph.poll_next_event(cx) {
616                    return Poll::Ready(event);
617                }
618            }
619            if let Poll::Ready(Some(result)) = self.resetting_graphs.poll_next_unpin(cx) {
620                let outputs = result.expect("failed to join resetting future");
621                for (partial_graph_id, _) in &outputs {
622                    let PartialGraphStatus::Resetting = self
623                        .partial_graphs
624                        .remove(partial_graph_id)
625                        .expect("should exist")
626                    else {
627                        panic!("should be resetting")
628                    };
629                }
630                return Poll::Ready(ManagedBarrierStateEvent::PartialGraphsReset(outputs));
631            }
632            Poll::Pending
633        })
634    }
635}
636
637/// Per-partial-graph barrier state manager. Handles barriers for one specific partial graph.
638/// Part of [`ManagedBarrierState`] in [`super::LocalBarrierWorker`].
639///
640/// See [`crate::task`] for architecture overview.
641pub(crate) struct PartialGraphState {
642    partial_graph_id: PartialGraphId,
643    pub(crate) actor_states: HashMap<ActorId, InflightActorState>,
644    pub(super) actor_pending_new_output_requests:
645        HashMap<ActorId, Vec<(ActorId, NewOutputRequest)>>,
646
647    pub(crate) graph_state: PartialGraphManagedBarrierState,
648
649    table_ids: HashSet<TableId>,
650
651    actor_manager: Arc<StreamActorManager>,
652
653    pub(super) local_barrier_manager: LocalBarrierManager,
654
655    barrier_event_rx: UnboundedReceiver<LocalBarrierEvent>,
656    pub(super) actor_failure_rx: UnboundedReceiver<(ActorId, StreamError)>,
657}
658
659impl PartialGraphState {
660    /// Create a barrier manager state. This will be called only once.
661    pub(super) fn new(
662        partial_graph_id: PartialGraphId,
663        term_id: String,
664        actor_manager: Arc<StreamActorManager>,
665    ) -> Self {
666        let (local_barrier_manager, barrier_event_rx, actor_failure_rx) =
667            LocalBarrierManager::new(term_id, actor_manager.env.clone());
668        Self {
669            partial_graph_id,
670            actor_states: Default::default(),
671            actor_pending_new_output_requests: Default::default(),
672            graph_state: PartialGraphManagedBarrierState::new(&actor_manager, partial_graph_id),
673            table_ids: Default::default(),
674            actor_manager,
675            local_barrier_manager,
676            barrier_event_rx,
677            actor_failure_rx,
678        }
679    }
680
681    pub(super) fn to_debug_info(&self) -> ManagedBarrierStateDebugInfo<'_> {
682        ManagedBarrierStateDebugInfo {
683            running_actors: self.actor_states.keys().cloned().collect(),
684            graph_state: &self.graph_state,
685        }
686    }
687
688    async fn abort_and_wait_actors(&mut self) {
689        for (actor_id, state) in &self.actor_states {
690            tracing::debug!("force stopping actor {}", actor_id);
691            state.join_handle.abort();
692            if let Some(monitor_task_handle) = &state.monitor_task_handle {
693                monitor_task_handle.abort();
694            }
695        }
696
697        for (actor_id, state) in self.actor_states.drain() {
698            tracing::debug!("join actor {}", actor_id);
699            let result = state.join_handle.await;
700            assert!(result.is_ok() || result.unwrap_err().is_cancelled());
701        }
702    }
703}
704
705impl InflightActorState {
706    pub(super) fn register_barrier_sender(
707        &mut self,
708        tx: mpsc::UnboundedSender<Barrier>,
709    ) -> StreamResult<()> {
710        match &self.status {
711            InflightActorStatus::IssuedFirst(pending_barriers) => {
712                for barrier in pending_barriers {
713                    tx.send(barrier.clone()).map_err(|_| {
714                        StreamError::barrier_send(
715                            barrier.clone(),
716                            self.actor_id,
717                            "failed to send pending barriers to newly registered sender",
718                        )
719                    })?;
720                }
721                self.barrier_senders.push(tx);
722            }
723            InflightActorStatus::Running(_) => {
724                unreachable!("should not register barrier sender when entering Running status")
725            }
726        }
727        Ok(())
728    }
729}
730
731impl PartialGraphState {
732    pub(super) fn register_barrier_sender(
733        &mut self,
734        actor_id: ActorId,
735        tx: mpsc::UnboundedSender<Barrier>,
736    ) -> StreamResult<()> {
737        self.actor_states
738            .get_mut(&actor_id)
739            .expect("should exist")
740            .register_barrier_sender(tx)
741    }
742}
743
744impl PartialGraphState {
745    pub(super) fn transform_to_issued(
746        &mut self,
747        barrier: &Barrier,
748        request: InjectBarrierRequest,
749    ) -> StreamResult<()> {
750        assert_eq!(self.partial_graph_id, request.partial_graph_id);
751        let actor_to_stop = barrier.all_stop_actors();
752        let is_stop_actor = |actor_id| {
753            actor_to_stop
754                .map(|actors| actors.contains(&actor_id))
755                .unwrap_or(false)
756        };
757
758        let table_ids = HashSet::from_iter(request.table_ids_to_sync);
759        self.table_ids.extend(table_ids.iter().cloned());
760
761        self.graph_state.transform_to_issued(
762            barrier,
763            request.actor_ids_to_collect.iter().copied(),
764            table_ids,
765        );
766
767        let mut new_actors = HashSet::new();
768        for (node, fragment_id, actor) in
769            request
770                .actors_to_build
771                .into_iter()
772                .flat_map(|fragment_actors| {
773                    let node = Arc::new(fragment_actors.node.unwrap());
774                    fragment_actors
775                        .actors
776                        .into_iter()
777                        .map(move |actor| (node.clone(), fragment_actors.fragment_id, actor))
778                })
779        {
780            let actor_id = actor.actor_id;
781            assert!(!is_stop_actor(actor_id));
782            assert!(new_actors.insert(actor_id));
783            assert!(request.actor_ids_to_collect.contains(&actor_id));
784            let (new_output_request_tx, new_output_request_rx) = unbounded_channel();
785            if let Some(pending_requests) = self.actor_pending_new_output_requests.remove(&actor_id)
786            {
787                for request in pending_requests {
788                    let _ = new_output_request_tx.send(request);
789                }
790            }
791            let (join_handle, monitor_join_handle) = self.actor_manager.spawn_actor(
792                actor,
793                fragment_id,
794                node,
795                self.local_barrier_manager.clone(),
796                new_output_request_rx,
797            );
798            assert!(
799                self.actor_states
800                    .try_insert(
801                        actor_id,
802                        InflightActorState::start(
803                            actor_id,
804                            barrier,
805                            new_output_request_tx,
806                            join_handle,
807                            monitor_join_handle
808                        )
809                    )
810                    .is_ok()
811            );
812        }
813
814        // Spawn a trivial join handle to be compatible with the unit test. In the unit tests that involve local barrier manager,
815        // actors are spawned in the local test logic, but we assume that there is an entry for each spawned actor in ·actor_states`,
816        // so under cfg!(test) we add a dummy entry for each new actor.
817        if cfg!(test) {
818            for &actor_id in &request.actor_ids_to_collect {
819                if !self.actor_states.contains_key(&actor_id) {
820                    let (tx, rx) = unbounded_channel();
821                    let join_handle = self.actor_manager.runtime.spawn(async move {
822                        // The rx is spawned so that tx.send() will not fail.
823                        let _ = rx;
824                        pending().await
825                    });
826                    assert!(
827                        self.actor_states
828                            .try_insert(
829                                actor_id,
830                                InflightActorState::start(actor_id, barrier, tx, join_handle, None,)
831                            )
832                            .is_ok()
833                    );
834                    new_actors.insert(actor_id);
835                }
836            }
837        }
838
839        // Note: it's important to issue barrier to actor after issuing to graph to ensure that
840        // we call `start_epoch` on the graph before the actors receive the barrier
841        for &actor_id in &request.actor_ids_to_collect {
842            if new_actors.contains(&actor_id) {
843                continue;
844            }
845            self.actor_states
846                .get_mut(&actor_id)
847                .unwrap_or_else(|| {
848                    panic!(
849                        "should exist: {} {:?}",
850                        actor_id, request.actor_ids_to_collect
851                    );
852                })
853                .issue_barrier(barrier, is_stop_actor(actor_id))?;
854        }
855
856        Ok(())
857    }
858
859    pub(super) fn new_actor_output_request(
860        &mut self,
861        actor_id: ActorId,
862        upstream_actor_id: ActorId,
863        request: NewOutputRequest,
864    ) {
865        if let Some(actor) = self.actor_states.get_mut(&upstream_actor_id) {
866            let _ = actor.new_output_request_tx.send((actor_id, request));
867        } else {
868            self.actor_pending_new_output_requests
869                .entry(upstream_actor_id)
870                .or_default()
871                .push((actor_id, request));
872        }
873    }
874
875    /// Handles [`LocalBarrierEvent`] from [`crate::task::barrier_manager::LocalBarrierManager`].
876    pub(super) fn poll_next_event(
877        &mut self,
878        cx: &mut Context<'_>,
879    ) -> Poll<ManagedBarrierStateEvent> {
880        if let Poll::Ready(option) = self.actor_failure_rx.poll_recv(cx) {
881            let (actor_id, err) = option.expect("non-empty when tx in local_barrier_manager");
882            return Poll::Ready(ManagedBarrierStateEvent::ActorError {
883                actor_id,
884                err,
885                partial_graph_id: self.partial_graph_id,
886            });
887        }
888        // yield some pending collected epochs
889        {
890            if let Some(barrier) = self.graph_state.may_have_collected_all() {
891                return Poll::Ready(ManagedBarrierStateEvent::BarrierCollected {
892                    barrier,
893                    partial_graph_id: self.partial_graph_id,
894                });
895            }
896        }
897        while let Poll::Ready(event) = self.barrier_event_rx.poll_recv(cx) {
898            match event.expect("non-empty when tx in local_barrier_manager") {
899                LocalBarrierEvent::ReportActorCollected { actor_id, epoch } => {
900                    if let Some(barrier) = self.collect(actor_id, epoch) {
901                        return Poll::Ready(ManagedBarrierStateEvent::BarrierCollected {
902                            barrier,
903                            partial_graph_id: self.partial_graph_id,
904                        });
905                    }
906                }
907                LocalBarrierEvent::ReportCreateProgress {
908                    epoch,
909                    fragment_id,
910                    actor,
911                    state,
912                } => {
913                    self.update_create_mview_progress(epoch, fragment_id, actor, state);
914                }
915                LocalBarrierEvent::ReportTableChangeLogProgress { epoch, progress } => {
916                    self.update_table_change_log_progress(epoch, progress);
917                }
918                LocalBarrierEvent::ReportSourceListFinished {
919                    epoch,
920                    actor_id,
921                    table_id,
922                    associated_source_id,
923                } => {
924                    self.report_source_list_finished(
925                        epoch,
926                        actor_id,
927                        table_id,
928                        associated_source_id,
929                    );
930                }
931                LocalBarrierEvent::ReportSourceLoadFinished {
932                    epoch,
933                    actor_id,
934                    table_id,
935                    associated_source_id,
936                } => {
937                    self.report_source_load_finished(
938                        epoch,
939                        actor_id,
940                        table_id,
941                        associated_source_id,
942                    );
943                }
944                LocalBarrierEvent::RefreshFinished {
945                    epoch,
946                    actor_id,
947                    table_id,
948                } => {
949                    self.report_refresh_finished(epoch, actor_id, table_id);
950                }
951                LocalBarrierEvent::RegisterBarrierSender {
952                    actor_id,
953                    barrier_sender,
954                } => {
955                    if let Err(err) = self.register_barrier_sender(actor_id, barrier_sender) {
956                        return Poll::Ready(ManagedBarrierStateEvent::ActorError {
957                            actor_id,
958                            err,
959                            partial_graph_id: self.partial_graph_id,
960                        });
961                    }
962                }
963                LocalBarrierEvent::RegisterLocalUpstreamOutput {
964                    actor_id,
965                    upstream_actor_id,
966                    upstream_partial_graph_id,
967                    term_id,
968                    result_sender,
969                } => {
970                    return Poll::Ready(ManagedBarrierStateEvent::RegisterLocalUpstreamOutput {
971                        actor_id,
972                        upstream_actor_id,
973                        upstream_partial_graph_id,
974                        term_id,
975                        result_sender,
976                    });
977                }
978                LocalBarrierEvent::ReportCdcTableBackfillProgress {
979                    actor_id,
980                    epoch,
981                    state,
982                } => {
983                    self.update_cdc_table_backfill_progress(epoch, actor_id, state);
984                }
985                LocalBarrierEvent::ReportCdcSourceOffsetUpdated {
986                    epoch,
987                    actor_id,
988                    source_id,
989                } => {
990                    self.report_cdc_source_offset_updated(epoch, actor_id, source_id);
991                }
992                LocalBarrierEvent::ReportIcebergPkIndexSinkMetadata {
993                    epoch,
994                    sink_id,
995                    actor_id,
996                    role,
997                    metadata,
998                } => {
999                    self.report_iceberg_pk_index_sink_metadata(
1000                        epoch, sink_id, actor_id, role, metadata,
1001                    );
1002                }
1003            }
1004        }
1005
1006        debug_assert!(self.graph_state.may_have_collected_all().is_none());
1007        Poll::Pending
1008    }
1009}
1010
1011impl PartialGraphState {
1012    #[must_use]
1013    pub(super) fn collect(&mut self, actor_id: ActorId, epoch: EpochPair) -> Option<Barrier> {
1014        let is_finished = self
1015            .actor_states
1016            .get_mut(&actor_id)
1017            .expect("should exist")
1018            .collect(epoch);
1019        if is_finished {
1020            let state = self.actor_states.remove(&actor_id).expect("should exist");
1021            if let Some(monitor_task_handle) = state.monitor_task_handle {
1022                monitor_task_handle.abort();
1023            }
1024        }
1025        self.graph_state.collect(actor_id, epoch);
1026        self.graph_state.may_have_collected_all()
1027    }
1028
1029    pub(super) fn pop_barrier_to_complete(&mut self, prev_epoch: u64) -> BarrierToComplete {
1030        self.graph_state.pop_barrier_to_complete(prev_epoch)
1031    }
1032
1033    /// Collect actor errors for a while and find the one that might be the root cause.
1034    ///
1035    /// Returns `None` if there's no actor error received.
1036    async fn try_find_root_actor_failure(
1037        &mut self,
1038        first_failure: Option<(Option<ActorId>, StreamError)>,
1039    ) -> Option<ScoredStreamError> {
1040        let mut later_errs = vec![];
1041        // fetch more actor errors within a timeout
1042        let _ = tokio::time::timeout(Duration::from_secs(3), async {
1043            let mut uncollected_actors: HashSet<_> = self.actor_states.keys().cloned().collect();
1044            if let Some((Some(failed_actor), _)) = &first_failure {
1045                uncollected_actors.remove(failed_actor);
1046            }
1047            while !uncollected_actors.is_empty()
1048                && let Some((actor_id, error)) = self.actor_failure_rx.recv().await
1049            {
1050                uncollected_actors.remove(&actor_id);
1051                later_errs.push(error);
1052            }
1053        })
1054        .await;
1055
1056        first_failure
1057            .into_iter()
1058            .map(|(_, err)| err)
1059            .chain(later_errs)
1060            .map(|e| e.with_score())
1061            .max_by_key(|e| e.score)
1062    }
1063
1064    /// Report that a source has finished listing for a specific epoch
1065    pub(super) fn report_source_list_finished(
1066        &mut self,
1067        epoch: EpochPair,
1068        actor_id: ActorId,
1069        table_id: TableId,
1070        associated_source_id: SourceId,
1071    ) {
1072        // Find the correct partial graph state by matching the actor's partial graph id
1073        if let Some(actor_state) = self.actor_states.get(&actor_id)
1074            && actor_state.inflight_barriers.contains(&epoch.prev)
1075        {
1076            self.graph_state
1077                .event_mut(epoch)
1078                .list_finished_source_ids
1079                .push(PbListFinishedSource {
1080                    reporter_actor_id: actor_id,
1081                    table_id,
1082                    associated_source_id,
1083                });
1084        } else {
1085            warn!(
1086                ?epoch,
1087                %actor_id, %table_id, %associated_source_id, "ignore source list finished"
1088            );
1089        }
1090    }
1091
1092    /// Report that a source has finished loading for a specific epoch
1093    pub(super) fn report_source_load_finished(
1094        &mut self,
1095        epoch: EpochPair,
1096        actor_id: ActorId,
1097        table_id: TableId,
1098        associated_source_id: SourceId,
1099    ) {
1100        // Find the correct partial graph state by matching the actor's partial graph id
1101        if let Some(actor_state) = self.actor_states.get(&actor_id)
1102            && actor_state.inflight_barriers.contains(&epoch.prev)
1103        {
1104            self.graph_state
1105                .event_mut(epoch)
1106                .load_finished_source_ids
1107                .push(PbLoadFinishedSource {
1108                    reporter_actor_id: actor_id,
1109                    table_id,
1110                    associated_source_id,
1111                });
1112        } else {
1113            warn!(
1114                ?epoch,
1115                %actor_id, %table_id, %associated_source_id, "ignore source load finished"
1116            );
1117        }
1118    }
1119
1120    /// Report that a CDC source has updated its offset at least once
1121    pub(super) fn report_cdc_source_offset_updated(
1122        &mut self,
1123        epoch: EpochPair,
1124        actor_id: ActorId,
1125        source_id: SourceId,
1126    ) {
1127        if let Some(actor_state) = self.actor_states.get(&actor_id)
1128            && actor_state.inflight_barriers.contains(&epoch.prev)
1129        {
1130            self.graph_state
1131                .event_mut(epoch)
1132                .cdc_source_offset_updated
1133                .push(PbCdcSourceOffsetUpdated {
1134                    reporter_actor_id: actor_id,
1135                    source_id,
1136                });
1137        } else {
1138            warn!(
1139                ?epoch,
1140                %actor_id, %source_id, "ignore cdc source offset updated"
1141            );
1142        }
1143    }
1144
1145    /// Record a Iceberg pk-index sink metadata report.
1146    pub(super) fn report_iceberg_pk_index_sink_metadata(
1147        &mut self,
1148        epoch: EpochPair,
1149        sink_id: SinkId,
1150        actor_id: ActorId,
1151        role: PbIcebergPkIndexSinkRole,
1152        metadata: Option<SinkMetadata>,
1153    ) {
1154        if let Some(actor_state) = self.actor_states.get(&actor_id)
1155            && actor_state.inflight_barriers.contains(&epoch.prev)
1156        {
1157            self.graph_state
1158                .event_mut(epoch)
1159                .iceberg_pk_index_sink_metadata
1160                .push(PbIcebergPkIndexSinkMetadata {
1161                    sink_id,
1162                    reporter_actor_id: actor_id,
1163                    prev_epoch: epoch.prev,
1164                    role: role as i32,
1165                    metadata,
1166                });
1167        } else {
1168            tracing::warn!(
1169                ?epoch,
1170                %actor_id,
1171                %sink_id,
1172                ?role,
1173                "ignore iceberg v3 sink metadata report from non-inflight actor"
1174            );
1175        }
1176    }
1177
1178    /// Report that a materialize actor has finished its part of a table refresh for a specific epoch
1179    pub(super) fn report_refresh_finished(
1180        &mut self,
1181        epoch: EpochPair,
1182        actor_id: ActorId,
1183        table_id: TableId,
1184    ) {
1185        if let Some(actor_state) = self.actor_states.get(&actor_id)
1186            && actor_state.inflight_barriers.contains(&epoch.prev)
1187        {
1188            self.graph_state
1189                .event_mut(epoch)
1190                .refresh_finished_actors
1191                .push(PbRefreshFinishedActor {
1192                    reporter_actor_id: actor_id,
1193                    table_id,
1194                });
1195        } else {
1196            warn!(
1197                ?epoch,
1198                %actor_id, %table_id, "ignore refresh finished table"
1199            );
1200        }
1201    }
1202}
1203
1204impl PartialGraphManagedBarrierState {
1205    /// Check whether any `Issued` barrier has been collected by all actors and, if so,
1206    /// transition it to `AllCollected`.
1207    fn may_have_collected_all(&mut self) -> Option<Barrier> {
1208        for barrier_state in self.epoch_barrier_state_map.values_mut() {
1209            match &barrier_state.inner {
1210                ManagedBarrierStateInner::Issued(IssuedState {
1211                    remaining_actors, ..
1212                }) if remaining_actors.is_empty() => {}
1213                ManagedBarrierStateInner::AllCollected(_) => {
1214                    continue;
1215                }
1216                ManagedBarrierStateInner::Issued(_) => {
1217                    break;
1218                }
1219            }
1220
1221            self.barrier_manager_progress.inc();
1222
1223            let event = self
1224                .barrier_events
1225                .remove(&barrier_state.barrier.epoch.curr)
1226                .unwrap_or_else(|| EpochBarrierEvent::new(barrier_state.barrier.epoch));
1227            assert_eq!(event.epoch, barrier_state.barrier.epoch);
1228            let prev_state = replace(
1229                &mut barrier_state.inner,
1230                ManagedBarrierStateInner::AllCollected(event),
1231            );
1232
1233            must_match!(prev_state, ManagedBarrierStateInner::Issued(IssuedState {
1234                barrier_inflight_latency: timer,
1235                ..
1236            }) => {
1237                timer.observe_duration();
1238            });
1239
1240            return Some(barrier_state.barrier.clone());
1241        }
1242        None
1243    }
1244
1245    fn pop_barrier_to_complete(&mut self, prev_epoch: u64) -> BarrierToComplete {
1246        let (popped_prev_epoch, barrier_state) = self
1247            .epoch_barrier_state_map
1248            .pop_first()
1249            .expect("should exist");
1250
1251        assert_eq!(prev_epoch, popped_prev_epoch);
1252
1253        let event = must_match!(barrier_state.inner, ManagedBarrierStateInner::AllCollected(event) => event);
1254        assert_eq!(event.epoch, barrier_state.barrier.epoch);
1255        BarrierToComplete {
1256            barrier: barrier_state.barrier,
1257            table_ids: barrier_state.table_ids,
1258            event,
1259        }
1260    }
1261
1262    pub(super) fn barrier_sync_latency(&self) -> LabelGuardedHistogram {
1263        self.barrier_sync_latency.clone()
1264    }
1265}
1266
1267pub(crate) struct BarrierToComplete {
1268    pub barrier: Barrier,
1269    pub table_ids: Option<HashSet<TableId>>,
1270    pub event: EpochBarrierEvent,
1271}
1272
1273impl PartialGraphManagedBarrierState {
1274    /// Collect a `barrier` from the actor with `actor_id`.
1275    pub(super) fn collect(&mut self, actor_id: impl Into<ActorId>, epoch: EpochPair) {
1276        let actor_id = actor_id.into();
1277        tracing::debug!(
1278            target: "events::stream::barrier::manager::collect",
1279            ?epoch, %actor_id, state = ?self.epoch_barrier_state_map,
1280            "collect_barrier",
1281        );
1282
1283        match self.epoch_barrier_state_map.get_mut(&epoch.prev) {
1284            None => {
1285                // If the barrier's state is stashed, this occurs exclusively in scenarios where the barrier has not been
1286                // injected by the barrier manager, or the barrier message is blocked at the `RemoteInput` side waiting for injection.
1287                // Given these conditions, it's inconceivable for an actor to attempt collect at this point.
1288                panic!(
1289                    "cannot collect new actor barrier {:?} at current state: None",
1290                    epoch,
1291                )
1292            }
1293            Some(&mut BarrierState {
1294                ref barrier,
1295                inner:
1296                    ManagedBarrierStateInner::Issued(IssuedState {
1297                        ref mut remaining_actors,
1298                        ..
1299                    }),
1300                ..
1301            }) => {
1302                let exist = remaining_actors.remove(&actor_id);
1303                assert!(
1304                    exist,
1305                    "the actor doesn't exist. actor_id: {:?}, curr_epoch: {:?}",
1306                    actor_id, epoch.curr
1307                );
1308                assert_eq!(barrier.epoch.curr, epoch.curr);
1309            }
1310            Some(BarrierState { inner, .. }) => {
1311                panic!(
1312                    "cannot collect new actor barrier {:?} at current state: {:?}",
1313                    epoch, inner
1314                )
1315            }
1316        }
1317    }
1318
1319    /// When the meta service issues a `send_barrier` request, call this function to transform to
1320    /// `Issued` and start to collect or to notify.
1321    pub(super) fn transform_to_issued(
1322        &mut self,
1323        barrier: &Barrier,
1324        actor_ids_to_collect: impl IntoIterator<Item = ActorId>,
1325        table_ids: HashSet<TableId>,
1326    ) {
1327        let timer = self.barrier_inflight_latency.start_timer();
1328
1329        if let Some(hummock) = self.state_store.as_hummock() {
1330            hummock.start_epoch(barrier.epoch.curr, table_ids.clone());
1331        }
1332
1333        let table_ids = match barrier.kind {
1334            BarrierKind::Unspecified => {
1335                unreachable!()
1336            }
1337            BarrierKind::Initial => {
1338                assert!(
1339                    self.prev_barrier_table_ids.is_none(),
1340                    "non empty table_ids at initial barrier: {:?}",
1341                    self.prev_barrier_table_ids
1342                );
1343                info!(epoch = ?barrier.epoch, "initialize at Initial barrier");
1344                self.prev_barrier_table_ids = Some((barrier.epoch, table_ids));
1345                None
1346            }
1347            BarrierKind::Barrier => {
1348                if let Some((prev_epoch, prev_table_ids)) = self.prev_barrier_table_ids.as_mut() {
1349                    assert_eq!(prev_epoch.curr, barrier.epoch.prev);
1350                    assert_eq!(prev_table_ids, &table_ids);
1351                    *prev_epoch = barrier.epoch;
1352                } else {
1353                    info!(epoch = ?barrier.epoch, "initialize at non-checkpoint barrier");
1354                    self.prev_barrier_table_ids = Some((barrier.epoch, table_ids));
1355                }
1356                None
1357            }
1358            BarrierKind::Checkpoint => Some(
1359                if let Some((prev_epoch, prev_table_ids)) = self
1360                    .prev_barrier_table_ids
1361                    .replace((barrier.epoch, table_ids))
1362                    && prev_epoch.curr == barrier.epoch.prev
1363                {
1364                    prev_table_ids
1365                } else {
1366                    debug!(epoch = ?barrier.epoch, "reinitialize at Checkpoint barrier");
1367                    HashSet::new()
1368                },
1369            ),
1370        };
1371
1372        if let Some(&mut BarrierState { ref inner, .. }) =
1373            self.epoch_barrier_state_map.get_mut(&barrier.epoch.prev)
1374        {
1375            {
1376                panic!(
1377                    "barrier epochs{:?} state has already been `Issued`. Current state: {:?}",
1378                    barrier.epoch, inner
1379                );
1380            }
1381        };
1382
1383        self.epoch_barrier_state_map.insert(
1384            barrier.epoch.prev,
1385            BarrierState {
1386                barrier: barrier.clone(),
1387                inner: ManagedBarrierStateInner::Issued(IssuedState {
1388                    remaining_actors: BTreeSet::from_iter(actor_ids_to_collect),
1389                    barrier_inflight_latency: timer,
1390                }),
1391                table_ids,
1392            },
1393        );
1394    }
1395
1396    #[cfg(test)]
1397    async fn pop_next_completed_epoch(&mut self) -> u64 {
1398        if let Some(barrier) = self.may_have_collected_all() {
1399            self.pop_barrier_to_complete(barrier.epoch.prev);
1400            return barrier.epoch.prev;
1401        }
1402        pending().await
1403    }
1404}
1405
1406#[cfg(test)]
1407mod tests {
1408    use std::collections::HashSet;
1409
1410    use risingwave_common::util::epoch::test_epoch;
1411
1412    use crate::executor::Barrier;
1413    use crate::task::barrier_worker::managed_state::PartialGraphManagedBarrierState;
1414
1415    #[tokio::test]
1416    async fn test_managed_state_add_actor() {
1417        let mut managed_barrier_state = PartialGraphManagedBarrierState::for_test();
1418        let barrier1 = Barrier::new_test_barrier(test_epoch(1));
1419        let barrier2 = Barrier::new_test_barrier(test_epoch(2));
1420        let barrier3 = Barrier::new_test_barrier(test_epoch(3));
1421        let actor_ids_to_collect1 = HashSet::from([1.into(), 2.into()]);
1422        let actor_ids_to_collect2 = HashSet::from([1.into(), 2.into()]);
1423        let actor_ids_to_collect3 = HashSet::from([1.into(), 2.into(), 3.into()]);
1424        managed_barrier_state.transform_to_issued(&barrier1, actor_ids_to_collect1, HashSet::new());
1425        managed_barrier_state.transform_to_issued(&barrier2, actor_ids_to_collect2, HashSet::new());
1426        managed_barrier_state.transform_to_issued(&barrier3, actor_ids_to_collect3, HashSet::new());
1427        managed_barrier_state.collect(1, barrier1.epoch);
1428        managed_barrier_state.collect(2, barrier1.epoch);
1429        assert_eq!(
1430            managed_barrier_state.pop_next_completed_epoch().await,
1431            test_epoch(0)
1432        );
1433        assert_eq!(
1434            managed_barrier_state
1435                .epoch_barrier_state_map
1436                .first_key_value()
1437                .unwrap()
1438                .0,
1439            &test_epoch(1)
1440        );
1441        managed_barrier_state.collect(1, barrier2.epoch);
1442        managed_barrier_state.collect(1, barrier3.epoch);
1443        managed_barrier_state.collect(2, barrier2.epoch);
1444        assert_eq!(
1445            managed_barrier_state.pop_next_completed_epoch().await,
1446            test_epoch(1)
1447        );
1448        assert_eq!(
1449            managed_barrier_state
1450                .epoch_barrier_state_map
1451                .first_key_value()
1452                .unwrap()
1453                .0,
1454            &test_epoch(2)
1455        );
1456        managed_barrier_state.collect(2, barrier3.epoch);
1457        managed_barrier_state.collect(3, barrier3.epoch);
1458        assert_eq!(
1459            managed_barrier_state.pop_next_completed_epoch().await,
1460            test_epoch(2)
1461        );
1462        assert!(managed_barrier_state.epoch_barrier_state_map.is_empty());
1463    }
1464
1465    #[tokio::test]
1466    async fn test_managed_state_stop_actor() {
1467        let mut managed_barrier_state = PartialGraphManagedBarrierState::for_test();
1468        let barrier1 = Barrier::new_test_barrier(test_epoch(1));
1469        let barrier2 = Barrier::new_test_barrier(test_epoch(2));
1470        let barrier3 = Barrier::new_test_barrier(test_epoch(3));
1471        let actor_ids_to_collect1 = HashSet::from([1.into(), 2.into(), 3.into(), 4.into()]);
1472        let actor_ids_to_collect2 = HashSet::from([1.into(), 2.into(), 3.into()]);
1473        let actor_ids_to_collect3 = HashSet::from([1.into(), 2.into()]);
1474        managed_barrier_state.transform_to_issued(&barrier1, actor_ids_to_collect1, HashSet::new());
1475        managed_barrier_state.transform_to_issued(&barrier2, actor_ids_to_collect2, HashSet::new());
1476        managed_barrier_state.transform_to_issued(&barrier3, actor_ids_to_collect3, HashSet::new());
1477
1478        managed_barrier_state.collect(1, barrier1.epoch);
1479        managed_barrier_state.collect(1, barrier2.epoch);
1480        managed_barrier_state.collect(1, barrier3.epoch);
1481        managed_barrier_state.collect(2, barrier1.epoch);
1482        managed_barrier_state.collect(2, barrier2.epoch);
1483        managed_barrier_state.collect(2, barrier3.epoch);
1484        assert_eq!(
1485            managed_barrier_state
1486                .epoch_barrier_state_map
1487                .first_key_value()
1488                .unwrap()
1489                .0,
1490            &0
1491        );
1492        managed_barrier_state.collect(3, barrier1.epoch);
1493        managed_barrier_state.collect(3, barrier2.epoch);
1494        assert_eq!(
1495            managed_barrier_state
1496                .epoch_barrier_state_map
1497                .first_key_value()
1498                .unwrap()
1499                .0,
1500            &0
1501        );
1502        managed_barrier_state.collect(4, barrier1.epoch);
1503        assert_eq!(
1504            managed_barrier_state.pop_next_completed_epoch().await,
1505            test_epoch(0)
1506        );
1507        assert_eq!(
1508            managed_barrier_state.pop_next_completed_epoch().await,
1509            test_epoch(1)
1510        );
1511        assert_eq!(
1512            managed_barrier_state.pop_next_completed_epoch().await,
1513            test_epoch(2)
1514        );
1515        assert!(managed_barrier_state.epoch_barrier_state_map.is_empty());
1516    }
1517}