1use 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#[derive(Debug, Clone)]
96pub struct Reschedule {
97 pub added_actors: HashMap<WorkerId, Vec<ActorId>>,
99
100 pub removed_actors: HashSet<ActorId>,
102
103 pub vnode_bitmap_updates: HashMap<ActorId, Bitmap>,
105
106 pub upstream_fragment_dispatcher_ids: Vec<(FragmentId, DispatcherId)>,
108 pub upstream_dispatcher_mapping: Option<ActorMapping>,
113
114 pub downstream_fragment_ids: Vec<FragmentId>,
116
117 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 pub fragment_actors: HashMap<FragmentId, HashSet<ActorId>>,
131}
132
133#[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 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 .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 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 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#[derive(Debug, Clone)]
310pub struct ReplaceStreamJobPlan {
311 pub old_fragments: StreamJobFragments,
312 pub new_fragments: StreamJobFragmentsToCreate,
313 pub database_resource_group: String,
315 pub replace_upstream: FragmentReplaceUpstream,
318 pub upstream_fragment_downstreams: FragmentDownstreamRelation,
319 pub split_plan: ReplaceJobSplitPlan,
322 pub streaming_job: StreamingJob,
324 pub streaming_job_model: streaming_job::Model,
326 pub tmp_id: JobId,
328 pub to_drop_state_table_ids: Vec<TableId>,
330 pub auto_refresh_schema_sinks: Option<Vec<AutoRefreshSchemaSinkContext>>,
331}
332
333impl ReplaceStreamJobPlan {
334 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 pub database_resource_group: String,
363 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 pub streaming_job_model: streaming_job::Model,
375 pub replace_sink: Option<SinkId>,
377 pub refresh_interval_sec: Option<u64>,
379}
380
381impl StreamJobFragments {
382 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 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#[derive(Debug)]
465pub enum Command {
466 Flush,
469
470 Pause,
473
474 Resume,
478
479 DropStreamingJobs {
487 streaming_job_ids: HashSet<JobId>,
488 unregistered_state_table_ids: HashSet<TableId>,
490 dropped_sink_fragment_by_targets: HashMap<FragmentId, Vec<FragmentId>>,
492 },
493
494 CreateStreamingJob {
504 info: CreateStreamingJobCommandInfo,
505 job_type: CreateStreamingJobType,
506 cross_db_snapshot_backfill_info: SnapshotBackfillInfo,
507 },
508
509 RescheduleIntent {
511 context: RescheduleContext,
512 reschedule_plan: Option<ReschedulePlan>,
517 },
518
519 ReplaceStreamJob(ReplaceStreamJobPlan),
526
527 SourceChangeSplit(SplitState),
530
531 Throttle {
534 config: ThrottleConfigMap,
535 },
536
537 CreateSubscription {
540 subscription_id: SubscriptionId,
541 upstream_mv_table_id: TableId,
542 },
543
544 DropSubscription {
548 subscription_id: SubscriptionId,
549 upstream_mv_table_id: TableId,
550 },
551
552 ConnectorPropsChange(ConnectorPropsChange),
553
554 Refresh {
558 table_id: TableId,
559 associated_source_id: SourceId,
560 staging_table_id: TableId,
561 trigger_time: NaiveDateTime,
562 },
563 ListFinish {
564 table_id: TableId,
565 associated_source_id: SourceId,
566 },
567 LoadFinish {
568 table_id: TableId,
569 associated_source_id: SourceId,
570 },
571 FinishRefresh {
575 table_id: TableId,
576 staging_table_id: TableId,
577 trigger_time: NaiveDateTime,
578 },
579
580 ResetSource {
583 source_id: SourceId,
584 },
585
586 ResumeBackfill {
589 target: ResumeBackfillTarget,
590 },
591
592 InjectSourceOffsets {
596 source_id: SourceId,
597 split_offsets: HashMap<String, String>,
599 },
600
601 ApplyIcebergPkIndexCompaction {
603 sink_id: SinkId,
604 task_id: risingwave_pb::id::IcebergCompactionTaskId,
605 overwrite: IcebergPkIndexCompactionOverwrite,
606 },
607}
608
609#[derive(Clone, educe::Educe)]
610#[educe(Debug)]
611pub struct IcebergPkIndexCompactionOverwrite {
612 #[educe(Debug(ignore))]
613 pub output_result: IcebergCommitResult,
614 pub input_file_paths: Vec<String>,
615 pub read_snapshot_id: i64,
616}
617
618#[derive(Debug, Clone, Copy)]
619pub enum ResumeBackfillTarget {
620 Job(JobId),
621 Fragment(FragmentId),
622}
623
624impl std::fmt::Display for Command {
626 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
627 match self {
628 Command::Flush => write!(f, "Flush"),
629 Command::Pause => write!(f, "Pause"),
630 Command::Resume => write!(f, "Resume"),
631 Command::DropStreamingJobs {
632 streaming_job_ids, ..
633 } => {
634 write!(
635 f,
636 "DropStreamingJobs: {}",
637 streaming_job_ids.iter().sorted().join(", ")
638 )
639 }
640 Command::CreateStreamingJob { info, .. } => {
641 write!(f, "CreateStreamingJob: {}", info.streaming_job)
642 }
643 Command::RescheduleIntent {
644 reschedule_plan, ..
645 } => {
646 if reschedule_plan.is_some() {
647 write!(f, "RescheduleIntent(planned)")
648 } else {
649 write!(f, "RescheduleIntent")
650 }
651 }
652 Command::ReplaceStreamJob(plan) => {
653 write!(f, "ReplaceStreamJob: {}", plan.streaming_job)
654 }
655 Command::SourceChangeSplit { .. } => write!(f, "SourceChangeSplit"),
656 Command::Throttle { .. } => write!(f, "Throttle"),
657 Command::CreateSubscription {
658 subscription_id, ..
659 } => write!(f, "CreateSubscription: {subscription_id}"),
660 Command::DropSubscription {
661 subscription_id, ..
662 } => write!(f, "DropSubscription: {subscription_id}"),
663 Command::ConnectorPropsChange(_) => write!(f, "ConnectorPropsChange"),
664 Command::Refresh {
665 table_id,
666 associated_source_id,
667 trigger_time,
668 ..
669 } => write!(
670 f,
671 "Refresh: {} (source: {}, cycle: {})",
672 table_id, associated_source_id, trigger_time
673 ),
674 Command::ListFinish {
675 table_id,
676 associated_source_id,
677 } => write!(
678 f,
679 "ListFinish: {} (source: {})",
680 table_id, associated_source_id
681 ),
682 Command::LoadFinish {
683 table_id,
684 associated_source_id,
685 } => write!(
686 f,
687 "LoadFinish: {} (source: {})",
688 table_id, associated_source_id
689 ),
690 Command::FinishRefresh {
691 table_id,
692 trigger_time,
693 ..
694 } => write!(f, "FinishRefresh: {} (cycle: {})", table_id, trigger_time),
695 Command::ResetSource { source_id } => write!(f, "ResetSource: {source_id}"),
696 Command::ResumeBackfill { target } => match target {
697 ResumeBackfillTarget::Job(job_id) => {
698 write!(f, "ResumeBackfill: job={job_id}")
699 }
700 ResumeBackfillTarget::Fragment(fragment_id) => {
701 write!(f, "ResumeBackfill: fragment={fragment_id}")
702 }
703 },
704 Command::InjectSourceOffsets {
705 source_id,
706 split_offsets,
707 } => write!(
708 f,
709 "InjectSourceOffsets: {} ({} splits)",
710 source_id,
711 split_offsets.len()
712 ),
713 Command::ApplyIcebergPkIndexCompaction {
714 sink_id, task_id, ..
715 } => write!(
716 f,
717 "ApplyIcebergPkIndexCompaction: sink={sink_id} task={task_id}"
718 ),
719 }
720 }
721}
722
723impl Command {
724 pub fn pause() -> Self {
725 Self::Pause
726 }
727
728 pub fn resume() -> Self {
729 Self::Resume
730 }
731
732 pub fn need_checkpoint(&self) -> bool {
733 !matches!(self, Command::Resume)
735 }
736}
737
738#[derive(Debug)]
739pub enum PostCollectCommand {
740 Command(String),
741 DropStreamingJobs,
742 CreateStreamingJob {
743 info: CreateStreamingJobCommandInfo,
744 job_type: CreateStreamingJobType,
745 cross_db_snapshot_backfill_info: SnapshotBackfillInfo,
746 resolved_split_assignment: SplitAssignment,
747 },
748 Reschedule {
749 reschedules: HashMap<FragmentId, Reschedule>,
750 },
751 ReplaceStreamJob {
752 plan: ReplaceStreamJobPlan,
753 resolved_split_assignment: SplitAssignment,
754 },
755 SourceChangeSplit {
756 split_assignment: SplitAssignment,
757 },
758 CreateSubscription {
759 subscription_id: SubscriptionId,
760 },
761 ConnectorPropsChange(ConnectorPropsChange),
762 ResumeBackfill {
763 target: ResumeBackfillTarget,
764 },
765 RefreshStarted {
768 table_id: TableId,
769 database_id: DatabaseId,
770 associated_source_id: SourceId,
771 staging_table_id: TableId,
772 trigger_time: NaiveDateTime,
773 actors: RefreshCycleActors,
774 },
775 FinishRefresh {
776 table_id: TableId,
777 staging_table_id: TableId,
778 trigger_time: NaiveDateTime,
779 },
780}
781
782impl PostCollectCommand {
783 pub fn barrier() -> Self {
784 PostCollectCommand::Command("barrier".to_owned())
785 }
786
787 pub fn should_checkpoint(&self) -> bool {
788 match self {
789 PostCollectCommand::DropStreamingJobs
790 | PostCollectCommand::CreateStreamingJob { .. }
791 | PostCollectCommand::Reschedule { .. }
792 | PostCollectCommand::ReplaceStreamJob { .. }
793 | PostCollectCommand::SourceChangeSplit { .. }
794 | PostCollectCommand::CreateSubscription { .. }
795 | PostCollectCommand::ConnectorPropsChange(_)
796 | PostCollectCommand::ResumeBackfill { .. }
797 | PostCollectCommand::RefreshStarted { .. }
798 | PostCollectCommand::FinishRefresh { .. } => true,
799 PostCollectCommand::Command(_) => false,
800 }
801 }
802
803 pub fn command_name(&self) -> &str {
804 match self {
805 PostCollectCommand::Command(name) => name.as_str(),
806 PostCollectCommand::DropStreamingJobs => "DropStreamingJobs",
807 PostCollectCommand::CreateStreamingJob { .. } => "CreateStreamingJob",
808 PostCollectCommand::Reschedule { .. } => "Reschedule",
809 PostCollectCommand::ReplaceStreamJob { .. } => "ReplaceStreamJob",
810 PostCollectCommand::SourceChangeSplit { .. } => "SourceChangeSplit",
811 PostCollectCommand::CreateSubscription { .. } => "CreateSubscription",
812 PostCollectCommand::ConnectorPropsChange(_) => "ConnectorPropsChange",
813 PostCollectCommand::ResumeBackfill { .. } => "ResumeBackfill",
814 PostCollectCommand::RefreshStarted { .. } => "Refresh",
815 PostCollectCommand::FinishRefresh { .. } => "FinishRefresh",
816 }
817 }
818}
819
820impl Display for PostCollectCommand {
821 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
822 f.write_str(self.command_name())
823 }
824}
825
826#[derive(Debug, Clone, PartialEq, Eq)]
827pub enum BarrierKind {
828 Initial,
829 Barrier,
830 Checkpoint(Vec<u64>),
832}
833
834impl BarrierKind {
835 pub fn to_protobuf(&self) -> PbBarrierKind {
836 match self {
837 BarrierKind::Initial => PbBarrierKind::Initial,
838 BarrierKind::Barrier => PbBarrierKind::Barrier,
839 BarrierKind::Checkpoint(_) => PbBarrierKind::Checkpoint,
840 }
841 }
842
843 pub fn is_checkpoint(&self) -> bool {
844 matches!(self, BarrierKind::Checkpoint(_))
845 }
846
847 pub fn is_initial(&self) -> bool {
848 matches!(self, BarrierKind::Initial)
849 }
850
851 pub fn as_str_name(&self) -> &'static str {
852 match self {
853 BarrierKind::Initial => "Initial",
854 BarrierKind::Barrier => "Barrier",
855 BarrierKind::Checkpoint(_) => "Checkpoint",
856 }
857 }
858}
859
860fn sink_original_schema_fields(columns: &[PbColumnCatalog]) -> Vec<PbField> {
861 columns
862 .iter()
863 .filter(|col| !col.is_hidden)
864 .map(|col| {
865 let column_desc = col
866 .column_desc
867 .as_ref()
868 .expect("sink column catalog should have a column descriptor");
869 PbField {
870 data_type: Some(
871 column_desc
872 .column_type
873 .as_ref()
874 .expect("sink column descriptor should have a column type")
875 .clone(),
876 ),
877 name: column_desc.name.clone(),
878 }
879 })
880 .collect()
881}
882
883impl Command {
884 pub(super) fn collect_commit_epoch_info(
885 database_info: &InflightDatabaseInfo,
886 barrier_info: &PartialGraphBarrierInfo,
887 task: &mut CompleteBarrierTask,
888 resps: Vec<BarrierCompleteResponse>,
889 backfill_pinned_upstream_tables: HashSet<TableId>,
890 ) {
891 let (
892 sst_to_context,
893 synced_ssts,
894 new_table_watermarks,
895 old_value_ssts,
896 vector_index_adds,
897 iceberg_pk_index_sink_metadata,
898 table_change_log_progress,
899 ) = collect_resp_info(resps);
900
901 let new_table_fragment_infos = match &barrier_info.post_collect_command {
902 PostCollectCommand::CreateStreamingJob { info, job_type, .. } => {
903 assert!(!matches!(
904 job_type,
905 CreateStreamingJobType::Independent { .. }
906 ));
907 let table_fragments = &info.stream_job_fragments;
908 let mut table_ids: HashSet<_> =
909 table_fragments.internal_table_ids().into_iter().collect();
910 if let Some(mv_table_id) = table_fragments.mv_table_id() {
911 table_ids.insert(mv_table_id);
912 }
913
914 vec![NewTableFragmentInfo { table_ids }]
915 }
916 _ => vec![],
917 };
918
919 let mut log_store_table_ids = HashSet::new();
920 log_store_table_ids.extend(database_info.subscribed_tables());
922 log_store_table_ids.extend(backfill_pinned_upstream_tables);
923
924 let table_new_change_log = build_table_change_log_delta(
925 old_value_ssts.into_iter(),
926 synced_ssts.iter().map(|sst| &sst.sst_info),
927 must_match!(&barrier_info.barrier_info.kind, BarrierKind::Checkpoint(epochs) => epochs),
928 log_store_table_ids.into_iter(),
929 );
930
931 let epoch = barrier_info.barrier_info.prev_epoch();
932 let info = &mut task.commit_info;
933 for table_id in &barrier_info.table_ids_to_commit {
934 info.tables_to_commit
935 .try_insert(*table_id, epoch)
936 .expect("non duplicate");
937 }
938
939 info.sstables.extend(synced_ssts);
940 info.new_table_watermarks.extend(new_table_watermarks);
941 info.sst_to_context.extend(sst_to_context);
942 info.new_table_fragment_infos
943 .extend(new_table_fragment_infos);
944 info.change_log_delta.extend(table_new_change_log);
945 for (table_id, vector_index_adds) in vector_index_adds {
946 info.vector_index_delta
947 .try_insert(table_id, VectorIndexDelta::Adds(vector_index_adds))
948 .expect("non-duplicate");
949 }
950 if let PostCollectCommand::CreateStreamingJob { info: job_info, .. } =
951 &barrier_info.post_collect_command
952 && let Some(index_table) = collect_new_vector_index_info(job_info)
953 {
954 info.vector_index_delta
955 .try_insert(
956 index_table.id,
957 VectorIndexDelta::Init(PbVectorIndexInit {
958 info: Some(index_table.vector_index_info.unwrap()),
959 }),
960 )
961 .expect("non-duplicate");
962 }
963 if let PostCollectCommand::RefreshStarted {
964 table_id,
965 staging_table_id,
966 ..
967 }
968 | PostCollectCommand::FinishRefresh {
969 table_id,
970 staging_table_id,
971 ..
972 } = &barrier_info.post_collect_command
973 {
974 if barrier_info.table_ids_to_commit.contains(staging_table_id) {
976 info.truncate_tables.insert(*staging_table_id);
977 } else {
978 tracing::warn!(%table_id, %staging_table_id, "skip truncating the staging table of a dropped table");
979 }
980 }
981 task.iceberg_pk_index_pre_commit_metadata
982 .extend(iceberg_pk_index_sink_metadata.into_iter().map(Into::into));
983 info.table_change_log_progress
984 .extend(table_change_log_progress);
985 }
986}
987
988impl Command {
989 pub(super) fn pause_to_mutation(is_currently_paused: bool) -> Option<Mutation> {
991 {
992 {
993 if !is_currently_paused {
996 Some(Mutation::Pause(PauseMutation {}))
997 } else {
998 None
999 }
1000 }
1001 }
1002 }
1003
1004 pub(super) fn resume_to_mutation(is_currently_paused: bool) -> Option<Mutation> {
1006 {
1007 {
1008 if is_currently_paused {
1010 Some(Mutation::Resume(ResumeMutation {}))
1011 } else {
1012 None
1013 }
1014 }
1015 }
1016 }
1017
1018 pub(super) fn source_change_split_to_mutation(split_assignment: &SplitAssignment) -> Mutation {
1020 {
1021 {
1022 let mut diff = HashMap::new();
1023
1024 for actor_splits in split_assignment.values() {
1025 diff.extend(actor_splits.clone());
1026 }
1027
1028 Mutation::Splits(SourceChangeSplitMutation {
1029 actor_splits: build_actor_connector_splits(&diff),
1030 })
1031 }
1032 }
1033 }
1034
1035 pub(super) fn drop_streaming_jobs_to_mutation(
1037 actors: &Vec<ActorId>,
1038 dropped_sink_fragment_by_targets: &HashMap<FragmentId, Vec<FragmentId>>,
1039 ) -> Mutation {
1040 {
1041 Mutation::Stop(StopMutation {
1042 actors: actors.clone(),
1043 dropped_sink_fragments: dropped_sink_fragment_by_targets
1044 .values()
1045 .flatten()
1046 .cloned()
1047 .collect(),
1048 })
1049 }
1050 }
1051
1052 pub(super) fn create_streaming_job_to_mutation(
1054 info: &CreateStreamingJobCommandInfo,
1055 job_type: &CreateStreamingJobType,
1056 dropped_actors: impl IntoIterator<Item = ActorId>,
1057 is_currently_paused: bool,
1058 mut edges: FragmentEdgeBuildResult,
1059 actor_cdc_table_snapshot_splits: Option<HashMap<ActorId, PbCdcTableSnapshotSplits>>,
1060 split_assignment: &SplitAssignment,
1061 stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1062 ) -> MetaResult<Mutation> {
1063 {
1064 {
1065 let CreateStreamingJobCommandInfo {
1066 stream_job_fragments,
1067 fragment_backfill_ordering,
1068 ..
1069 } = info;
1070 let added_actors: Vec<ActorId> = stream_actors
1071 .values()
1072 .flatten()
1073 .map(|actor| actor.actor_id)
1074 .collect();
1075 let dropped_actors = dropped_actors.into_iter().collect();
1076 let actor_splits = split_assignment
1077 .values()
1078 .flat_map(build_actor_connector_splits)
1079 .collect();
1080 let subscriptions_to_add = {
1081 if let CreateStreamingJobType::Independent {
1082 snapshot_backfill_info,
1083 ..
1084 } = job_type
1085 {
1086 snapshot_backfill_info
1087 .upstream_mv_table_id_to_backfill_epoch
1088 .keys()
1089 .map(|table_id| SubscriptionUpstreamInfo {
1090 subscriber_id: stream_job_fragments
1091 .stream_job_id()
1092 .as_subscriber_id(),
1093 upstream_mv_table_id: *table_id,
1094 })
1095 .collect()
1096 } else {
1097 Default::default()
1098 }
1099 };
1100 let backfill_nodes_to_pause: Vec<_> =
1101 get_nodes_with_backfill_dependencies(fragment_backfill_ordering)
1102 .into_iter()
1103 .collect();
1104
1105 let new_upstream_sinks =
1106 if let CreateStreamingJobType::SinkIntoTable(UpstreamSinkInfo {
1107 sink_fragment_id,
1108 sink_output_fields,
1109 project_exprs,
1110 new_sink_downstream,
1111 ..
1112 }) = job_type
1113 {
1114 let upstream_actors = edges.take_common_upstream_actors(
1115 *sink_fragment_id,
1116 new_sink_downstream.downstream_fragment_id,
1117 )?;
1118 let new_upstream_sink = PbNewUpstreamSink {
1119 info: Some(PbUpstreamSinkInfo {
1120 upstream_fragment_id: *sink_fragment_id,
1121 sink_output_schema: sink_output_fields.clone(),
1122 project_exprs: project_exprs.clone(),
1123 }),
1124 upstream_actors,
1125 };
1126 HashMap::from([(
1127 new_sink_downstream.downstream_fragment_id,
1128 new_upstream_sink,
1129 )])
1130 } else {
1131 HashMap::new()
1132 };
1133
1134 let actor_cdc_table_snapshot_splits = actor_cdc_table_snapshot_splits
1135 .map(|splits| PbCdcTableSnapshotSplitsWithGeneration { splits });
1136
1137 let mut add_mutation = AddMutation {
1138 actor_dispatchers: Default::default(),
1139 added_actors,
1140 actor_splits,
1141 pause: is_currently_paused,
1143 subscriptions_to_add,
1144 backfill_nodes_to_pause,
1145 actor_cdc_table_snapshot_splits,
1146 new_upstream_sinks,
1147 dropped_actors,
1148 sink_log_store_flush: info
1149 .replace_sink
1150 .map(|old_sink_id| vec![old_sink_id])
1151 .unwrap_or_default(),
1152 };
1153 edges.apply_to_add_mutation(&mut add_mutation);
1154
1155 Ok(Mutation::Add(add_mutation))
1156 }
1157 }
1158 }
1159
1160 pub(super) fn replace_stream_job_to_mutation(
1162 ReplaceStreamJobPlan {
1163 old_fragments,
1164 auto_refresh_schema_sinks,
1165 ..
1166 }: &ReplaceStreamJobPlan,
1167 edges: FragmentEdgeBuildResult,
1168 database_info: &mut InflightDatabaseInfo,
1169 split_assignment: &SplitAssignment,
1170 ) -> MetaResult<Mutation> {
1171 {
1172 {
1173 let actor_cdc_table_snapshot_splits = database_info
1174 .assign_cdc_backfill_splits(old_fragments.stream_job_id)?
1175 .map(|splits| PbCdcTableSnapshotSplitsWithGeneration { splits });
1176 let old_fragments = old_fragments.fragments.keys().copied();
1177 let auto_refresh_sink_fragment_ids = auto_refresh_schema_sinks
1178 .as_ref()
1179 .into_iter()
1180 .flat_map(|sinks| sinks.iter())
1181 .map(|sink| sink.original_fragment.fragment_id);
1182 Ok(Self::generate_update_mutation_for_replace_table(
1183 old_fragments
1184 .chain(auto_refresh_sink_fragment_ids)
1185 .flat_map(|fragment_id| {
1186 database_info.fragment(fragment_id).actors.keys().copied()
1187 }),
1188 edges,
1189 split_assignment,
1190 actor_cdc_table_snapshot_splits,
1191 auto_refresh_schema_sinks.as_ref(),
1192 ))
1193 }
1194 }
1195 }
1196
1197 pub(super) fn reschedule_to_mutation(
1199 reschedules: &HashMap<FragmentId, Reschedule>,
1200 fragment_actors: &HashMap<FragmentId, HashSet<ActorId>>,
1201 control_stream_manager: &ControlStreamManager,
1202 database_info: &mut InflightDatabaseInfo,
1203 ) -> MetaResult<Option<Mutation>> {
1204 {
1205 {
1206 let database_id = database_info.database_id;
1207 let mut dispatcher_update = HashMap::new();
1208 for reschedule in reschedules.values() {
1209 for &(upstream_fragment_id, dispatcher_id) in
1210 &reschedule.upstream_fragment_dispatcher_ids
1211 {
1212 let upstream_actor_ids = fragment_actors
1214 .get(&upstream_fragment_id)
1215 .expect("should contain");
1216
1217 let upstream_reschedule = reschedules.get(&upstream_fragment_id);
1218
1219 for &actor_id in upstream_actor_ids {
1221 let added_downstream_actor_id = if upstream_reschedule
1222 .map(|reschedule| !reschedule.removed_actors.contains(&actor_id))
1223 .unwrap_or(true)
1224 {
1225 reschedule
1226 .added_actors
1227 .values()
1228 .flatten()
1229 .cloned()
1230 .collect()
1231 } else {
1232 Default::default()
1233 };
1234 dispatcher_update
1236 .try_insert(
1237 (actor_id, dispatcher_id),
1238 DispatcherUpdate {
1239 actor_id,
1240 dispatcher_id,
1241 hash_mapping: reschedule
1242 .upstream_dispatcher_mapping
1243 .as_ref()
1244 .map(|m| m.to_protobuf()),
1245 added_downstream_actor_id,
1246 removed_downstream_actor_id: reschedule
1247 .removed_actors
1248 .iter()
1249 .cloned()
1250 .collect(),
1251 },
1252 )
1253 .unwrap();
1254 }
1255 }
1256 }
1257 let dispatcher_update = dispatcher_update.into_values().collect();
1258
1259 let mut merge_update = HashMap::new();
1260 for (&fragment_id, reschedule) in reschedules {
1261 for &downstream_fragment_id in &reschedule.downstream_fragment_ids {
1262 let downstream_actor_ids = fragment_actors
1264 .get(&downstream_fragment_id)
1265 .expect("should contain");
1266
1267 let downstream_removed_actors: HashSet<_> = reschedules
1271 .get(&downstream_fragment_id)
1272 .map(|downstream_reschedule| {
1273 downstream_reschedule
1274 .removed_actors
1275 .iter()
1276 .copied()
1277 .collect()
1278 })
1279 .unwrap_or_default();
1280
1281 for &actor_id in downstream_actor_ids {
1283 if downstream_removed_actors.contains(&actor_id) {
1284 continue;
1285 }
1286
1287 merge_update
1289 .try_insert(
1290 (actor_id, fragment_id),
1291 MergeUpdate {
1292 actor_id,
1293 upstream_fragment_id: fragment_id,
1294 new_upstream_fragment_id: None,
1295 added_upstream_actors: reschedule
1296 .added_actors
1297 .iter()
1298 .flat_map(|(worker_id, actors)| {
1299 let host =
1300 control_stream_manager.host_addr(*worker_id);
1301 actors.iter().map(move |&actor_id| PbActorInfo {
1302 actor_id,
1303 host: Some(host.clone()),
1304 partial_graph_id: to_partial_graph_id(
1306 database_id,
1307 None,
1308 ),
1309 })
1310 })
1311 .collect(),
1312 removed_upstream_actor_id: reschedule
1313 .removed_actors
1314 .iter()
1315 .cloned()
1316 .collect(),
1317 },
1318 )
1319 .unwrap();
1320 }
1321 }
1322 }
1323 let merge_update = merge_update.into_values().collect();
1324
1325 let mut actor_vnode_bitmap_update = HashMap::new();
1326 for reschedule in reschedules.values() {
1327 for (&actor_id, bitmap) in &reschedule.vnode_bitmap_updates {
1329 let bitmap = bitmap.to_protobuf();
1330 actor_vnode_bitmap_update
1331 .try_insert(actor_id, bitmap)
1332 .unwrap();
1333 }
1334 }
1335 let dropped_actors = reschedules
1336 .values()
1337 .flat_map(|r| r.removed_actors.iter().copied())
1338 .collect();
1339 let mut actor_splits = HashMap::new();
1340 let mut actor_cdc_table_snapshot_splits = HashMap::new();
1341 for (fragment_id, reschedule) in reschedules {
1342 for (actor_id, splits) in &reschedule.actor_splits {
1343 actor_splits.insert(
1344 *actor_id,
1345 ConnectorSplits {
1346 splits: splits.iter().map(ConnectorSplit::from).collect(),
1347 },
1348 );
1349 }
1350
1351 if let Some(assignment) =
1352 database_info.may_assign_fragment_cdc_backfill_splits(*fragment_id)?
1353 {
1354 actor_cdc_table_snapshot_splits.extend(assignment)
1355 }
1356 }
1357
1358 let actor_new_dispatchers = HashMap::new();
1360 let mutation = Mutation::Update(UpdateMutation {
1361 dispatcher_update,
1362 merge_update,
1363 actor_vnode_bitmap_update,
1364 dropped_actors,
1365 actor_splits,
1366 actor_new_dispatchers,
1367 actor_cdc_table_snapshot_splits: Some(PbCdcTableSnapshotSplitsWithGeneration {
1368 splits: actor_cdc_table_snapshot_splits,
1369 }),
1370 sink_schema_change: Default::default(),
1371 subscriptions_to_drop: vec![],
1372 iceberg_pk_index_compaction: None,
1373 });
1374 tracing::debug!("update mutation: {mutation:?}");
1375 Ok(Some(mutation))
1376 }
1377 }
1378 }
1379
1380 pub(super) fn create_subscription_to_mutation(
1382 upstream_mv_table_id: TableId,
1383 subscription_id: SubscriptionId,
1384 ) -> Mutation {
1385 {
1386 Mutation::Add(AddMutation {
1387 actor_dispatchers: Default::default(),
1388 added_actors: vec![],
1389 actor_splits: Default::default(),
1390 pause: false,
1391 subscriptions_to_add: vec![SubscriptionUpstreamInfo {
1392 upstream_mv_table_id,
1393 subscriber_id: subscription_id.as_subscriber_id(),
1394 }],
1395 backfill_nodes_to_pause: vec![],
1396 actor_cdc_table_snapshot_splits: None,
1397 new_upstream_sinks: Default::default(),
1398 dropped_actors: Default::default(),
1399 sink_log_store_flush: Default::default(),
1400 })
1401 }
1402 }
1403
1404 pub(super) fn drop_subscription_to_mutation(
1406 upstream_mv_table_id: TableId,
1407 subscription_id: SubscriptionId,
1408 ) -> Mutation {
1409 {
1410 Mutation::DropSubscriptions(DropSubscriptionsMutation {
1411 info: vec![SubscriptionUpstreamInfo {
1412 subscriber_id: subscription_id.as_subscriber_id(),
1413 upstream_mv_table_id,
1414 }],
1415 })
1416 }
1417 }
1418
1419 pub(super) fn connector_props_change_to_mutation(config: &ConnectorPropsChange) -> Mutation {
1421 {
1422 {
1423 let mut connector_props_infos = HashMap::default();
1424 for (k, v) in config {
1425 connector_props_infos.insert(
1426 k.as_raw_id(),
1427 ConnectorPropsInfo {
1428 connector_props_info: v.clone(),
1429 },
1430 );
1431 }
1432 Mutation::ConnectorPropsChange(ConnectorPropsChangeMutation {
1433 connector_props_infos,
1434 })
1435 }
1436 }
1437 }
1438
1439 pub(super) fn refresh_to_mutation(
1441 table_id: TableId,
1442 associated_source_id: SourceId,
1443 ) -> Mutation {
1444 Mutation::RefreshStart(risingwave_pb::stream_plan::RefreshStartMutation {
1445 table_id,
1446 associated_source_id,
1447 })
1448 }
1449
1450 pub(super) fn list_finish_to_mutation(associated_source_id: SourceId) -> Mutation {
1452 Mutation::ListFinish(ListFinishMutation {
1453 associated_source_id,
1454 })
1455 }
1456
1457 pub(super) fn load_finish_to_mutation(associated_source_id: SourceId) -> Mutation {
1459 Mutation::LoadFinish(LoadFinishMutation {
1460 associated_source_id,
1461 })
1462 }
1463
1464 pub(super) fn reset_source_to_mutation(source_id: SourceId) -> Mutation {
1466 Mutation::ResetSource(risingwave_pb::stream_plan::ResetSourceMutation {
1467 source_id: source_id.as_raw_id(),
1468 })
1469 }
1470
1471 pub(super) fn resume_backfill_to_mutation(
1473 target: &ResumeBackfillTarget,
1474 database_info: &InflightDatabaseInfo,
1475 ) -> MetaResult<Option<Mutation>> {
1476 {
1477 {
1478 let fragment_ids: HashSet<_> = match target {
1479 ResumeBackfillTarget::Job(job_id) => {
1480 database_info.backfill_fragment_ids_for_job(*job_id)?
1481 }
1482 ResumeBackfillTarget::Fragment(fragment_id) => {
1483 if !database_info.is_backfill_fragment(*fragment_id)? {
1484 return Err(MetaError::invalid_parameter(format!(
1485 "fragment {} is not a backfill node",
1486 fragment_id
1487 )));
1488 }
1489 HashSet::from([*fragment_id])
1490 }
1491 };
1492 if fragment_ids.is_empty() {
1493 warn!(
1494 ?target,
1495 "resume backfill command ignored because no backfill fragments found"
1496 );
1497 Ok(None)
1498 } else {
1499 Ok(Some(Mutation::StartFragmentBackfill(
1500 StartFragmentBackfillMutation {
1501 fragment_ids: fragment_ids.into_iter().collect(),
1502 },
1503 )))
1504 }
1505 }
1506 }
1507 }
1508
1509 pub(super) fn inject_source_offsets_to_mutation(
1511 source_id: SourceId,
1512 split_offsets: &HashMap<String, String>,
1513 ) -> Mutation {
1514 Mutation::InjectSourceOffsets(risingwave_pb::stream_plan::InjectSourceOffsetsMutation {
1515 source_id: source_id.as_raw_id(),
1516 split_offsets: split_offsets.clone(),
1517 })
1518 }
1519
1520 pub(super) fn create_streaming_job_actors_to_create(
1522 info: &CreateStreamingJobCommandInfo,
1523 edges: &mut FragmentEdgeBuildResult,
1524 stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1525 actor_location: &HashMap<ActorId, WorkerId>,
1526 ) -> StreamJobActorsToCreate {
1527 {
1528 {
1529 edges.collect_actors_to_create(info.stream_job_fragments.fragments.values().map(
1530 |fragment| {
1531 let actors = stream_actors
1532 .get(&fragment.fragment_id)
1533 .into_iter()
1534 .flatten()
1535 .map(|actor| (actor, actor_location[&actor.actor_id]));
1536 (
1537 fragment.fragment_id,
1538 &fragment.nodes,
1539 actors,
1540 [], )
1542 },
1543 ))
1544 }
1545 }
1546 }
1547
1548 pub(super) fn reschedule_actors_to_create(
1550 reschedules: &HashMap<FragmentId, Reschedule>,
1551 fragment_actors: &HashMap<FragmentId, HashSet<ActorId>>,
1552 database_info: &InflightDatabaseInfo,
1553 control_stream_manager: &ControlStreamManager,
1554 ) -> StreamJobActorsToCreate {
1555 {
1556 {
1557 let mut actor_upstreams = Self::collect_database_partial_graph_actor_upstreams(
1558 reschedules.iter().map(|(fragment_id, reschedule)| {
1559 (
1560 *fragment_id,
1561 reschedule.newly_created_actors.values().map(
1562 |((actor, dispatchers), _)| {
1563 (actor.actor_id, dispatchers.as_slice())
1564 },
1565 ),
1566 )
1567 }),
1568 Some((reschedules, fragment_actors)),
1569 database_info,
1570 control_stream_manager,
1571 );
1572 let mut map: HashMap<WorkerId, HashMap<_, (_, Vec<_>, _)>> = HashMap::new();
1573 for (fragment_id, (actor, dispatchers), worker_id) in
1574 reschedules.iter().flat_map(|(fragment_id, reschedule)| {
1575 reschedule
1576 .newly_created_actors
1577 .values()
1578 .map(|(actors, status)| (*fragment_id, actors, status))
1579 })
1580 {
1581 let upstreams = actor_upstreams.remove(&actor.actor_id).unwrap_or_default();
1582 map.entry(*worker_id)
1583 .or_default()
1584 .entry(fragment_id)
1585 .or_insert_with(|| {
1586 let node = database_info.fragment(fragment_id).nodes.clone();
1587 let subscribers =
1588 database_info.fragment_subscribers(fragment_id).collect();
1589 (node, vec![], subscribers)
1590 })
1591 .1
1592 .push((actor.clone(), upstreams, dispatchers.clone()));
1593 }
1594 map
1595 }
1596 }
1597 }
1598
1599 pub(super) fn replace_stream_job_actors_to_create(
1601 replace_table: &ReplaceStreamJobPlan,
1602 edges: &mut FragmentEdgeBuildResult,
1603 database_info: &InflightDatabaseInfo,
1604 stream_actors: &HashMap<FragmentId, Vec<StreamActor>>,
1605 actor_location: &HashMap<ActorId, WorkerId>,
1606 ) -> StreamJobActorsToCreate {
1607 {
1608 {
1609 let mut actors = edges.collect_actors_to_create(
1610 replace_table
1611 .new_fragments
1612 .fragments
1613 .values()
1614 .map(|fragment| {
1615 let actors = stream_actors
1616 .get(&fragment.fragment_id)
1617 .into_iter()
1618 .flatten()
1619 .map(|actor| (actor, actor_location[&actor.actor_id]));
1620 (
1621 fragment.fragment_id,
1622 &fragment.nodes,
1623 actors,
1624 database_info
1625 .job_subscribers(replace_table.old_fragments.stream_job_id),
1626 )
1627 }),
1628 );
1629
1630 if let Some(sinks) = &replace_table.auto_refresh_schema_sinks {
1632 let sink_actors = edges.collect_actors_to_create(sinks.iter().map(|sink| {
1633 (
1634 sink.new_fragment.fragment_id,
1635 &sink.new_fragment.nodes,
1636 stream_actors
1637 .get(&sink.new_fragment.fragment_id)
1638 .into_iter()
1639 .flatten()
1640 .map(|actor| (actor, actor_location[&actor.actor_id])),
1641 database_info.job_subscribers(sink.original_sink.id.as_job_id()),
1642 )
1643 }));
1644 for (worker_id, fragment_actors) in sink_actors {
1645 actors.entry(worker_id).or_default().extend(fragment_actors);
1646 }
1647 }
1648 actors
1649 }
1650 }
1651 }
1652
1653 fn generate_update_mutation_for_replace_table(
1654 dropped_actors: impl IntoIterator<Item = ActorId>,
1655 edges: FragmentEdgeBuildResult,
1656 split_assignment: &SplitAssignment,
1657 cdc_table_snapshot_split_assignment: Option<PbCdcTableSnapshotSplitsWithGeneration>,
1658 auto_refresh_schema_sinks: Option<&Vec<AutoRefreshSchemaSinkContext>>,
1659 ) -> Mutation {
1660 let dropped_actors = dropped_actors.into_iter().collect();
1661
1662 let actor_splits = split_assignment
1663 .values()
1664 .flat_map(build_actor_connector_splits)
1665 .collect();
1666 let mut mutation = UpdateMutation {
1667 dropped_actors,
1668 actor_splits,
1669 actor_cdc_table_snapshot_splits: cdc_table_snapshot_split_assignment,
1670 sink_schema_change: auto_refresh_schema_sinks
1671 .as_ref()
1672 .into_iter()
1673 .flat_map(|sinks| {
1674 sinks.iter().map(|sink| {
1675 let op = if !sink.removed_column_names.is_empty() {
1676 PbSinkSchemaChangeOp::DropColumns(PbSinkDropColumnsOp {
1677 column_names: sink.removed_column_names.clone(),
1678 })
1679 } else {
1680 PbSinkSchemaChangeOp::AddColumns(PbSinkAddColumnsOp {
1681 fields: sink
1682 .newly_add_fields
1683 .iter()
1684 .map(|field| field.to_prost())
1685 .collect(),
1686 })
1687 };
1688 (
1689 sink.original_sink.id.as_raw_id(),
1690 PbSinkSchemaChange {
1691 original_schema: sink_original_schema_fields(
1692 &sink.original_sink.columns,
1693 ),
1694 op: Some(op),
1695 },
1696 )
1697 })
1698 })
1699 .collect(),
1700 ..Default::default()
1701 };
1702 edges.apply_to_update_mutation(&mut mutation);
1703 Mutation::Update(mutation)
1704 }
1705}
1706
1707impl Command {
1708 #[expect(clippy::type_complexity)]
1709 pub(super) fn collect_database_partial_graph_actor_upstreams(
1710 actor_dispatchers: impl Iterator<
1711 Item = (FragmentId, impl Iterator<Item = (ActorId, &[Dispatcher])>),
1712 >,
1713 reschedule_dispatcher_update: Option<(
1714 &HashMap<FragmentId, Reschedule>,
1715 &HashMap<FragmentId, HashSet<ActorId>>,
1716 )>,
1717 database_info: &InflightDatabaseInfo,
1718 control_stream_manager: &ControlStreamManager,
1719 ) -> HashMap<ActorId, ActorUpstreams> {
1720 let mut actor_upstreams: HashMap<ActorId, ActorUpstreams> = HashMap::new();
1721 for (upstream_fragment_id, upstream_actors) in actor_dispatchers {
1722 let upstream_fragment = database_info.fragment(upstream_fragment_id);
1723 for (upstream_actor_id, dispatchers) in upstream_actors {
1724 let upstream_actor_location =
1725 upstream_fragment.actors[&upstream_actor_id].worker_id;
1726 let upstream_actor_host = control_stream_manager.host_addr(upstream_actor_location);
1727 for downstream_actor_id in dispatchers
1728 .iter()
1729 .flat_map(|dispatcher| dispatcher.downstream_actor_id.iter())
1730 {
1731 actor_upstreams
1732 .entry(*downstream_actor_id)
1733 .or_default()
1734 .entry(upstream_fragment_id)
1735 .or_default()
1736 .insert(
1737 upstream_actor_id,
1738 PbActorInfo {
1739 actor_id: upstream_actor_id,
1740 host: Some(upstream_actor_host.clone()),
1741 partial_graph_id: to_partial_graph_id(
1742 database_info.database_id,
1743 None,
1744 ),
1745 },
1746 );
1747 }
1748 }
1749 }
1750 if let Some((reschedules, fragment_actors)) = reschedule_dispatcher_update {
1751 for reschedule in reschedules.values() {
1752 for (upstream_fragment_id, _) in &reschedule.upstream_fragment_dispatcher_ids {
1753 let upstream_fragment = database_info.fragment(*upstream_fragment_id);
1754 let upstream_reschedule = reschedules.get(upstream_fragment_id);
1755 for upstream_actor_id in fragment_actors
1756 .get(upstream_fragment_id)
1757 .expect("should exist")
1758 {
1759 let upstream_actor_location =
1760 upstream_fragment.actors[upstream_actor_id].worker_id;
1761 let upstream_actor_host =
1762 control_stream_manager.host_addr(upstream_actor_location);
1763 if let Some(upstream_reschedule) = upstream_reschedule
1764 && upstream_reschedule
1765 .removed_actors
1766 .contains(upstream_actor_id)
1767 {
1768 continue;
1769 }
1770 for (_, downstream_actor_id) in
1771 reschedule
1772 .added_actors
1773 .iter()
1774 .flat_map(|(worker_id, actors)| {
1775 actors.iter().map(|actor| (*worker_id, *actor))
1776 })
1777 {
1778 actor_upstreams
1779 .entry(downstream_actor_id)
1780 .or_default()
1781 .entry(*upstream_fragment_id)
1782 .or_default()
1783 .insert(
1784 *upstream_actor_id,
1785 PbActorInfo {
1786 actor_id: *upstream_actor_id,
1787 host: Some(upstream_actor_host.clone()),
1788 partial_graph_id: to_partial_graph_id(
1789 database_info.database_id,
1790 None,
1791 ),
1792 },
1793 );
1794 }
1795 }
1796 }
1797 }
1798 }
1799 actor_upstreams
1800 }
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805 use risingwave_pb::data::PbDataType;
1806 use risingwave_pb::data::data_type::PbTypeName;
1807 use risingwave_pb::plan_common::{ColumnCatalog as PbColumnCatalog, ColumnDesc};
1808
1809 use super::sink_original_schema_fields;
1810
1811 fn column(name: &str, type_name: PbTypeName, is_hidden: bool) -> PbColumnCatalog {
1812 PbColumnCatalog {
1813 column_desc: Some(ColumnDesc {
1814 column_type: Some(PbDataType {
1815 type_name: type_name as i32,
1816 ..Default::default()
1817 }),
1818 name: name.to_owned(),
1819 ..Default::default()
1820 }),
1821 is_hidden,
1822 }
1823 }
1824
1825 #[test]
1826 fn test_sink_original_schema_fields_skips_hidden_columns() {
1827 let columns = vec![
1828 column("k", PbTypeName::Int32, false),
1829 column("v", PbTypeName::Varchar, false),
1830 column("_row_id", PbTypeName::Serial, true),
1831 ];
1832
1833 let fields = sink_original_schema_fields(&columns);
1834 let field_names = fields
1835 .iter()
1836 .map(|field| field.name.as_str())
1837 .collect::<Vec<_>>();
1838
1839 assert_eq!(field_names, ["k", "v"]);
1840 }
1841}