Skip to main content

risingwave_meta/barrier/
command.rs

1// Copyright 2022 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::{HashMap, HashSet};
16use std::fmt::{Display, Formatter};
17
18use chrono::NaiveDateTime;
19use itertools::Itertools;
20use risingwave_common::bitmap::Bitmap;
21use risingwave_common::catalog::{DatabaseId, TableId};
22use risingwave_common::hash::{ActorMapping, VnodeCountCompat};
23use risingwave_common::id::{JobId, SinkId, SourceId};
24use risingwave_common::must_match;
25use risingwave_connector::sink::iceberg::IcebergCommitResult;
26use risingwave_connector::source::{CdcTableSnapshotSplitRaw, SplitImpl};
27use risingwave_hummock_sdk::change_log::build_table_change_log_delta;
28use risingwave_hummock_sdk::vector_index::VectorIndexDelta;
29use risingwave_meta_model::{DispatcherType, WorkerId, fragment_relation, streaming_job};
30use risingwave_pb::catalog::CreateType;
31use risingwave_pb::common::PbActorInfo;
32use risingwave_pb::hummock::vector_index_delta::PbVectorIndexInit;
33use risingwave_pb::plan_common::{ColumnCatalog as PbColumnCatalog, PbField};
34use risingwave_pb::source::{
35    ConnectorSplit, ConnectorSplits, PbCdcTableSnapshotSplits,
36    PbCdcTableSnapshotSplitsWithGeneration,
37};
38use risingwave_pb::stream_plan::add_mutation::PbNewUpstreamSink;
39use risingwave_pb::stream_plan::barrier::BarrierKind as PbBarrierKind;
40use risingwave_pb::stream_plan::barrier_mutation::Mutation;
41use risingwave_pb::stream_plan::connector_props_change_mutation::ConnectorPropsInfo;
42use risingwave_pb::stream_plan::sink_schema_change::Op as PbSinkSchemaChangeOp;
43use risingwave_pb::stream_plan::throttle_mutation::ThrottleConfig;
44use risingwave_pb::stream_plan::update_mutation::{DispatcherUpdate, MergeUpdate};
45use risingwave_pb::stream_plan::{
46    AddMutation, ConnectorPropsChangeMutation, Dispatcher, DropSubscriptionsMutation,
47    ListFinishMutation, LoadFinishMutation, PauseMutation, PbSinkAddColumnsOp, PbSinkDropColumnsOp,
48    PbSinkSchemaChange, PbStreamNode, PbUpstreamSinkInfo, ResumeMutation,
49    SourceChangeSplitMutation, StartFragmentBackfillMutation, StopMutation,
50    SubscriptionUpstreamInfo, ThrottleMutation, UpdateMutation,
51};
52use risingwave_pb::stream_service::BarrierCompleteResponse;
53use tracing::warn;
54
55use super::info::InflightDatabaseInfo;
56use crate::barrier::backfill_order_control::get_nodes_with_backfill_dependencies;
57use crate::barrier::complete_task::CompleteBarrierTask;
58use crate::barrier::edge_builder::FragmentEdgeBuildResult;
59use crate::barrier::partial_graph::PartialGraphBarrierInfo;
60use crate::barrier::rpc::{ControlStreamManager, to_partial_graph_id};
61use crate::barrier::utils::{collect_new_vector_index_info, collect_resp_info};
62use crate::controller::fragment::{InflightActorInfo, InflightFragmentInfo};
63use crate::controller::scale::LoadedFragmentContext;
64use crate::controller::utils::StreamingJobExtraInfo;
65use crate::hummock::NewTableFragmentInfo;
66use crate::manager::{StreamingJob, StreamingJobType};
67use crate::model::{
68    ActorId, ActorUpstreams, DispatcherId, FragmentDownstreamRelation, FragmentId,
69    FragmentReplaceUpstream, StreamActor, StreamActorWithDispatchers, StreamJobActorsToCreate,
70    StreamJobFragments, StreamJobFragmentsToCreate, SubscriptionId,
71};
72use crate::stream::{
73    AutoRefreshSchemaSinkContext, ConnectorPropsChange, ExtendedFragmentBackfillOrder,
74    RefreshCycleActors, ReplaceJobSplitPlan, SourceSplitAssignment, SplitAssignment, SplitState,
75    UpstreamSinkInfo, build_actor_connector_splits,
76};
77use crate::{MetaError, MetaResult};
78
79pub(crate) type ThrottleConfigMap = HashMap<FragmentId, (ThrottleConfig, PbStreamNode)>;
80
81pub(crate) fn extract_throttle_config(
82    config: &mut ThrottleConfigMap,
83    mut apply: impl FnMut(FragmentId, &PbStreamNode) -> bool,
84) -> Option<Mutation> {
85    let fragment_throttle = config
86        .extract_if(|fragment_id, (_, stream_node)| apply(*fragment_id, stream_node))
87        .map(|(fragment_id, (throttle_config, _))| (fragment_id, throttle_config))
88        .collect::<HashMap<_, _>>();
89    (!fragment_throttle.is_empty())
90        .then_some(Mutation::Throttle(ThrottleMutation { fragment_throttle }))
91}
92
93/// [`Reschedule`] describes per-fragment changes in a resolved reschedule plan,
94/// used for actor scaling or migration.
95#[derive(Debug, Clone)]
96pub struct Reschedule {
97    /// Added actors in this fragment.
98    pub added_actors: HashMap<WorkerId, Vec<ActorId>>,
99
100    /// Removed actors in this fragment.
101    pub removed_actors: HashSet<ActorId>,
102
103    /// Vnode bitmap updates for some actors in this fragment.
104    pub vnode_bitmap_updates: HashMap<ActorId, Bitmap>,
105
106    /// The upstream fragments of this fragment, and the dispatchers that should be updated.
107    pub upstream_fragment_dispatcher_ids: Vec<(FragmentId, DispatcherId)>,
108    /// New hash mapping of the upstream dispatcher to be updated.
109    ///
110    /// This field exists only when there's upstream fragment and the current fragment is
111    /// hash-sharded.
112    pub upstream_dispatcher_mapping: Option<ActorMapping>,
113
114    /// The downstream fragments of this fragment.
115    pub downstream_fragment_ids: Vec<FragmentId>,
116
117    /// Reassigned splits for source actors.
118    /// It becomes the `actor_splits` in [`UpdateMutation`].
119    /// `Source` and `SourceBackfill` are handled together here.
120    pub actor_splits: HashMap<ActorId, Vec<SplitImpl>>,
121
122    pub newly_created_actors: HashMap<ActorId, (StreamActorWithDispatchers, WorkerId)>,
123}
124
125#[derive(Debug, Clone)]
126pub struct ReschedulePlan {
127    pub reschedules: HashMap<FragmentId, Reschedule>,
128    /// Should contain the actor ids in upstream and downstream fragments referenced by
129    /// `reschedules`.
130    pub fragment_actors: HashMap<FragmentId, HashSet<ActorId>>,
131}
132
133/// Preloaded context for rescheduling, built outside the barrier worker.
134#[derive(Debug, Clone)]
135pub struct RescheduleContext {
136    pub loaded: LoadedFragmentContext,
137    pub job_extra_info: HashMap<JobId, StreamingJobExtraInfo>,
138    pub upstream_fragments: HashMap<FragmentId, HashMap<FragmentId, DispatcherType>>,
139    pub downstream_fragments: HashMap<FragmentId, HashMap<FragmentId, DispatcherType>>,
140    pub downstream_relations: HashMap<(FragmentId, FragmentId), fragment_relation::Model>,
141}
142
143impl RescheduleContext {
144    pub fn empty() -> Self {
145        Self {
146            loaded: LoadedFragmentContext::default(),
147            job_extra_info: HashMap::new(),
148            upstream_fragments: HashMap::new(),
149            downstream_fragments: HashMap::new(),
150            downstream_relations: HashMap::new(),
151        }
152    }
153
154    pub fn is_empty(&self) -> bool {
155        self.loaded.is_empty()
156    }
157
158    pub fn for_database(&self, database_id: DatabaseId) -> Option<Self> {
159        let loaded = self.loaded.for_database(database_id)?;
160        let job_ids: HashSet<JobId> = loaded.job_map.keys().copied().collect();
161        // Use the filtered loaded context as the source of truth so every side map is pruned by
162        // the same fragment set.
163        let fragment_ids: HashSet<FragmentId> = loaded
164            .job_fragments
165            .values()
166            .flat_map(|fragments| fragments.keys().copied())
167            .collect();
168
169        let job_extra_info = self
170            .job_extra_info
171            .iter()
172            .filter(|(job_id, _)| job_ids.contains(*job_id))
173            .map(|(job_id, info)| (*job_id, info.clone()))
174            .collect();
175
176        let upstream_fragments = self
177            .upstream_fragments
178            .iter()
179            .filter(|(fragment_id, _)| fragment_ids.contains(*fragment_id))
180            .map(|(fragment_id, upstreams)| (*fragment_id, upstreams.clone()))
181            .collect();
182
183        let downstream_fragments = self
184            .downstream_fragments
185            .iter()
186            .filter(|(fragment_id, _)| fragment_ids.contains(*fragment_id))
187            .map(|(fragment_id, downstreams)| (*fragment_id, downstreams.clone()))
188            .collect();
189
190        let downstream_relations = self
191            .downstream_relations
192            .iter()
193            // Ownership of this map is source-fragment based. We keep all downstream edges for
194            // selected sources because the target side can still be referenced during dispatcher
195            // reconstruction even if that target fragment is not being rescheduled.
196            .filter(|((source_fragment_id, _), _)| fragment_ids.contains(source_fragment_id))
197            .map(|(key, relation)| (*key, relation.clone()))
198            .collect();
199
200        Some(Self {
201            loaded,
202            job_extra_info,
203            upstream_fragments,
204            downstream_fragments,
205            downstream_relations,
206        })
207    }
208
209    /// Split this context into per-database contexts without cloning the large loaded graph
210    /// payloads.
211    pub fn into_database_contexts(self) -> HashMap<DatabaseId, Self> {
212        let Self {
213            loaded,
214            job_extra_info,
215            upstream_fragments,
216            downstream_fragments,
217            downstream_relations,
218        } = self;
219
220        let mut contexts: HashMap<_, _> = loaded
221            .into_database_contexts()
222            .into_iter()
223            .map(|(database_id, loaded)| {
224                (
225                    database_id,
226                    Self {
227                        loaded,
228                        job_extra_info: HashMap::new(),
229                        upstream_fragments: HashMap::new(),
230                        downstream_fragments: HashMap::new(),
231                        downstream_relations: HashMap::new(),
232                    },
233                )
234            })
235            .collect();
236
237        if contexts.is_empty() {
238            return contexts;
239        }
240
241        let mut job_databases = HashMap::new();
242        let mut fragment_databases = HashMap::new();
243        for (&database_id, context) in &contexts {
244            for job_id in context.loaded.job_map.keys().copied() {
245                job_databases.insert(job_id, database_id);
246            }
247            for fragment_id in context
248                .loaded
249                .job_fragments
250                .values()
251                .flat_map(|fragments| fragments.keys().copied())
252            {
253                fragment_databases.insert(fragment_id, database_id);
254            }
255        }
256
257        for (job_id, info) in job_extra_info {
258            if let Some(database_id) = job_databases.get(&job_id).copied() {
259                contexts
260                    .get_mut(&database_id)
261                    .expect("database context should exist for job")
262                    .job_extra_info
263                    .insert(job_id, info);
264            }
265        }
266
267        for (fragment_id, upstreams) in upstream_fragments {
268            if let Some(database_id) = fragment_databases.get(&fragment_id).copied() {
269                contexts
270                    .get_mut(&database_id)
271                    .expect("database context should exist for fragment")
272                    .upstream_fragments
273                    .insert(fragment_id, upstreams);
274            }
275        }
276
277        for (fragment_id, downstreams) in downstream_fragments {
278            if let Some(database_id) = fragment_databases.get(&fragment_id).copied() {
279                contexts
280                    .get_mut(&database_id)
281                    .expect("database context should exist for fragment")
282                    .downstream_fragments
283                    .insert(fragment_id, downstreams);
284            }
285        }
286
287        for ((source_fragment_id, target_fragment_id), relation) in downstream_relations {
288            // Route by source fragment ownership. A target may be outside of current reschedule
289            // set, but this edge still belongs to the source-side command.
290            if let Some(database_id) = fragment_databases.get(&source_fragment_id).copied() {
291                contexts
292                    .get_mut(&database_id)
293                    .expect("database context should exist for relation source")
294                    .downstream_relations
295                    .insert((source_fragment_id, target_fragment_id), relation);
296            }
297        }
298
299        contexts
300    }
301}
302
303/// Replacing an old job with a new one. All actors in the job will be rebuilt.
304///
305/// Current use cases:
306/// - `ALTER SOURCE` (via [`Command::ReplaceStreamJob`]) will replace a source job's plan.
307/// - `ALTER TABLE` (via [`Command::ReplaceStreamJob`]) and `CREATE SINK INTO table` ([`Command::CreateStreamingJob`])
308///   will replace a table job's plan.
309#[derive(Debug, Clone)]
310pub struct ReplaceStreamJobPlan {
311    pub old_fragments: StreamJobFragments,
312    pub new_fragments: StreamJobFragmentsToCreate,
313    /// The resource group of the database this job belongs to.
314    pub database_resource_group: String,
315    /// Downstream jobs of the replaced job need to update their `Merge` node to
316    /// connect to the new fragment.
317    pub replace_upstream: FragmentReplaceUpstream,
318    pub upstream_fragment_downstreams: FragmentDownstreamRelation,
319    /// Split plan for the replace job. Determines how splits are resolved in Phase 2
320    /// inside the barrier worker.
321    pub split_plan: ReplaceJobSplitPlan,
322    /// The `StreamingJob` info of the table to be replaced. Must be `StreamingJob::Table`
323    pub streaming_job: StreamingJob,
324    /// The `streaming_job::Model` for this job, loaded from meta store.
325    pub streaming_job_model: streaming_job::Model,
326    /// The temporary dummy job fragments id of new table fragment
327    pub tmp_id: JobId,
328    /// The state table ids to be dropped.
329    pub to_drop_state_table_ids: Vec<TableId>,
330    pub auto_refresh_schema_sinks: Option<Vec<AutoRefreshSchemaSinkContext>>,
331}
332
333impl ReplaceStreamJobPlan {
334    /// `old_fragment_id` -> `new_fragment_id`
335    pub fn fragment_replacements(&self) -> HashMap<FragmentId, FragmentId> {
336        let mut fragment_replacements = HashMap::new();
337        for (upstream_fragment_id, new_upstream_fragment_id) in
338            self.replace_upstream.values().flatten()
339        {
340            {
341                let r =
342                    fragment_replacements.insert(*upstream_fragment_id, *new_upstream_fragment_id);
343                if let Some(r) = r {
344                    assert_eq!(
345                        *new_upstream_fragment_id, r,
346                        "one fragment is replaced by multiple fragments"
347                    );
348                }
349            }
350        }
351        fragment_replacements
352    }
353}
354
355#[derive(educe::Educe, Clone)]
356#[educe(Debug)]
357pub struct CreateStreamingJobCommandInfo {
358    #[educe(Debug(ignore))]
359    pub stream_job_fragments: StreamJobFragmentsToCreate,
360    pub upstream_fragment_downstreams: FragmentDownstreamRelation,
361    /// The resource group of the database this job belongs to.
362    pub database_resource_group: String,
363    /// Source-level split assignment (Phase 1). Resolved to actor-level in the barrier worker.
364    pub init_split_assignment: SourceSplitAssignment,
365    pub definition: String,
366    pub job_type: StreamingJobType,
367    pub create_type: CreateType,
368    pub streaming_job: StreamingJob,
369    pub fragment_backfill_ordering: ExtendedFragmentBackfillOrder,
370    pub cdc_table_snapshot_splits: Option<Vec<CdcTableSnapshotSplitRaw>>,
371    pub locality_fragment_state_table_mapping: HashMap<FragmentId, Vec<TableId>>,
372    pub is_serverless: bool,
373    /// The `streaming_job::Model` for this job, loaded from meta store.
374    pub streaming_job_model: streaming_job::Model,
375    /// If set, this create command replaces an existing sink while creating the new sink job.
376    pub replace_sink: Option<SinkId>,
377    /// Batch refresh interval in seconds. If set, the MV uses batch refresh semantics.
378    pub refresh_interval_sec: Option<u64>,
379}
380
381impl StreamJobFragments {
382    /// Build fragment-level info for new fragments, populating actor infos from the
383    /// rendered actors and their locations, and applying split assignment to actor splits.
384    pub(super) fn new_fragment_info<'a>(
385        &'a self,
386        stream_actors: &'a HashMap<FragmentId, Vec<StreamActor>>,
387        actor_location: &'a HashMap<ActorId, WorkerId>,
388        assignment: &'a SplitAssignment,
389    ) -> impl Iterator<Item = (FragmentId, InflightFragmentInfo)> + 'a {
390        self.fragments.values().map(|fragment| {
391            (
392                fragment.fragment_id,
393                InflightFragmentInfo {
394                    fragment_id: fragment.fragment_id,
395                    distribution_type: fragment.distribution_type.into(),
396                    fragment_type_mask: fragment.fragment_type_mask,
397                    vnode_count: fragment.vnode_count(),
398                    nodes: fragment.nodes.clone(),
399                    actors: stream_actors
400                        .get(&fragment.fragment_id)
401                        .into_iter()
402                        .flatten()
403                        .map(|actor| {
404                            (
405                                actor.actor_id,
406                                InflightActorInfo {
407                                    worker_id: actor_location[&actor.actor_id],
408                                    vnode_bitmap: actor.vnode_bitmap.clone(),
409                                    splits: assignment
410                                        .get(&fragment.fragment_id)
411                                        .and_then(|s| s.get(&actor.actor_id))
412                                        .cloned()
413                                        .unwrap_or_default(),
414                                },
415                            )
416                        })
417                        .collect(),
418                    state_table_ids: fragment.state_table_ids.iter().copied().collect(),
419                },
420            )
421        })
422    }
423}
424
425pub type TableLogEpochs = Vec<(Vec<u64>, u64)>;
426pub type UpstreamTableLogEpochs = HashMap<TableId, TableLogEpochs>;
427pub type SinceTimestampResolvedEpoch = (u64, TableLogEpochs);
428
429#[derive(Debug, Clone)]
430pub struct SnapshotBackfillInfo {
431    /// `table_id` -> `Some(snapshot_backfill_epoch)`
432    /// The `snapshot_backfill_epoch` should be None at the beginning, and be filled
433    /// by global barrier worker when handling the command.
434    pub upstream_mv_table_id_to_backfill_epoch: HashMap<TableId, Option<u64>>,
435}
436
437#[derive(Debug, Clone)]
438pub struct SinceEpochInfo {
439    pub provided_since_epoch: u64,
440    pub resolved: Option<SinceTimestampResolvedEpoch>,
441}
442
443#[derive(Debug, Clone)]
444pub enum IndependentStreamingJobType {
445    SnapshotBackfill { since_epoch: Option<SinceEpochInfo> },
446    BatchRefresh { refresh_interval_sec: u64 },
447    IcebergV3,
448}
449
450#[derive(Debug, Clone)]
451pub enum CreateStreamingJobType {
452    Normal,
453    SinkIntoTable(UpstreamSinkInfo),
454    Independent {
455        snapshot_backfill_info: SnapshotBackfillInfo,
456        kind: IndependentStreamingJobType,
457    },
458}
459
460/// [`Command`] is the input of [`crate::barrier::worker::GlobalBarrierWorker`]. For different commands,
461/// it will build different barriers to send via corresponding `*_to_mutation` helpers,
462/// and may [do different stuffs after the barrier is collected](PostCollectCommand::post_collect).
463// FIXME: this enum is significantly large on stack, box it
464#[derive(Debug)]
465pub enum Command {
466    /// `Flush` command will generate a checkpoint barrier. After the barrier is collected and committed
467    /// all messages before the checkpoint barrier should have been committed.
468    Flush,
469
470    /// `Pause` command generates a `Pause` barrier **only if**
471    /// the cluster is not already paused. Otherwise, a barrier with no mutation will be generated.
472    Pause,
473
474    /// `Resume` command generates a `Resume` barrier **only
475    /// if** the cluster is paused with the same reason. Otherwise, a barrier with no mutation
476    /// will be generated.
477    Resume,
478
479    /// `DropStreamingJobs` command generates a `Stop` barrier to stop the given
480    /// [`Vec<ActorId>`]. The catalog has ensured that these streaming jobs are safe to be
481    /// dropped by reference counts before.
482    ///
483    /// Barriers from the actors to be dropped will STILL be collected.
484    /// After the barrier is collected, it notifies the local stream manager of compute nodes to
485    /// drop actors, and then delete the job fragments info from meta store.
486    DropStreamingJobs {
487        streaming_job_ids: HashSet<JobId>,
488        /// Used by recovery quick path when draining buffered drop/cancel commands.
489        unregistered_state_table_ids: HashSet<TableId>,
490        // target_fragment -> [sink_fragments]
491        dropped_sink_fragment_by_targets: HashMap<FragmentId, Vec<FragmentId>>,
492    },
493
494    /// `CreateStreamingJob` command generates a `Add` barrier by given info.
495    ///
496    /// Barriers from the actors to be created, which is marked as `Inactive` at first, will STILL
497    /// be collected since the barrier should be passthrough.
498    ///
499    /// After the barrier is collected, these newly created actors will be marked as `Running`. And
500    /// it adds the job fragments info to meta store. However, the creating progress will **last
501    /// for a while** until the `finish` channel is signaled, then the state of `TableFragments`
502    /// will be set to `Created`.
503    CreateStreamingJob {
504        info: CreateStreamingJobCommandInfo,
505        job_type: CreateStreamingJobType,
506        cross_db_snapshot_backfill_info: SnapshotBackfillInfo,
507    },
508
509    /// Reschedule context. It must be resolved inside the barrier worker before injection.
510    RescheduleIntent {
511        context: RescheduleContext,
512        /// Filled by the barrier worker after resolving `context` against current worker topology.
513        ///
514        /// We keep unresolved `context` outside of checkpoint state and only materialize this
515        /// execution plan right before injection, then drop `context` to release memory earlier.
516        reschedule_plan: Option<ReschedulePlan>,
517    },
518
519    /// `ReplaceStreamJob` command generates a `Update` barrier with the given `replace_upstream`. This is
520    /// essentially switching the downstream of the old job fragments to the new ones, and
521    /// dropping the old job fragments. Used for schema change.
522    ///
523    /// This can be treated as a special case of reschedule, while the upstream fragment
524    /// of the Merge executors are changed additionally.
525    ReplaceStreamJob(ReplaceStreamJobPlan),
526
527    /// `SourceChangeSplit` generates a `Splits` barrier for pushing initialized splits or
528    /// changed splits.
529    SourceChangeSplit(SplitState),
530
531    /// `Throttle` command generates a `Throttle` barrier with the given throttle config to change
532    /// the `rate_limit` of executors. `throttle_type` specifies which executor kinds should apply it.
533    Throttle {
534        config: ThrottleConfigMap,
535    },
536
537    /// `CreateSubscription` command generates a `CreateSubscriptionMutation` to notify
538    /// materialize executor to start storing old value for subscription.
539    CreateSubscription {
540        subscription_id: SubscriptionId,
541        upstream_mv_table_id: TableId,
542        retention_second: u64,
543    },
544
545    /// `DropSubscription` command generates a `DropSubscriptionsMutation` to notify
546    /// materialize executor to stop storing old value when there is no
547    /// subscription depending on it.
548    DropSubscription {
549        subscription_id: SubscriptionId,
550        upstream_mv_table_id: TableId,
551    },
552
553    /// `AlterSubscriptionRetention` command updates the subscription retention time.
554    AlterSubscriptionRetention {
555        subscription_id: SubscriptionId,
556        upstream_mv_table_id: TableId,
557        retention_second: u64,
558    },
559
560    ConnectorPropsChange(ConnectorPropsChange),
561
562    /// Starts the refresh cycle `trigger_time` of a table: the barrier's commit truncates the
563    /// staging table, which an abandoned cycle leaves dirty, and its post-collect moves the job to
564    /// `Refreshing`.
565    Refresh {
566        table_id: TableId,
567        associated_source_id: SourceId,
568        staging_table_id: TableId,
569        trigger_time: NaiveDateTime,
570    },
571    ListFinish {
572        table_id: TableId,
573        associated_source_id: SourceId,
574    },
575    LoadFinish {
576        table_id: TableId,
577        associated_source_id: SourceId,
578    },
579    /// Ends the refresh cycle `trigger_time` of a table once every materialize actor merged: the
580    /// barrier's commit truncates the staging table, which nothing reads after the merge, and its
581    /// post-collect moves the job back to `Idle`.
582    FinishRefresh {
583        table_id: TableId,
584        staging_table_id: TableId,
585        trigger_time: NaiveDateTime,
586    },
587
588    /// `ResetSource` command generates a barrier to reset CDC source offset to latest.
589    /// Used when upstream binlog/oplog has expired.
590    ResetSource {
591        source_id: SourceId,
592    },
593
594    /// `ResumeBackfill` command generates a `StartFragmentBackfill` barrier to force backfill
595    /// to resume for troubleshooting.
596    ResumeBackfill {
597        target: ResumeBackfillTarget,
598    },
599
600    /// `InjectSourceOffsets` command generates a barrier to inject specific offsets
601    /// into source splits (UNSAFE - admin only).
602    /// This can cause data duplication or loss depending on the correctness of the provided offsets.
603    InjectSourceOffsets {
604        source_id: SourceId,
605        /// Split ID -> offset (JSON-encoded based on connector type)
606        split_offsets: HashMap<String, String>,
607    },
608
609    /// Apply a completed Iceberg data-file compaction to the pk-index sink graph.
610    ApplyIcebergPkIndexCompaction {
611        sink_id: SinkId,
612        task_id: risingwave_pb::id::IcebergCompactionTaskId,
613        overwrite: IcebergPkIndexCompactionOverwrite,
614    },
615}
616
617#[derive(Clone, educe::Educe)]
618#[educe(Debug)]
619pub struct IcebergPkIndexCompactionOverwrite {
620    #[educe(Debug(ignore))]
621    pub output_result: IcebergCommitResult,
622    pub input_file_paths: Vec<String>,
623    pub read_snapshot_id: i64,
624}
625
626#[derive(Debug, Clone, Copy)]
627pub enum ResumeBackfillTarget {
628    Job(JobId),
629    Fragment(FragmentId),
630}
631
632// For debugging and observability purposes. Can add more details later if needed.
633impl std::fmt::Display for Command {
634    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
635        match self {
636            Command::Flush => write!(f, "Flush"),
637            Command::Pause => write!(f, "Pause"),
638            Command::Resume => write!(f, "Resume"),
639            Command::DropStreamingJobs {
640                streaming_job_ids, ..
641            } => {
642                write!(
643                    f,
644                    "DropStreamingJobs: {}",
645                    streaming_job_ids.iter().sorted().join(", ")
646                )
647            }
648            Command::CreateStreamingJob { info, .. } => {
649                write!(f, "CreateStreamingJob: {}", info.streaming_job)
650            }
651            Command::RescheduleIntent {
652                reschedule_plan, ..
653            } => {
654                if reschedule_plan.is_some() {
655                    write!(f, "RescheduleIntent(planned)")
656                } else {
657                    write!(f, "RescheduleIntent")
658                }
659            }
660            Command::ReplaceStreamJob(plan) => {
661                write!(f, "ReplaceStreamJob: {}", plan.streaming_job)
662            }
663            Command::SourceChangeSplit { .. } => write!(f, "SourceChangeSplit"),
664            Command::Throttle { .. } => write!(f, "Throttle"),
665            Command::CreateSubscription {
666                subscription_id, ..
667            } => write!(f, "CreateSubscription: {subscription_id}"),
668            Command::DropSubscription {
669                subscription_id, ..
670            } => write!(f, "DropSubscription: {subscription_id}"),
671            Command::AlterSubscriptionRetention {
672                subscription_id,
673                retention_second,
674                ..
675            } => write!(
676                f,
677                "AlterSubscriptionRetention: {subscription_id} -> {retention_second}"
678            ),
679            Command::ConnectorPropsChange(_) => write!(f, "ConnectorPropsChange"),
680            Command::Refresh {
681                table_id,
682                associated_source_id,
683                trigger_time,
684                ..
685            } => write!(
686                f,
687                "Refresh: {} (source: {}, cycle: {})",
688                table_id, associated_source_id, trigger_time
689            ),
690            Command::ListFinish {
691                table_id,
692                associated_source_id,
693            } => write!(
694                f,
695                "ListFinish: {} (source: {})",
696                table_id, associated_source_id
697            ),
698            Command::LoadFinish {
699                table_id,
700                associated_source_id,
701            } => write!(
702                f,
703                "LoadFinish: {} (source: {})",
704                table_id, associated_source_id
705            ),
706            Command::FinishRefresh {
707                table_id,
708                trigger_time,
709                ..
710            } => write!(f, "FinishRefresh: {} (cycle: {})", table_id, trigger_time),
711            Command::ResetSource { source_id } => write!(f, "ResetSource: {source_id}"),
712            Command::ResumeBackfill { target } => match target {
713                ResumeBackfillTarget::Job(job_id) => {
714                    write!(f, "ResumeBackfill: job={job_id}")
715                }
716                ResumeBackfillTarget::Fragment(fragment_id) => {
717                    write!(f, "ResumeBackfill: fragment={fragment_id}")
718                }
719            },
720            Command::InjectSourceOffsets {
721                source_id,
722                split_offsets,
723            } => write!(
724                f,
725                "InjectSourceOffsets: {} ({} splits)",
726                source_id,
727                split_offsets.len()
728            ),
729            Command::ApplyIcebergPkIndexCompaction {
730                sink_id, task_id, ..
731            } => write!(
732                f,
733                "ApplyIcebergPkIndexCompaction: sink={sink_id} task={task_id}"
734            ),
735        }
736    }
737}
738
739impl Command {
740    pub fn pause() -> Self {
741        Self::Pause
742    }
743
744    pub fn resume() -> Self {
745        Self::Resume
746    }
747
748    pub fn need_checkpoint(&self) -> bool {
749        // todo! Reviewing the flow of different command to reduce the amount of checkpoint
750        !matches!(self, Command::Resume)
751    }
752}
753
754#[derive(Debug)]
755pub enum PostCollectCommand {
756    Command(String),
757    DropStreamingJobs,
758    CreateStreamingJob {
759        info: CreateStreamingJobCommandInfo,
760        job_type: CreateStreamingJobType,
761        cross_db_snapshot_backfill_info: SnapshotBackfillInfo,
762        resolved_split_assignment: SplitAssignment,
763    },
764    Reschedule {
765        reschedules: HashMap<FragmentId, Reschedule>,
766    },
767    ReplaceStreamJob {
768        plan: ReplaceStreamJobPlan,
769        resolved_split_assignment: SplitAssignment,
770    },
771    SourceChangeSplit {
772        split_assignment: SplitAssignment,
773    },
774    CreateSubscription {
775        subscription_id: SubscriptionId,
776    },
777    ConnectorPropsChange(ConnectorPropsChange),
778    ResumeBackfill {
779        target: ResumeBackfillTarget,
780    },
781    /// The actors the `RefreshStart` barrier reached, so the cycle is tracked against the actor
782    /// set it actually runs on.
783    RefreshStarted {
784        table_id: TableId,
785        database_id: DatabaseId,
786        associated_source_id: SourceId,
787        staging_table_id: TableId,
788        trigger_time: NaiveDateTime,
789        actors: RefreshCycleActors,
790    },
791    FinishRefresh {
792        table_id: TableId,
793        staging_table_id: TableId,
794        trigger_time: NaiveDateTime,
795    },
796}
797
798impl PostCollectCommand {
799    pub fn barrier() -> Self {
800        PostCollectCommand::Command("barrier".to_owned())
801    }
802
803    pub fn should_checkpoint(&self) -> bool {
804        match self {
805            PostCollectCommand::DropStreamingJobs
806            | PostCollectCommand::CreateStreamingJob { .. }
807            | PostCollectCommand::Reschedule { .. }
808            | PostCollectCommand::ReplaceStreamJob { .. }
809            | PostCollectCommand::SourceChangeSplit { .. }
810            | PostCollectCommand::CreateSubscription { .. }
811            | PostCollectCommand::ConnectorPropsChange(_)
812            | PostCollectCommand::ResumeBackfill { .. }
813            | PostCollectCommand::RefreshStarted { .. }
814            | PostCollectCommand::FinishRefresh { .. } => true,
815            PostCollectCommand::Command(_) => false,
816        }
817    }
818
819    pub fn command_name(&self) -> &str {
820        match self {
821            PostCollectCommand::Command(name) => name.as_str(),
822            PostCollectCommand::DropStreamingJobs => "DropStreamingJobs",
823            PostCollectCommand::CreateStreamingJob { .. } => "CreateStreamingJob",
824            PostCollectCommand::Reschedule { .. } => "Reschedule",
825            PostCollectCommand::ReplaceStreamJob { .. } => "ReplaceStreamJob",
826            PostCollectCommand::SourceChangeSplit { .. } => "SourceChangeSplit",
827            PostCollectCommand::CreateSubscription { .. } => "CreateSubscription",
828            PostCollectCommand::ConnectorPropsChange(_) => "ConnectorPropsChange",
829            PostCollectCommand::ResumeBackfill { .. } => "ResumeBackfill",
830            PostCollectCommand::RefreshStarted { .. } => "Refresh",
831            PostCollectCommand::FinishRefresh { .. } => "FinishRefresh",
832        }
833    }
834}
835
836impl Display for PostCollectCommand {
837    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
838        f.write_str(self.command_name())
839    }
840}
841
842#[derive(Debug, Clone, PartialEq, Eq)]
843pub enum BarrierKind {
844    Initial,
845    Barrier,
846    /// Hold a list of previous non-checkpoint prev-epoch + current prev-epoch
847    Checkpoint(Vec<u64>),
848}
849
850impl BarrierKind {
851    pub fn to_protobuf(&self) -> PbBarrierKind {
852        match self {
853            BarrierKind::Initial => PbBarrierKind::Initial,
854            BarrierKind::Barrier => PbBarrierKind::Barrier,
855            BarrierKind::Checkpoint(_) => PbBarrierKind::Checkpoint,
856        }
857    }
858
859    pub fn is_checkpoint(&self) -> bool {
860        matches!(self, BarrierKind::Checkpoint(_))
861    }
862
863    pub fn is_initial(&self) -> bool {
864        matches!(self, BarrierKind::Initial)
865    }
866
867    pub fn as_str_name(&self) -> &'static str {
868        match self {
869            BarrierKind::Initial => "Initial",
870            BarrierKind::Barrier => "Barrier",
871            BarrierKind::Checkpoint(_) => "Checkpoint",
872        }
873    }
874}
875
876fn sink_original_schema_fields(columns: &[PbColumnCatalog]) -> Vec<PbField> {
877    columns
878        .iter()
879        .filter(|col| !col.is_hidden)
880        .map(|col| {
881            let column_desc = col
882                .column_desc
883                .as_ref()
884                .expect("sink column catalog should have a column descriptor");
885            PbField {
886                data_type: Some(
887                    column_desc
888                        .column_type
889                        .as_ref()
890                        .expect("sink column descriptor should have a column type")
891                        .clone(),
892                ),
893                name: column_desc.name.clone(),
894            }
895        })
896        .collect()
897}
898
899impl Command {
900    pub(super) fn collect_commit_epoch_info(
901        database_info: &InflightDatabaseInfo,
902        barrier_info: &PartialGraphBarrierInfo,
903        task: &mut CompleteBarrierTask,
904        resps: Vec<BarrierCompleteResponse>,
905        backfill_pinned_upstream_tables: HashSet<TableId>,
906    ) {
907        let (
908            sst_to_context,
909            synced_ssts,
910            new_table_watermarks,
911            old_value_ssts,
912            vector_index_adds,
913            iceberg_pk_index_sink_metadata,
914        ) = collect_resp_info(resps);
915
916        let new_table_fragment_infos = match &barrier_info.post_collect_command {
917            PostCollectCommand::CreateStreamingJob { info, job_type, .. } => {
918                assert!(!matches!(
919                    job_type,
920                    CreateStreamingJobType::Independent { .. }
921                ));
922                let table_fragments = &info.stream_job_fragments;
923                let mut table_ids: HashSet<_> =
924                    table_fragments.internal_table_ids().into_iter().collect();
925                if let Some(mv_table_id) = table_fragments.mv_table_id() {
926                    table_ids.insert(mv_table_id);
927                }
928
929                vec![NewTableFragmentInfo { table_ids }]
930            }
931            _ => vec![],
932        };
933
934        let mut log_store_table_ids = HashSet::new();
935        // TODO: may collect cross db snapshot backfill
936        log_store_table_ids.extend(database_info.subscribed_tables());
937        log_store_table_ids.extend(backfill_pinned_upstream_tables);
938
939        let table_new_change_log = build_table_change_log_delta(
940            old_value_ssts.into_iter(),
941            synced_ssts.iter().map(|sst| &sst.sst_info),
942            must_match!(&barrier_info.barrier_info.kind, BarrierKind::Checkpoint(epochs) => epochs),
943            log_store_table_ids.into_iter(),
944        );
945
946        let epoch = barrier_info.barrier_info.prev_epoch();
947        let info = &mut task.commit_info;
948        for table_id in &barrier_info.table_ids_to_commit {
949            info.tables_to_commit
950                .try_insert(*table_id, epoch)
951                .expect("non duplicate");
952        }
953
954        info.sstables.extend(synced_ssts);
955        info.new_table_watermarks.extend(new_table_watermarks);
956        info.sst_to_context.extend(sst_to_context);
957        info.new_table_fragment_infos
958            .extend(new_table_fragment_infos);
959        info.change_log_delta.extend(table_new_change_log);
960        for (table_id, vector_index_adds) in vector_index_adds {
961            info.vector_index_delta
962                .try_insert(table_id, VectorIndexDelta::Adds(vector_index_adds))
963                .expect("non-duplicate");
964        }
965        if let PostCollectCommand::CreateStreamingJob { info: job_info, .. } =
966            &barrier_info.post_collect_command
967            && let Some(index_table) = collect_new_vector_index_info(job_info)
968        {
969            info.vector_index_delta
970                .try_insert(
971                    index_table.id,
972                    VectorIndexDelta::Init(PbVectorIndexInit {
973                        info: Some(index_table.vector_index_info.unwrap()),
974                    }),
975                )
976                .expect("non-duplicate");
977        }
978        if let PostCollectCommand::RefreshStarted {
979            table_id,
980            staging_table_id,
981            ..
982        }
983        | PostCollectCommand::FinishRefresh {
984            table_id,
985            staging_table_id,
986            ..
987        } = &barrier_info.post_collect_command
988        {
989            // The table may have been dropped after the command was scheduled.
990            if barrier_info.table_ids_to_commit.contains(staging_table_id) {
991                info.truncate_tables.insert(*staging_table_id);
992            } else {
993                tracing::warn!(%table_id, %staging_table_id, "skip truncating the staging table of a dropped table");
994            }
995        }
996        task.iceberg_pk_index_pre_commit_metadata
997            .extend(iceberg_pk_index_sink_metadata.into_iter().map(Into::into));
998    }
999}
1000
1001impl Command {
1002    /// Build the `Pause` mutation.
1003    pub(super) fn pause_to_mutation(is_currently_paused: bool) -> Option<Mutation> {
1004        {
1005            {
1006                // Only pause when the cluster is not already paused.
1007                // XXX: what if pause(r1) - pause(r2) - resume(r1) - resume(r2)??
1008                if !is_currently_paused {
1009                    Some(Mutation::Pause(PauseMutation {}))
1010                } else {
1011                    None
1012                }
1013            }
1014        }
1015    }
1016
1017    /// Build the `Resume` mutation.
1018    pub(super) fn resume_to_mutation(is_currently_paused: bool) -> Option<Mutation> {
1019        {
1020            {
1021                // Only resume when the cluster is paused with the same reason.
1022                if is_currently_paused {
1023                    Some(Mutation::Resume(ResumeMutation {}))
1024                } else {
1025                    None
1026                }
1027            }
1028        }
1029    }
1030
1031    /// Build the `Splits` mutation for `SourceChangeSplit`.
1032    pub(super) fn source_change_split_to_mutation(split_assignment: &SplitAssignment) -> Mutation {
1033        {
1034            {
1035                let mut diff = HashMap::new();
1036
1037                for actor_splits in split_assignment.values() {
1038                    diff.extend(actor_splits.clone());
1039                }
1040
1041                Mutation::Splits(SourceChangeSplitMutation {
1042                    actor_splits: build_actor_connector_splits(&diff),
1043                })
1044            }
1045        }
1046    }
1047
1048    /// Build the `Stop` mutation for `DropStreamingJobs`.
1049    pub(super) fn drop_streaming_jobs_to_mutation(
1050        actors: &Vec<ActorId>,
1051        dropped_sink_fragment_by_targets: &HashMap<FragmentId, Vec<FragmentId>>,
1052    ) -> Mutation {
1053        {
1054            Mutation::Stop(StopMutation {
1055                actors: actors.clone(),
1056                dropped_sink_fragments: dropped_sink_fragment_by_targets
1057                    .values()
1058                    .flatten()
1059                    .cloned()
1060                    .collect(),
1061            })
1062        }
1063    }
1064
1065    /// Build the `Add` mutation for `CreateStreamingJob`.
1066    pub(super) fn create_streaming_job_to_mutation(
1067        info: &CreateStreamingJobCommandInfo,
1068        job_type: &CreateStreamingJobType,
1069        dropped_actors: impl IntoIterator<Item = ActorId>,
1070        is_currently_paused: bool,
1071        mut edges: FragmentEdgeBuildResult,
1072        actor_cdc_table_snapshot_splits: Option<HashMap<ActorId, PbCdcTableSnapshotSplits>>,
1073        split_assignment: &SplitAssignment,
1074        stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1075    ) -> MetaResult<Mutation> {
1076        {
1077            {
1078                let CreateStreamingJobCommandInfo {
1079                    stream_job_fragments,
1080                    fragment_backfill_ordering,
1081                    ..
1082                } = info;
1083                let added_actors: Vec<ActorId> = stream_actors
1084                    .values()
1085                    .flatten()
1086                    .map(|actor| actor.actor_id)
1087                    .collect();
1088                let dropped_actors = dropped_actors.into_iter().collect();
1089                let actor_splits = split_assignment
1090                    .values()
1091                    .flat_map(build_actor_connector_splits)
1092                    .collect();
1093                let subscriptions_to_add = {
1094                    if let CreateStreamingJobType::Independent {
1095                        snapshot_backfill_info,
1096                        ..
1097                    } = job_type
1098                    {
1099                        snapshot_backfill_info
1100                            .upstream_mv_table_id_to_backfill_epoch
1101                            .keys()
1102                            .map(|table_id| SubscriptionUpstreamInfo {
1103                                subscriber_id: stream_job_fragments
1104                                    .stream_job_id()
1105                                    .as_subscriber_id(),
1106                                upstream_mv_table_id: *table_id,
1107                            })
1108                            .collect()
1109                    } else {
1110                        Default::default()
1111                    }
1112                };
1113                let backfill_nodes_to_pause: Vec<_> =
1114                    get_nodes_with_backfill_dependencies(fragment_backfill_ordering)
1115                        .into_iter()
1116                        .collect();
1117
1118                let new_upstream_sinks =
1119                    if let CreateStreamingJobType::SinkIntoTable(UpstreamSinkInfo {
1120                        sink_fragment_id,
1121                        sink_output_fields,
1122                        project_exprs,
1123                        new_sink_downstream,
1124                        ..
1125                    }) = job_type
1126                    {
1127                        let upstream_actors = edges.take_common_upstream_actors(
1128                            *sink_fragment_id,
1129                            new_sink_downstream.downstream_fragment_id,
1130                        )?;
1131                        let new_upstream_sink = PbNewUpstreamSink {
1132                            info: Some(PbUpstreamSinkInfo {
1133                                upstream_fragment_id: *sink_fragment_id,
1134                                sink_output_schema: sink_output_fields.clone(),
1135                                project_exprs: project_exprs.clone(),
1136                            }),
1137                            upstream_actors,
1138                        };
1139                        HashMap::from([(
1140                            new_sink_downstream.downstream_fragment_id,
1141                            new_upstream_sink,
1142                        )])
1143                    } else {
1144                        HashMap::new()
1145                    };
1146
1147                let actor_cdc_table_snapshot_splits = actor_cdc_table_snapshot_splits
1148                    .map(|splits| PbCdcTableSnapshotSplitsWithGeneration { splits });
1149
1150                let mut add_mutation = AddMutation {
1151                    actor_dispatchers: Default::default(),
1152                    added_actors,
1153                    actor_splits,
1154                    // If the cluster is already paused, the new actors should be paused too.
1155                    pause: is_currently_paused,
1156                    subscriptions_to_add,
1157                    backfill_nodes_to_pause,
1158                    actor_cdc_table_snapshot_splits,
1159                    new_upstream_sinks,
1160                    dropped_actors,
1161                    sink_log_store_flush: info
1162                        .replace_sink
1163                        .map(|old_sink_id| vec![old_sink_id])
1164                        .unwrap_or_default(),
1165                };
1166                edges.apply_to_add_mutation(&mut add_mutation);
1167
1168                Ok(Mutation::Add(add_mutation))
1169            }
1170        }
1171    }
1172
1173    /// Build the `Update` mutation for `ReplaceStreamJob`.
1174    pub(super) fn replace_stream_job_to_mutation(
1175        ReplaceStreamJobPlan {
1176            old_fragments,
1177            auto_refresh_schema_sinks,
1178            ..
1179        }: &ReplaceStreamJobPlan,
1180        edges: FragmentEdgeBuildResult,
1181        database_info: &mut InflightDatabaseInfo,
1182        split_assignment: &SplitAssignment,
1183    ) -> MetaResult<Mutation> {
1184        {
1185            {
1186                let actor_cdc_table_snapshot_splits = database_info
1187                    .assign_cdc_backfill_splits(old_fragments.stream_job_id)?
1188                    .map(|splits| PbCdcTableSnapshotSplitsWithGeneration { splits });
1189                let old_fragments = old_fragments.fragments.keys().copied();
1190                let auto_refresh_sink_fragment_ids = auto_refresh_schema_sinks
1191                    .as_ref()
1192                    .into_iter()
1193                    .flat_map(|sinks| sinks.iter())
1194                    .map(|sink| sink.original_fragment.fragment_id);
1195                Ok(Self::generate_update_mutation_for_replace_table(
1196                    old_fragments
1197                        .chain(auto_refresh_sink_fragment_ids)
1198                        .flat_map(|fragment_id| {
1199                            database_info.fragment(fragment_id).actors.keys().copied()
1200                        }),
1201                    edges,
1202                    split_assignment,
1203                    actor_cdc_table_snapshot_splits,
1204                    auto_refresh_schema_sinks.as_ref(),
1205                ))
1206            }
1207        }
1208    }
1209
1210    /// Build the `Update` mutation for `RescheduleIntent`.
1211    pub(super) fn reschedule_to_mutation(
1212        reschedules: &HashMap<FragmentId, Reschedule>,
1213        fragment_actors: &HashMap<FragmentId, HashSet<ActorId>>,
1214        control_stream_manager: &ControlStreamManager,
1215        database_info: &mut InflightDatabaseInfo,
1216    ) -> MetaResult<Option<Mutation>> {
1217        {
1218            {
1219                let database_id = database_info.database_id;
1220                let mut dispatcher_update = HashMap::new();
1221                for reschedule in reschedules.values() {
1222                    for &(upstream_fragment_id, dispatcher_id) in
1223                        &reschedule.upstream_fragment_dispatcher_ids
1224                    {
1225                        // Find the actors of the upstream fragment.
1226                        let upstream_actor_ids = fragment_actors
1227                            .get(&upstream_fragment_id)
1228                            .expect("should contain");
1229
1230                        let upstream_reschedule = reschedules.get(&upstream_fragment_id);
1231
1232                        // Record updates for all actors.
1233                        for &actor_id in upstream_actor_ids {
1234                            let added_downstream_actor_id = if upstream_reschedule
1235                                .map(|reschedule| !reschedule.removed_actors.contains(&actor_id))
1236                                .unwrap_or(true)
1237                            {
1238                                reschedule
1239                                    .added_actors
1240                                    .values()
1241                                    .flatten()
1242                                    .cloned()
1243                                    .collect()
1244                            } else {
1245                                Default::default()
1246                            };
1247                            // Index with the dispatcher id to check duplicates.
1248                            dispatcher_update
1249                                .try_insert(
1250                                    (actor_id, dispatcher_id),
1251                                    DispatcherUpdate {
1252                                        actor_id,
1253                                        dispatcher_id,
1254                                        hash_mapping: reschedule
1255                                            .upstream_dispatcher_mapping
1256                                            .as_ref()
1257                                            .map(|m| m.to_protobuf()),
1258                                        added_downstream_actor_id,
1259                                        removed_downstream_actor_id: reschedule
1260                                            .removed_actors
1261                                            .iter()
1262                                            .cloned()
1263                                            .collect(),
1264                                    },
1265                                )
1266                                .unwrap();
1267                        }
1268                    }
1269                }
1270                let dispatcher_update = dispatcher_update.into_values().collect();
1271
1272                let mut merge_update = HashMap::new();
1273                for (&fragment_id, reschedule) in reschedules {
1274                    for &downstream_fragment_id in &reschedule.downstream_fragment_ids {
1275                        // Find the actors of the downstream fragment.
1276                        let downstream_actor_ids = fragment_actors
1277                            .get(&downstream_fragment_id)
1278                            .expect("should contain");
1279
1280                        // Downstream removed actors should be skipped
1281                        // Newly created actors of the current fragment will not dispatch Update
1282                        // barriers to them
1283                        let downstream_removed_actors: HashSet<_> = reschedules
1284                            .get(&downstream_fragment_id)
1285                            .map(|downstream_reschedule| {
1286                                downstream_reschedule
1287                                    .removed_actors
1288                                    .iter()
1289                                    .copied()
1290                                    .collect()
1291                            })
1292                            .unwrap_or_default();
1293
1294                        // Record updates for all actors.
1295                        for &actor_id in downstream_actor_ids {
1296                            if downstream_removed_actors.contains(&actor_id) {
1297                                continue;
1298                            }
1299
1300                            // Index with the fragment id to check duplicates.
1301                            merge_update
1302                                .try_insert(
1303                                    (actor_id, fragment_id),
1304                                    MergeUpdate {
1305                                        actor_id,
1306                                        upstream_fragment_id: fragment_id,
1307                                        new_upstream_fragment_id: None,
1308                                        added_upstream_actors: reschedule
1309                                            .added_actors
1310                                            .iter()
1311                                            .flat_map(|(worker_id, actors)| {
1312                                                let host =
1313                                                    control_stream_manager.host_addr(*worker_id);
1314                                                actors.iter().map(move |&actor_id| PbActorInfo {
1315                                                    actor_id,
1316                                                    host: Some(host.clone()),
1317                                                    // we assume that we only scale the partial graph of database
1318                                                    partial_graph_id: to_partial_graph_id(
1319                                                        database_id,
1320                                                        None,
1321                                                    ),
1322                                                })
1323                                            })
1324                                            .collect(),
1325                                        removed_upstream_actor_id: reschedule
1326                                            .removed_actors
1327                                            .iter()
1328                                            .cloned()
1329                                            .collect(),
1330                                    },
1331                                )
1332                                .unwrap();
1333                        }
1334                    }
1335                }
1336                let merge_update = merge_update.into_values().collect();
1337
1338                let mut actor_vnode_bitmap_update = HashMap::new();
1339                for reschedule in reschedules.values() {
1340                    // Record updates for all actors in this fragment.
1341                    for (&actor_id, bitmap) in &reschedule.vnode_bitmap_updates {
1342                        let bitmap = bitmap.to_protobuf();
1343                        actor_vnode_bitmap_update
1344                            .try_insert(actor_id, bitmap)
1345                            .unwrap();
1346                    }
1347                }
1348                let dropped_actors = reschedules
1349                    .values()
1350                    .flat_map(|r| r.removed_actors.iter().copied())
1351                    .collect();
1352                let mut actor_splits = HashMap::new();
1353                let mut actor_cdc_table_snapshot_splits = HashMap::new();
1354                for (fragment_id, reschedule) in reschedules {
1355                    for (actor_id, splits) in &reschedule.actor_splits {
1356                        actor_splits.insert(
1357                            *actor_id,
1358                            ConnectorSplits {
1359                                splits: splits.iter().map(ConnectorSplit::from).collect(),
1360                            },
1361                        );
1362                    }
1363
1364                    if let Some(assignment) =
1365                        database_info.may_assign_fragment_cdc_backfill_splits(*fragment_id)?
1366                    {
1367                        actor_cdc_table_snapshot_splits.extend(assignment)
1368                    }
1369                }
1370
1371                // we don't create dispatchers in reschedule scenario
1372                let actor_new_dispatchers = HashMap::new();
1373                let mutation = Mutation::Update(UpdateMutation {
1374                    dispatcher_update,
1375                    merge_update,
1376                    actor_vnode_bitmap_update,
1377                    dropped_actors,
1378                    actor_splits,
1379                    actor_new_dispatchers,
1380                    actor_cdc_table_snapshot_splits: Some(PbCdcTableSnapshotSplitsWithGeneration {
1381                        splits: actor_cdc_table_snapshot_splits,
1382                    }),
1383                    sink_schema_change: Default::default(),
1384                    subscriptions_to_drop: vec![],
1385                    iceberg_pk_index_compaction: None,
1386                });
1387                tracing::debug!("update mutation: {mutation:?}");
1388                Ok(Some(mutation))
1389            }
1390        }
1391    }
1392
1393    /// Build the `Add` mutation for `CreateSubscription`.
1394    pub(super) fn create_subscription_to_mutation(
1395        upstream_mv_table_id: TableId,
1396        subscription_id: SubscriptionId,
1397    ) -> Mutation {
1398        {
1399            Mutation::Add(AddMutation {
1400                actor_dispatchers: Default::default(),
1401                added_actors: vec![],
1402                actor_splits: Default::default(),
1403                pause: false,
1404                subscriptions_to_add: vec![SubscriptionUpstreamInfo {
1405                    upstream_mv_table_id,
1406                    subscriber_id: subscription_id.as_subscriber_id(),
1407                }],
1408                backfill_nodes_to_pause: vec![],
1409                actor_cdc_table_snapshot_splits: None,
1410                new_upstream_sinks: Default::default(),
1411                dropped_actors: Default::default(),
1412                sink_log_store_flush: Default::default(),
1413            })
1414        }
1415    }
1416
1417    /// Build the `DropSubscriptions` mutation for `DropSubscription`.
1418    pub(super) fn drop_subscription_to_mutation(
1419        upstream_mv_table_id: TableId,
1420        subscription_id: SubscriptionId,
1421    ) -> Mutation {
1422        {
1423            Mutation::DropSubscriptions(DropSubscriptionsMutation {
1424                info: vec![SubscriptionUpstreamInfo {
1425                    subscriber_id: subscription_id.as_subscriber_id(),
1426                    upstream_mv_table_id,
1427                }],
1428            })
1429        }
1430    }
1431
1432    /// Build the `ConnectorPropsChange` mutation.
1433    pub(super) fn connector_props_change_to_mutation(config: &ConnectorPropsChange) -> Mutation {
1434        {
1435            {
1436                let mut connector_props_infos = HashMap::default();
1437                for (k, v) in config {
1438                    connector_props_infos.insert(
1439                        k.as_raw_id(),
1440                        ConnectorPropsInfo {
1441                            connector_props_info: v.clone(),
1442                        },
1443                    );
1444                }
1445                Mutation::ConnectorPropsChange(ConnectorPropsChangeMutation {
1446                    connector_props_infos,
1447                })
1448            }
1449        }
1450    }
1451
1452    /// Build the `RefreshStart` mutation.
1453    pub(super) fn refresh_to_mutation(
1454        table_id: TableId,
1455        associated_source_id: SourceId,
1456    ) -> Mutation {
1457        Mutation::RefreshStart(risingwave_pb::stream_plan::RefreshStartMutation {
1458            table_id,
1459            associated_source_id,
1460        })
1461    }
1462
1463    /// Build the `ListFinish` mutation.
1464    pub(super) fn list_finish_to_mutation(associated_source_id: SourceId) -> Mutation {
1465        Mutation::ListFinish(ListFinishMutation {
1466            associated_source_id,
1467        })
1468    }
1469
1470    /// Build the `LoadFinish` mutation.
1471    pub(super) fn load_finish_to_mutation(associated_source_id: SourceId) -> Mutation {
1472        Mutation::LoadFinish(LoadFinishMutation {
1473            associated_source_id,
1474        })
1475    }
1476
1477    /// Build the `ResetSource` mutation.
1478    pub(super) fn reset_source_to_mutation(source_id: SourceId) -> Mutation {
1479        Mutation::ResetSource(risingwave_pb::stream_plan::ResetSourceMutation {
1480            source_id: source_id.as_raw_id(),
1481        })
1482    }
1483
1484    /// Build the `StartFragmentBackfill` mutation for `ResumeBackfill`.
1485    pub(super) fn resume_backfill_to_mutation(
1486        target: &ResumeBackfillTarget,
1487        database_info: &InflightDatabaseInfo,
1488    ) -> MetaResult<Option<Mutation>> {
1489        {
1490            {
1491                let fragment_ids: HashSet<_> = match target {
1492                    ResumeBackfillTarget::Job(job_id) => {
1493                        database_info.backfill_fragment_ids_for_job(*job_id)?
1494                    }
1495                    ResumeBackfillTarget::Fragment(fragment_id) => {
1496                        if !database_info.is_backfill_fragment(*fragment_id)? {
1497                            return Err(MetaError::invalid_parameter(format!(
1498                                "fragment {} is not a backfill node",
1499                                fragment_id
1500                            )));
1501                        }
1502                        HashSet::from([*fragment_id])
1503                    }
1504                };
1505                if fragment_ids.is_empty() {
1506                    warn!(
1507                        ?target,
1508                        "resume backfill command ignored because no backfill fragments found"
1509                    );
1510                    Ok(None)
1511                } else {
1512                    Ok(Some(Mutation::StartFragmentBackfill(
1513                        StartFragmentBackfillMutation {
1514                            fragment_ids: fragment_ids.into_iter().collect(),
1515                        },
1516                    )))
1517                }
1518            }
1519        }
1520    }
1521
1522    /// Build the `InjectSourceOffsets` mutation.
1523    pub(super) fn inject_source_offsets_to_mutation(
1524        source_id: SourceId,
1525        split_offsets: &HashMap<String, String>,
1526    ) -> Mutation {
1527        Mutation::InjectSourceOffsets(risingwave_pb::stream_plan::InjectSourceOffsetsMutation {
1528            source_id: source_id.as_raw_id(),
1529            split_offsets: split_offsets.clone(),
1530        })
1531    }
1532
1533    /// Collect actors to create for `CreateStreamingJob` (non-snapshot-backfill).
1534    pub(super) fn create_streaming_job_actors_to_create(
1535        info: &CreateStreamingJobCommandInfo,
1536        edges: &mut FragmentEdgeBuildResult,
1537        stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1538        actor_location: &HashMap<ActorId, WorkerId>,
1539    ) -> StreamJobActorsToCreate {
1540        {
1541            {
1542                edges.collect_actors_to_create(info.stream_job_fragments.fragments.values().map(
1543                    |fragment| {
1544                        let actors = stream_actors
1545                            .get(&fragment.fragment_id)
1546                            .into_iter()
1547                            .flatten()
1548                            .map(|actor| (actor, actor_location[&actor.actor_id]));
1549                        (
1550                            fragment.fragment_id,
1551                            &fragment.nodes,
1552                            actors,
1553                            [], // no subscriber for new job to create
1554                        )
1555                    },
1556                ))
1557            }
1558        }
1559    }
1560
1561    /// Collect actors to create for `RescheduleIntent`.
1562    pub(super) fn reschedule_actors_to_create(
1563        reschedules: &HashMap<FragmentId, Reschedule>,
1564        fragment_actors: &HashMap<FragmentId, HashSet<ActorId>>,
1565        database_info: &InflightDatabaseInfo,
1566        control_stream_manager: &ControlStreamManager,
1567    ) -> StreamJobActorsToCreate {
1568        {
1569            {
1570                let mut actor_upstreams = Self::collect_database_partial_graph_actor_upstreams(
1571                    reschedules.iter().map(|(fragment_id, reschedule)| {
1572                        (
1573                            *fragment_id,
1574                            reschedule.newly_created_actors.values().map(
1575                                |((actor, dispatchers), _)| {
1576                                    (actor.actor_id, dispatchers.as_slice())
1577                                },
1578                            ),
1579                        )
1580                    }),
1581                    Some((reschedules, fragment_actors)),
1582                    database_info,
1583                    control_stream_manager,
1584                );
1585                let mut map: HashMap<WorkerId, HashMap<_, (_, Vec<_>, _)>> = HashMap::new();
1586                for (fragment_id, (actor, dispatchers), worker_id) in
1587                    reschedules.iter().flat_map(|(fragment_id, reschedule)| {
1588                        reschedule
1589                            .newly_created_actors
1590                            .values()
1591                            .map(|(actors, status)| (*fragment_id, actors, status))
1592                    })
1593                {
1594                    let upstreams = actor_upstreams.remove(&actor.actor_id).unwrap_or_default();
1595                    map.entry(*worker_id)
1596                        .or_default()
1597                        .entry(fragment_id)
1598                        .or_insert_with(|| {
1599                            let node = database_info.fragment(fragment_id).nodes.clone();
1600                            let subscribers =
1601                                database_info.fragment_subscribers(fragment_id).collect();
1602                            (node, vec![], subscribers)
1603                        })
1604                        .1
1605                        .push((actor.clone(), upstreams, dispatchers.clone()));
1606                }
1607                map
1608            }
1609        }
1610    }
1611
1612    /// Collect actors to create for `ReplaceStreamJob`.
1613    pub(super) fn replace_stream_job_actors_to_create(
1614        replace_table: &ReplaceStreamJobPlan,
1615        edges: &mut FragmentEdgeBuildResult,
1616        database_info: &InflightDatabaseInfo,
1617        stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1618        actor_location: &HashMap<ActorId, WorkerId>,
1619    ) -> StreamJobActorsToCreate {
1620        {
1621            {
1622                let mut actors = edges.collect_actors_to_create(
1623                    replace_table
1624                        .new_fragments
1625                        .fragments
1626                        .values()
1627                        .map(|fragment| {
1628                            let actors = stream_actors
1629                                .get(&fragment.fragment_id)
1630                                .into_iter()
1631                                .flatten()
1632                                .map(|actor| (actor, actor_location[&actor.actor_id]));
1633                            (
1634                                fragment.fragment_id,
1635                                &fragment.nodes,
1636                                actors,
1637                                database_info
1638                                    .job_subscribers(replace_table.old_fragments.stream_job_id),
1639                            )
1640                        }),
1641                );
1642
1643                // Handle auto-refresh schema sinks
1644                if let Some(sinks) = &replace_table.auto_refresh_schema_sinks {
1645                    let sink_actors = edges.collect_actors_to_create(sinks.iter().map(|sink| {
1646                        (
1647                            sink.new_fragment.fragment_id,
1648                            &sink.new_fragment.nodes,
1649                            stream_actors
1650                                .get(&sink.new_fragment.fragment_id)
1651                                .into_iter()
1652                                .flatten()
1653                                .map(|actor| (actor, actor_location[&actor.actor_id])),
1654                            database_info.job_subscribers(sink.original_sink.id.as_job_id()),
1655                        )
1656                    }));
1657                    for (worker_id, fragment_actors) in sink_actors {
1658                        actors.entry(worker_id).or_default().extend(fragment_actors);
1659                    }
1660                }
1661                actors
1662            }
1663        }
1664    }
1665
1666    fn generate_update_mutation_for_replace_table(
1667        dropped_actors: impl IntoIterator<Item = ActorId>,
1668        edges: FragmentEdgeBuildResult,
1669        split_assignment: &SplitAssignment,
1670        cdc_table_snapshot_split_assignment: Option<PbCdcTableSnapshotSplitsWithGeneration>,
1671        auto_refresh_schema_sinks: Option<&Vec<AutoRefreshSchemaSinkContext>>,
1672    ) -> Mutation {
1673        let dropped_actors = dropped_actors.into_iter().collect();
1674
1675        let actor_splits = split_assignment
1676            .values()
1677            .flat_map(build_actor_connector_splits)
1678            .collect();
1679        let mut mutation = UpdateMutation {
1680            dropped_actors,
1681            actor_splits,
1682            actor_cdc_table_snapshot_splits: cdc_table_snapshot_split_assignment,
1683            sink_schema_change: auto_refresh_schema_sinks
1684                .as_ref()
1685                .into_iter()
1686                .flat_map(|sinks| {
1687                    sinks.iter().map(|sink| {
1688                        let op = if !sink.removed_column_names.is_empty() {
1689                            PbSinkSchemaChangeOp::DropColumns(PbSinkDropColumnsOp {
1690                                column_names: sink.removed_column_names.clone(),
1691                            })
1692                        } else {
1693                            PbSinkSchemaChangeOp::AddColumns(PbSinkAddColumnsOp {
1694                                fields: sink
1695                                    .newly_add_fields
1696                                    .iter()
1697                                    .map(|field| field.to_prost())
1698                                    .collect(),
1699                            })
1700                        };
1701                        (
1702                            sink.original_sink.id.as_raw_id(),
1703                            PbSinkSchemaChange {
1704                                original_schema: sink_original_schema_fields(
1705                                    &sink.original_sink.columns,
1706                                ),
1707                                op: Some(op),
1708                            },
1709                        )
1710                    })
1711                })
1712                .collect(),
1713            ..Default::default()
1714        };
1715        edges.apply_to_update_mutation(&mut mutation);
1716        Mutation::Update(mutation)
1717    }
1718}
1719
1720impl Command {
1721    #[expect(clippy::type_complexity)]
1722    pub(super) fn collect_database_partial_graph_actor_upstreams(
1723        actor_dispatchers: impl Iterator<
1724            Item = (FragmentId, impl Iterator<Item = (ActorId, &[Dispatcher])>),
1725        >,
1726        reschedule_dispatcher_update: Option<(
1727            &HashMap<FragmentId, Reschedule>,
1728            &HashMap<FragmentId, HashSet<ActorId>>,
1729        )>,
1730        database_info: &InflightDatabaseInfo,
1731        control_stream_manager: &ControlStreamManager,
1732    ) -> HashMap<ActorId, ActorUpstreams> {
1733        let mut actor_upstreams: HashMap<ActorId, ActorUpstreams> = HashMap::new();
1734        for (upstream_fragment_id, upstream_actors) in actor_dispatchers {
1735            let upstream_fragment = database_info.fragment(upstream_fragment_id);
1736            for (upstream_actor_id, dispatchers) in upstream_actors {
1737                let upstream_actor_location =
1738                    upstream_fragment.actors[&upstream_actor_id].worker_id;
1739                let upstream_actor_host = control_stream_manager.host_addr(upstream_actor_location);
1740                for downstream_actor_id in dispatchers
1741                    .iter()
1742                    .flat_map(|dispatcher| dispatcher.downstream_actor_id.iter())
1743                {
1744                    actor_upstreams
1745                        .entry(*downstream_actor_id)
1746                        .or_default()
1747                        .entry(upstream_fragment_id)
1748                        .or_default()
1749                        .insert(
1750                            upstream_actor_id,
1751                            PbActorInfo {
1752                                actor_id: upstream_actor_id,
1753                                host: Some(upstream_actor_host.clone()),
1754                                partial_graph_id: to_partial_graph_id(
1755                                    database_info.database_id,
1756                                    None,
1757                                ),
1758                            },
1759                        );
1760                }
1761            }
1762        }
1763        if let Some((reschedules, fragment_actors)) = reschedule_dispatcher_update {
1764            for reschedule in reschedules.values() {
1765                for (upstream_fragment_id, _) in &reschedule.upstream_fragment_dispatcher_ids {
1766                    let upstream_fragment = database_info.fragment(*upstream_fragment_id);
1767                    let upstream_reschedule = reschedules.get(upstream_fragment_id);
1768                    for upstream_actor_id in fragment_actors
1769                        .get(upstream_fragment_id)
1770                        .expect("should exist")
1771                    {
1772                        let upstream_actor_location =
1773                            upstream_fragment.actors[upstream_actor_id].worker_id;
1774                        let upstream_actor_host =
1775                            control_stream_manager.host_addr(upstream_actor_location);
1776                        if let Some(upstream_reschedule) = upstream_reschedule
1777                            && upstream_reschedule
1778                                .removed_actors
1779                                .contains(upstream_actor_id)
1780                        {
1781                            continue;
1782                        }
1783                        for (_, downstream_actor_id) in
1784                            reschedule
1785                                .added_actors
1786                                .iter()
1787                                .flat_map(|(worker_id, actors)| {
1788                                    actors.iter().map(|actor| (*worker_id, *actor))
1789                                })
1790                        {
1791                            actor_upstreams
1792                                .entry(downstream_actor_id)
1793                                .or_default()
1794                                .entry(*upstream_fragment_id)
1795                                .or_default()
1796                                .insert(
1797                                    *upstream_actor_id,
1798                                    PbActorInfo {
1799                                        actor_id: *upstream_actor_id,
1800                                        host: Some(upstream_actor_host.clone()),
1801                                        partial_graph_id: to_partial_graph_id(
1802                                            database_info.database_id,
1803                                            None,
1804                                        ),
1805                                    },
1806                                );
1807                        }
1808                    }
1809                }
1810            }
1811        }
1812        actor_upstreams
1813    }
1814}
1815
1816#[cfg(test)]
1817mod tests {
1818    use risingwave_pb::data::PbDataType;
1819    use risingwave_pb::data::data_type::PbTypeName;
1820    use risingwave_pb::plan_common::{ColumnCatalog as PbColumnCatalog, ColumnDesc};
1821
1822    use super::sink_original_schema_fields;
1823
1824    fn column(name: &str, type_name: PbTypeName, is_hidden: bool) -> PbColumnCatalog {
1825        PbColumnCatalog {
1826            column_desc: Some(ColumnDesc {
1827                column_type: Some(PbDataType {
1828                    type_name: type_name as i32,
1829                    ..Default::default()
1830                }),
1831                name: name.to_owned(),
1832                ..Default::default()
1833            }),
1834            is_hidden,
1835        }
1836    }
1837
1838    #[test]
1839    fn test_sink_original_schema_fields_skips_hidden_columns() {
1840        let columns = vec![
1841            column("k", PbTypeName::Int32, false),
1842            column("v", PbTypeName::Varchar, false),
1843            column("_row_id", PbTypeName::Serial, true),
1844        ];
1845
1846        let fields = sink_original_schema_fields(&columns);
1847        let field_names = fields
1848            .iter()
1849            .map(|field| field.name.as_str())
1850            .collect::<Vec<_>>();
1851
1852        assert_eq!(field_names, ["k", "v"]);
1853    }
1854}