Skip to main content

risingwave_meta/rpc/
ddl_controller.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::cmp::Ordering;
16use std::collections::{HashMap, HashSet};
17use std::num::NonZeroUsize;
18use std::sync::Arc;
19use std::sync::atomic::AtomicU64;
20use std::time::Duration;
21
22use anyhow::{Context, anyhow};
23use await_tree::InstrumentAwait;
24use either::Either;
25use itertools::Itertools;
26use risingwave_common::catalog::{
27    AlterDatabaseParam, ColumnCatalog, ColumnId, Field, FragmentTypeFlag,
28};
29use risingwave_common::hash::VnodeCountCompat;
30use risingwave_common::id::{JobId, TableId};
31use risingwave_common::secret::{LocalSecretManager, SecretEncryption};
32use risingwave_common::system_param::adaptive_parallelism_strategy::parse_strategy;
33use risingwave_common::system_param::reader::SystemParamsRead;
34use risingwave_common::util::stream_graph_visitor::visit_stream_node_cont_mut;
35use risingwave_common::{bail, bail_not_implemented};
36use risingwave_connector::WithOptionsSecResolved;
37use risingwave_connector::connector_common::validate_connection;
38use risingwave_connector::sink::SinkParam;
39use risingwave_connector::sink::iceberg::IcebergSink;
40use risingwave_connector::source::cdc::CdcScanOptions;
41use risingwave_connector::source::{
42    ConnectorProperties, SourceEnumeratorContext, UPSTREAM_SOURCE_KEY,
43};
44use risingwave_meta_model::object::ObjectType;
45use risingwave_meta_model::refresh_job::RefreshState;
46use risingwave_meta_model::{
47    ConnectionId, DatabaseId, DispatcherType, FragmentId, FunctionId, IndexId, JobStatus, ObjectId,
48    SchemaId, SecretId, SinkId, SourceId, StreamingParallelism, SubscriptionId, UserId, ViewId,
49    streaming_job,
50};
51use risingwave_pb::catalog::{
52    Comment, Connection, CreateType, Database, Function, PbTable, Schema, Secret, Source,
53    Subscription, Table, View,
54};
55use risingwave_pb::ddl_service::alter_owner_request::Object;
56use risingwave_pb::ddl_service::{
57    DdlProgress, TableJobType, WaitVersion, alter_name_request, alter_set_schema_request,
58    alter_swap_rename_request, streaming_job_resource_type,
59};
60use risingwave_pb::meta::table_fragments::fragment::FragmentDistributionType as PbFragmentDistributionType;
61use risingwave_pb::plan_common::{PbColumnCatalog, PbExternalTableDesc};
62use risingwave_pb::stream_plan::stream_node::NodeBody;
63use risingwave_pb::stream_plan::{
64    PbDispatchOutputMapping, PbStreamFragmentGraph, PbStreamNode, PbUpstreamSinkInfo,
65    StreamFragmentGraph as StreamFragmentGraphProto,
66};
67use risingwave_pb::telemetry::{PbTelemetryDatabaseObject, PbTelemetryEventStage};
68use strum::Display;
69use thiserror_ext::AsReport;
70use tokio::sync::Semaphore;
71use tokio::time::sleep;
72use tracing::Instrument;
73
74use crate::barrier::{BarrierManagerRef, Command};
75use crate::controller::catalog::{
76    CrossDbSubscriptionInfo, DropTableConnectorContext, ReleaseContext,
77};
78use crate::controller::streaming_job::{FinishAutoRefreshSchemaSinkContext, SinkIntoTableContext};
79use crate::controller::utils::build_select_node_list;
80use crate::error::{MetaErrorInner, bail_invalid_parameter};
81use crate::manager::iceberg_pk_index_sink::IcebergPkIndexSinkManager;
82use crate::manager::{
83    IGNORED_NOTIFICATION_VERSION, LocalNotification, MetaSrvEnv, MetadataManager,
84    NotificationVersion, StreamingJob, StreamingJobType,
85};
86use crate::model::{
87    DownstreamFragmentRelation, FragmentDownstreamRelation, FragmentId as CatalogFragmentId,
88    StreamContext, StreamJobFragments, StreamJobFragmentsToCreate,
89};
90use crate::stream::cdc::{
91    parallel_cdc_table_backfill_fragment, try_init_parallel_cdc_table_snapshot_splits,
92};
93use crate::stream::{
94    ActorGraphBuildResult, ActorGraphBuilder, AutoRefreshSchemaSinkContext,
95    CompleteStreamFragmentGraph, CreateStreamingJobContext, CreateStreamingJobOption,
96    FragmentGraphDownstreamContext, FragmentGraphUpstreamContext, GlobalStreamManagerRef,
97    ParallelismPolicy, ReplaceStreamJobContext, ReschedulePolicy, SourceChange, SourceManagerRef,
98    StreamFragmentGraph, UpstreamSinkInfo, check_sink_fragments_support_refresh_schema,
99    create_source_worker, first_variant_column, rewrite_refresh_schema_sink_fragment, state_match,
100    validate_sink,
101};
102use crate::telemetry::report_event;
103use crate::{MetaError, MetaResult};
104
105#[derive(PartialEq)]
106pub enum DropMode {
107    Restrict,
108    Cascade,
109}
110
111impl DropMode {
112    pub fn from_request_setting(cascade: bool) -> DropMode {
113        if cascade {
114            DropMode::Cascade
115        } else {
116            DropMode::Restrict
117        }
118    }
119}
120
121#[derive(strum::AsRefStr)]
122pub enum StreamingJobId {
123    MaterializedView(TableId),
124    Sink(SinkId),
125    Table(Option<SourceId>, TableId),
126    Index(IndexId),
127}
128
129impl std::fmt::Display for StreamingJobId {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        write!(f, "{}", self.as_ref())?;
132        write!(f, "({})", self.id())
133    }
134}
135
136impl StreamingJobId {
137    fn id(&self) -> JobId {
138        match self {
139            StreamingJobId::MaterializedView(id) | StreamingJobId::Table(_, id) => id.as_job_id(),
140            StreamingJobId::Index(id) => id.as_job_id(),
141            StreamingJobId::Sink(id) => id.as_job_id(),
142        }
143    }
144}
145
146/// It’s used to describe the information of the job that needs to be replaced
147/// and it will be used during replacing table and creating sink into table operations.
148pub struct ReplaceStreamJobInfo {
149    pub streaming_job: StreamingJob,
150    pub fragment_graph: StreamFragmentGraphProto,
151}
152
153#[derive(Display)]
154pub enum DdlCommand {
155    CreateDatabase(Database),
156    DropDatabase(DatabaseId),
157    CreateSchema(Schema),
158    DropSchema(SchemaId, DropMode),
159    CreateNonSharedSource(Source, Option<TableId>),
160    DropSource(SourceId, DropMode),
161    ResetSource(SourceId),
162    CreateFunction(Function),
163    DropFunction(FunctionId, DropMode),
164    CreateView(View, HashSet<ObjectId>),
165    DropView(ViewId, DropMode),
166    CreateStreamingJob {
167        stream_job: StreamingJob,
168        fragment_graph: StreamFragmentGraphProto,
169        dependencies: HashSet<ObjectId>,
170        resource_type: streaming_job_resource_type::ResourceType,
171        if_not_exists: bool,
172        refresh_interval_sec: Option<u64>,
173        replace_sink: Option<SinkId>,
174        since_timestamp_epoch: Option<u64>,
175    },
176    DropStreamingJob {
177        job_id: StreamingJobId,
178        drop_mode: DropMode,
179    },
180    AlterName(alter_name_request::Object, String),
181    AlterSwapRename(alter_swap_rename_request::Object),
182    ReplaceStreamJob(ReplaceStreamJobInfo),
183    AlterNonSharedSource(Source),
184    AlterObjectOwner(Object, UserId),
185    AlterSetSchema(alter_set_schema_request::Object, SchemaId),
186    CreateConnection(Connection),
187    DropConnection(ConnectionId, DropMode),
188    CreateSecret(Secret),
189    AlterSecret(Secret),
190    DropSecret(SecretId, DropMode),
191    CommentOn(Comment),
192    CreateSubscription(Subscription),
193    DropSubscription(SubscriptionId, DropMode),
194    AlterSubscriptionRetention {
195        subscription_id: SubscriptionId,
196        retention_seconds: u64,
197        definition: String,
198    },
199    AlterDatabaseParam(DatabaseId, AlterDatabaseParam),
200    AlterDatabaseResourceGroup(DatabaseId, Option<String>, bool),
201    AlterStreamingJobConfig(JobId, HashMap<String, String>, Vec<String>),
202}
203
204impl DdlCommand {
205    /// Returns the name or ID of the object that this command operates on, for observability and debugging.
206    fn object(&self) -> Either<String, ObjectId> {
207        use Either::*;
208        match self {
209            DdlCommand::CreateDatabase(database) => Left(database.name.clone()),
210            DdlCommand::DropDatabase(id) => Right(id.as_object_id()),
211            DdlCommand::CreateSchema(schema) => Left(schema.name.clone()),
212            DdlCommand::DropSchema(id, _) => Right(id.as_object_id()),
213            DdlCommand::CreateNonSharedSource(source, _) => Left(source.name.clone()),
214            DdlCommand::DropSource(id, _) => Right(id.as_object_id()),
215            DdlCommand::ResetSource(id) => Right(id.as_object_id()),
216            DdlCommand::CreateFunction(function) => Left(function.name.clone()),
217            DdlCommand::DropFunction(id, _) => Right(id.as_object_id()),
218            DdlCommand::CreateView(view, _) => Left(view.name.clone()),
219            DdlCommand::DropView(id, _) => Right(id.as_object_id()),
220            DdlCommand::CreateStreamingJob { stream_job, .. } => Left(stream_job.name()),
221            DdlCommand::DropStreamingJob { job_id, .. } => Right(job_id.id().as_object_id()),
222            DdlCommand::AlterName(object, _) => Left(format!("{object:?}")),
223            DdlCommand::AlterSwapRename(object) => Left(format!("{object:?}")),
224            DdlCommand::ReplaceStreamJob(info) => Left(info.streaming_job.name()),
225            DdlCommand::AlterNonSharedSource(source) => Left(source.name.clone()),
226            DdlCommand::AlterObjectOwner(object, _) => Left(format!("{object:?}")),
227            DdlCommand::AlterSetSchema(object, _) => Left(format!("{object:?}")),
228            DdlCommand::CreateConnection(connection) => Left(connection.name.clone()),
229            DdlCommand::DropConnection(id, _) => Right(id.as_object_id()),
230            DdlCommand::CreateSecret(secret) => Left(secret.name.clone()),
231            DdlCommand::AlterSecret(secret) => Left(secret.name.clone()),
232            DdlCommand::DropSecret(id, _) => Right(id.as_object_id()),
233            DdlCommand::CommentOn(comment) => Right(comment.table_id.into()),
234            DdlCommand::CreateSubscription(subscription) => Left(subscription.name.clone()),
235            DdlCommand::DropSubscription(id, _) => Right(id.as_object_id()),
236            DdlCommand::AlterSubscriptionRetention {
237                subscription_id, ..
238            } => Right(subscription_id.as_object_id()),
239            DdlCommand::AlterDatabaseParam(id, _) => Right(id.as_object_id()),
240            DdlCommand::AlterDatabaseResourceGroup(id, _, _) => Right(id.as_object_id()),
241            DdlCommand::AlterStreamingJobConfig(job_id, _, _) => Right(job_id.as_object_id()),
242        }
243    }
244
245    fn allow_in_recovery(&self) -> bool {
246        match self {
247            DdlCommand::DropDatabase(_)
248            | DdlCommand::DropSchema(_, _)
249            | DdlCommand::DropSource(_, _)
250            | DdlCommand::DropFunction(_, _)
251            | DdlCommand::DropView(_, _)
252            | DdlCommand::DropStreamingJob { .. }
253            | DdlCommand::DropConnection(_, _)
254            | DdlCommand::DropSecret(_, _)
255            | DdlCommand::DropSubscription(_, _)
256            | DdlCommand::AlterName(_, _)
257            | DdlCommand::AlterObjectOwner(_, _)
258            | DdlCommand::AlterSetSchema(_, _)
259            | DdlCommand::CreateDatabase(_)
260            | DdlCommand::CreateSchema(_)
261            | DdlCommand::CreateFunction(_)
262            | DdlCommand::CreateView(_, _)
263            | DdlCommand::CreateConnection(_)
264            | DdlCommand::CommentOn(_)
265            | DdlCommand::CreateSecret(_)
266            | DdlCommand::AlterSecret(_)
267            | DdlCommand::AlterSwapRename(_)
268            | DdlCommand::AlterDatabaseParam(_, _)
269            | DdlCommand::AlterDatabaseResourceGroup(_, _, _)
270            | DdlCommand::AlterStreamingJobConfig(_, _, _)
271            | DdlCommand::AlterSubscriptionRetention { .. } => true,
272            DdlCommand::CreateStreamingJob { .. }
273            | DdlCommand::CreateNonSharedSource(_, _)
274            | DdlCommand::ReplaceStreamJob(_)
275            | DdlCommand::AlterNonSharedSource(_)
276            | DdlCommand::ResetSource(_)
277            | DdlCommand::CreateSubscription(_) => false,
278        }
279    }
280}
281
282#[derive(Clone)]
283pub struct DdlController {
284    pub(crate) env: MetaSrvEnv,
285
286    pub(crate) metadata_manager: MetadataManager,
287    pub(crate) stream_manager: GlobalStreamManagerRef,
288    pub(crate) source_manager: SourceManagerRef,
289    barrier_manager: BarrierManagerRef,
290    iceberg_pk_index_sink_manager: IcebergPkIndexSinkManager,
291
292    // The semaphore is used to limit the number of concurrent streaming job creation.
293    pub(crate) creating_streaming_job_permits: Arc<CreatingStreamingJobPermit>,
294
295    /// Sequence number for DDL commands, used for observability and debugging.
296    seq: Arc<AtomicU64>,
297}
298
299#[derive(Clone)]
300pub struct CreatingStreamingJobPermit {
301    pub(crate) semaphore: Arc<Semaphore>,
302}
303
304impl CreatingStreamingJobPermit {
305    async fn new(env: &MetaSrvEnv) -> Self {
306        let mut permits = env
307            .system_params_reader()
308            .await
309            .max_concurrent_creating_streaming_jobs() as usize;
310        if permits == 0 {
311            // if the system parameter is set to zero, use the max permitted value.
312            permits = Semaphore::MAX_PERMITS;
313        }
314        let semaphore = Arc::new(Semaphore::new(permits));
315
316        let (local_notification_tx, mut local_notification_rx) =
317            tokio::sync::mpsc::unbounded_channel();
318        env.notification_manager()
319            .insert_local_sender(local_notification_tx);
320        let semaphore_clone = semaphore.clone();
321        tokio::spawn(async move {
322            while let Some(notification) = local_notification_rx.recv().await {
323                let LocalNotification::SystemParamsChange(p) = &notification else {
324                    continue;
325                };
326                let mut new_permits = p.max_concurrent_creating_streaming_jobs() as usize;
327                if new_permits == 0 {
328                    new_permits = Semaphore::MAX_PERMITS;
329                }
330                match permits.cmp(&new_permits) {
331                    Ordering::Less => {
332                        semaphore_clone.add_permits(new_permits - permits);
333                    }
334                    Ordering::Equal => continue,
335                    Ordering::Greater => {
336                        let to_release = permits - new_permits;
337                        let reduced = semaphore_clone.forget_permits(to_release);
338                        // TODO: implement dynamic semaphore with limits by ourself.
339                        if reduced != to_release {
340                            tracing::warn!(
341                                "no enough permits to release, expected {}, but reduced {}",
342                                to_release,
343                                reduced
344                            );
345                        }
346                    }
347                }
348                tracing::info!(
349                    "max_concurrent_creating_streaming_jobs changed from {} to {}",
350                    permits,
351                    new_permits
352                );
353                permits = new_permits;
354            }
355        });
356
357        Self { semaphore }
358    }
359}
360
361impl DdlController {
362    fn validate_specified_parallelism(
363        specified_parallelism: Option<NonZeroUsize>,
364        specified_backfill_parallelism: Option<NonZeroUsize>,
365        max_parallelism: NonZeroUsize,
366    ) -> MetaResult<()> {
367        if let Some(parallelism) = specified_parallelism
368            && parallelism > max_parallelism
369        {
370            bail_invalid_parameter!(
371                "specified parallelism {} should not exceed max parallelism {}",
372                parallelism,
373                max_parallelism,
374            );
375        }
376        if let Some(backfill_parallelism) = specified_backfill_parallelism
377            && backfill_parallelism > max_parallelism
378        {
379            bail_invalid_parameter!(
380                "specified backfill parallelism {} should not exceed max parallelism {}",
381                backfill_parallelism,
382                max_parallelism,
383            );
384        }
385        Ok(())
386    }
387
388    fn validate_serverless_backfill_enabled(
389        &self,
390        resource_type: &streaming_job_resource_type::ResourceType,
391    ) -> MetaResult<()> {
392        if matches!(
393            resource_type,
394            streaming_job_resource_type::ResourceType::ServerlessBackfill(true)
395        ) && self.env.opts.serverless_backfill_controller_addr.is_empty()
396        {
397            bail_invalid_parameter!(
398                "Serverless Backfill is disabled. Use RisingWave cloud at https://cloud.risingwave.com/auth/signup to try this feature"
399            );
400        }
401
402        Ok(())
403    }
404
405    pub async fn new(
406        env: MetaSrvEnv,
407        metadata_manager: MetadataManager,
408        stream_manager: GlobalStreamManagerRef,
409        source_manager: SourceManagerRef,
410        barrier_manager: BarrierManagerRef,
411        iceberg_pk_index_sink_manager: IcebergPkIndexSinkManager,
412    ) -> Self {
413        let creating_streaming_job_permits = Arc::new(CreatingStreamingJobPermit::new(&env).await);
414        Self {
415            env,
416            metadata_manager,
417            stream_manager,
418            source_manager,
419            barrier_manager,
420            iceberg_pk_index_sink_manager,
421            creating_streaming_job_permits,
422            seq: Arc::new(AtomicU64::new(0)),
423        }
424    }
425
426    /// Obtains the next sequence number for DDL commands, for observability and debugging purposes.
427    pub fn next_seq(&self) -> u64 {
428        // This is a simple atomic increment operation.
429        self.seq.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
430    }
431
432    /// `run_command` spawns a tokio coroutine to execute the target ddl command. When the client
433    /// has been interrupted during executing, the request will be cancelled by tonic. Since we have
434    /// a lot of logic for revert, status management, notification and so on, ensuring consistency
435    /// would be a huge hassle and pain if we don't spawn here.
436    ///
437    /// Though returning `Option`, it's always `Some`, to simplify the handling logic
438    pub async fn run_command(&self, command: DdlCommand) -> MetaResult<Option<WaitVersion>> {
439        if !command.allow_in_recovery() {
440            self.barrier_manager.check_status_running()?;
441        }
442
443        let await_tree_key = format!("DDL Command {}", self.next_seq());
444        let await_tree_span = await_tree::span!("{command}({})", command.object());
445
446        let ctrl = self.clone();
447        let fut = Box::pin(async move {
448            match command {
449                DdlCommand::CreateDatabase(database) => ctrl.create_database(database).await,
450                DdlCommand::DropDatabase(database_id) => ctrl.drop_database(database_id).await,
451                DdlCommand::CreateSchema(schema) => ctrl.create_schema(schema).await,
452                DdlCommand::DropSchema(schema_id, drop_mode) => {
453                    ctrl.drop_schema(schema_id, drop_mode).await
454                }
455                DdlCommand::CreateNonSharedSource(source, iceberg_table_id) => {
456                    ctrl.create_non_shared_source(source, iceberg_table_id)
457                        .await
458                }
459                DdlCommand::DropSource(source_id, drop_mode) => {
460                    ctrl.drop_source(source_id, drop_mode).await
461                }
462                DdlCommand::ResetSource(source_id) => ctrl.reset_source(source_id).await,
463                DdlCommand::CreateFunction(function) => ctrl.create_function(function).await,
464                DdlCommand::DropFunction(function_id, drop_mode) => {
465                    ctrl.drop_function(function_id, drop_mode).await
466                }
467                DdlCommand::CreateView(view, dependencies) => {
468                    ctrl.create_view(view, dependencies).await
469                }
470                DdlCommand::DropView(view_id, drop_mode) => {
471                    ctrl.drop_view(view_id, drop_mode).await
472                }
473                DdlCommand::CreateStreamingJob {
474                    stream_job,
475                    fragment_graph,
476                    dependencies,
477                    resource_type,
478                    if_not_exists,
479                    refresh_interval_sec,
480                    replace_sink,
481                    since_timestamp_epoch,
482                } => {
483                    ctrl.create_streaming_job(
484                        stream_job,
485                        fragment_graph,
486                        dependencies,
487                        resource_type,
488                        if_not_exists,
489                        refresh_interval_sec,
490                        replace_sink,
491                        since_timestamp_epoch,
492                    )
493                    .await
494                }
495                DdlCommand::DropStreamingJob { job_id, drop_mode } => {
496                    ctrl.drop_streaming_job(job_id, drop_mode).await
497                }
498                DdlCommand::ReplaceStreamJob(ReplaceStreamJobInfo {
499                    streaming_job,
500                    fragment_graph,
501                }) => ctrl.replace_job(streaming_job, fragment_graph).await,
502                DdlCommand::AlterName(relation, name) => ctrl.alter_name(relation, &name).await,
503                DdlCommand::AlterObjectOwner(object, owner_id) => {
504                    ctrl.alter_owner(object, owner_id).await
505                }
506                DdlCommand::AlterSetSchema(object, new_schema_id) => {
507                    ctrl.alter_set_schema(object, new_schema_id).await
508                }
509                DdlCommand::CreateConnection(connection) => {
510                    ctrl.create_connection(connection).await
511                }
512                DdlCommand::DropConnection(connection_id, drop_mode) => {
513                    ctrl.drop_connection(connection_id, drop_mode).await
514                }
515                DdlCommand::CreateSecret(secret) => ctrl.create_secret(secret).await,
516                DdlCommand::DropSecret(secret_id, drop_mode) => {
517                    ctrl.drop_secret(secret_id, drop_mode).await
518                }
519                DdlCommand::AlterSecret(secret) => ctrl.alter_secret(secret).await,
520                DdlCommand::AlterNonSharedSource(source) => {
521                    ctrl.alter_non_shared_source(source).await
522                }
523                DdlCommand::CommentOn(comment) => ctrl.comment_on(comment).await,
524                DdlCommand::CreateSubscription(subscription) => {
525                    ctrl.create_subscription(subscription).await
526                }
527                DdlCommand::DropSubscription(subscription_id, drop_mode) => {
528                    ctrl.drop_subscription(subscription_id, drop_mode).await
529                }
530                DdlCommand::AlterSubscriptionRetention {
531                    subscription_id,
532                    retention_seconds,
533                    definition,
534                } => {
535                    ctrl.alter_subscription_retention(
536                        subscription_id,
537                        retention_seconds,
538                        definition,
539                    )
540                    .await
541                }
542                DdlCommand::AlterSwapRename(objects) => ctrl.alter_swap_rename(objects).await,
543                DdlCommand::AlterDatabaseParam(database_id, param) => {
544                    ctrl.alter_database_param(database_id, param).await
545                }
546                DdlCommand::AlterDatabaseResourceGroup(database_id, resource_group, deferred) => {
547                    ctrl.alter_database_resource_group(database_id, resource_group, deferred)
548                        .await
549                }
550                DdlCommand::AlterStreamingJobConfig(job_id, entries_to_add, keys_to_remove) => {
551                    ctrl.alter_streaming_job_config(job_id, entries_to_add, keys_to_remove)
552                        .await
553                }
554            }
555        })
556        .in_current_span();
557        let fut = (self.env.await_tree_reg())
558            .register(await_tree_key, await_tree_span)
559            .instrument(Box::pin(fut));
560        let notification_version = tokio::spawn(fut).await.map_err(|e| anyhow!(e))??;
561        Ok(Some(WaitVersion {
562            catalog_version: notification_version,
563            hummock_version_id: self.barrier_manager.get_hummock_version_id().await,
564        }))
565    }
566
567    pub async fn get_ddl_progress(&self) -> MetaResult<Vec<DdlProgress>> {
568        self.barrier_manager.get_ddl_progress().await
569    }
570
571    async fn create_database(&self, database: Database) -> MetaResult<NotificationVersion> {
572        let (version, updated_db) = self
573            .metadata_manager
574            .catalog_controller
575            .create_database(database)
576            .await?;
577        // If persistent successfully, notify `GlobalBarrierManager` to create database asynchronously.
578        self.barrier_manager
579            .update_database_barrier(
580                updated_db.database_id,
581                updated_db.barrier_interval_ms.map(|v| v as u32),
582                updated_db.checkpoint_frequency.map(|v| v as u64),
583            )
584            .await?;
585        Ok(version)
586    }
587
588    #[tracing::instrument(skip(self), level = "debug")]
589    pub async fn reschedule_streaming_job(
590        &self,
591        job_id: JobId,
592        target: ReschedulePolicy,
593        mut deferred: bool,
594    ) -> MetaResult<()> {
595        tracing::info!("altering parallelism for job {}", job_id);
596        if self.barrier_manager.check_status_running().is_err() {
597            tracing::info!(
598                "alter parallelism is set to deferred mode because the system is in recovery state"
599            );
600            deferred = true;
601        }
602
603        self.stream_manager
604            .reschedule_streaming_job(job_id, target, deferred)
605            .await
606    }
607
608    pub async fn reschedule_streaming_job_backfill_parallelism(
609        &self,
610        job_id: JobId,
611        parallelism: Option<ParallelismPolicy>,
612        mut deferred: bool,
613    ) -> MetaResult<()> {
614        tracing::info!("altering backfill parallelism for job {}", job_id);
615        if self.barrier_manager.check_status_running().is_err() {
616            tracing::info!(
617                "alter backfill parallelism is set to deferred mode because the system is in recovery state"
618            );
619            deferred = true;
620        }
621
622        self.stream_manager
623            .reschedule_streaming_job_backfill_parallelism(job_id, parallelism, deferred)
624            .await
625    }
626
627    pub async fn reschedule_cdc_table_backfill(
628        &self,
629        job_id: JobId,
630        target: ReschedulePolicy,
631    ) -> MetaResult<()> {
632        tracing::info!("alter CDC table backfill parallelism");
633        if self.barrier_manager.check_status_running().is_err() {
634            return Err(anyhow::anyhow!("CDC table backfill reschedule is unavailable because the system is in recovery state").into());
635        }
636        self.stream_manager
637            .reschedule_cdc_table_backfill(job_id, target)
638            .await
639    }
640
641    pub async fn reschedule_fragments(
642        &self,
643        fragment_targets: HashMap<FragmentId, Option<StreamingParallelism>>,
644    ) -> MetaResult<()> {
645        tracing::info!(
646            "altering parallelism for fragments {:?}",
647            fragment_targets.keys()
648        );
649        let fragment_targets = fragment_targets
650            .into_iter()
651            .map(|(fragment_id, parallelism)| (fragment_id as CatalogFragmentId, parallelism))
652            .collect();
653
654        self.stream_manager
655            .reschedule_fragments(fragment_targets)
656            .await
657    }
658
659    async fn drop_database(&self, database_id: DatabaseId) -> MetaResult<NotificationVersion> {
660        self.drop_object(ObjectType::Database, database_id, DropMode::Cascade)
661            .await
662    }
663
664    async fn create_schema(&self, schema: Schema) -> MetaResult<NotificationVersion> {
665        self.metadata_manager
666            .catalog_controller
667            .create_schema(schema)
668            .await
669    }
670
671    async fn drop_schema(
672        &self,
673        schema_id: SchemaId,
674        drop_mode: DropMode,
675    ) -> MetaResult<NotificationVersion> {
676        self.drop_object(ObjectType::Schema, schema_id, drop_mode)
677            .await
678    }
679
680    /// Shared source is handled in [`Self::create_streaming_job`]
681    async fn create_non_shared_source(
682        &self,
683        source: Source,
684        iceberg_table_id: Option<TableId>,
685    ) -> MetaResult<NotificationVersion> {
686        if let Some(cdc_table_desc) = source
687            .info
688            .as_ref()
689            .and_then(|info| info.external_table.as_ref())
690        {
691            assert!(iceberg_table_id.is_none());
692            // A CDC table source has no streaming job, so validate the declared schema against
693            // the upstream table here, the same way `CREATE TABLE ... FROM <cdc source>` does
694            // while creating its job.
695            self.validate_cdc_table_desc(cdc_table_desc).await?;
696            let (_, version) = self
697                .metadata_manager
698                .catalog_controller
699                .create_source(source, iceberg_table_id)
700                .await?;
701            return Ok(version);
702        }
703
704        let handle = create_source_worker(
705            &source,
706            self.source_manager.metrics.clone(),
707            self.env.await_tree_reg().clone(),
708        )
709        .await
710        .context("failed to create source worker")?;
711
712        let (source_id, version) = self
713            .metadata_manager
714            .catalog_controller
715            .create_source(source, iceberg_table_id)
716            .await?;
717        self.source_manager
718            .register_source_with_handle(source_id, handle)
719            .await;
720        Ok(version)
721    }
722
723    async fn drop_source(
724        &self,
725        source_id: SourceId,
726        drop_mode: DropMode,
727    ) -> MetaResult<NotificationVersion> {
728        self.drop_object(ObjectType::Source, source_id, drop_mode)
729            .await
730    }
731
732    async fn reset_source(&self, source_id: SourceId) -> MetaResult<NotificationVersion> {
733        tracing::info!(source_id = %source_id, "resetting CDC source offset to latest");
734
735        // Get database_id for the source
736        let database_id = self
737            .metadata_manager
738            .catalog_controller
739            .get_object_database_id(source_id)
740            .await?;
741
742        self.stream_manager
743            .barrier_scheduler
744            .run_command(database_id, Command::ResetSource { source_id })
745            .await?;
746
747        // RESET SOURCE doesn't modify catalog, so return the current catalog version.
748        let version = self
749            .metadata_manager
750            .catalog_controller
751            .current_notification_version()
752            .await;
753        Ok(version)
754    }
755
756    /// This replaces the source in the catalog.
757    /// Note: `StreamSourceInfo` in downstream MVs' `SourceExecutor`s are not updated.
758    async fn alter_non_shared_source(&self, source: Source) -> MetaResult<NotificationVersion> {
759        self.metadata_manager
760            .catalog_controller
761            .alter_non_shared_source(source)
762            .await
763    }
764
765    async fn create_function(&self, function: Function) -> MetaResult<NotificationVersion> {
766        self.metadata_manager
767            .catalog_controller
768            .create_function(function)
769            .await
770    }
771
772    async fn drop_function(
773        &self,
774        function_id: FunctionId,
775        drop_mode: DropMode,
776    ) -> MetaResult<NotificationVersion> {
777        self.drop_object(ObjectType::Function, function_id, drop_mode)
778            .await
779    }
780
781    async fn create_view(
782        &self,
783        view: View,
784        dependencies: HashSet<ObjectId>,
785    ) -> MetaResult<NotificationVersion> {
786        self.metadata_manager
787            .catalog_controller
788            .create_view(view, dependencies)
789            .await
790    }
791
792    async fn drop_view(
793        &self,
794        view_id: ViewId,
795        drop_mode: DropMode,
796    ) -> MetaResult<NotificationVersion> {
797        self.drop_object(ObjectType::View, view_id, drop_mode).await
798    }
799
800    async fn create_connection(&self, connection: Connection) -> MetaResult<NotificationVersion> {
801        validate_connection(&connection).await?;
802        self.metadata_manager
803            .catalog_controller
804            .create_connection(connection)
805            .await
806    }
807
808    async fn drop_connection(
809        &self,
810        connection_id: ConnectionId,
811        drop_mode: DropMode,
812    ) -> MetaResult<NotificationVersion> {
813        self.drop_object(ObjectType::Connection, connection_id, drop_mode)
814            .await
815    }
816
817    async fn alter_database_param(
818        &self,
819        database_id: DatabaseId,
820        param: AlterDatabaseParam,
821    ) -> MetaResult<NotificationVersion> {
822        let (version, updated_db) = self
823            .metadata_manager
824            .catalog_controller
825            .alter_database_param(database_id, param)
826            .await?;
827        // If persistent successfully, notify `GlobalBarrierManager` to update param asynchronously.
828        self.barrier_manager
829            .update_database_barrier(
830                database_id,
831                updated_db.barrier_interval_ms.map(|v| v as u32),
832                updated_db.checkpoint_frequency.map(|v| v as u64),
833            )
834            .await?;
835        Ok(version)
836    }
837
838    async fn alter_database_resource_group(
839        &self,
840        database_id: DatabaseId,
841        resource_group: Option<String>,
842        _deferred: bool,
843    ) -> MetaResult<NotificationVersion> {
844        let version = self
845            .metadata_manager
846            .catalog_controller
847            .alter_database_resource_group(database_id, resource_group)
848            .await?;
849
850        Ok(version)
851    }
852
853    // The 'secret' part of the request we receive from the frontend is in plaintext;
854    // here, we need to encrypt it before storing it in the catalog.
855    fn get_encrypted_payload(&self, secret: &Secret) -> MetaResult<Vec<u8>> {
856        let secret_store_private_key = self
857            .env
858            .opts
859            .secret_store_private_key
860            .clone()
861            .ok_or_else(|| anyhow!("secret_store_private_key is not configured"))?;
862
863        let encrypted_payload = SecretEncryption::encrypt(
864            secret_store_private_key.as_slice(),
865            secret.get_value().as_slice(),
866        )
867        .context(format!("failed to encrypt secret {}", secret.name))?;
868        Ok(encrypted_payload
869            .serialize()
870            .context(format!("failed to serialize secret {}", secret.name))?)
871    }
872
873    async fn create_secret(&self, mut secret: Secret) -> MetaResult<NotificationVersion> {
874        // The 'secret' part of the request we receive from the frontend is in plaintext;
875        // here, we need to encrypt it before storing it in the catalog.
876        let secret_plain_payload = secret.value.clone();
877        let encrypted_payload = self.get_encrypted_payload(&secret)?;
878        secret.value = encrypted_payload;
879
880        self.metadata_manager
881            .catalog_controller
882            .create_secret(secret, secret_plain_payload)
883            .await
884    }
885
886    async fn drop_secret(
887        &self,
888        secret_id: SecretId,
889        drop_mode: DropMode,
890    ) -> MetaResult<NotificationVersion> {
891        self.drop_object(ObjectType::Secret, secret_id, drop_mode)
892            .await
893    }
894
895    async fn alter_secret(&self, mut secret: Secret) -> MetaResult<NotificationVersion> {
896        let secret_plain_payload = secret.value.clone();
897        let encrypted_payload = self.get_encrypted_payload(&secret)?;
898        secret.value = encrypted_payload;
899        self.metadata_manager
900            .catalog_controller
901            .alter_secret(secret, secret_plain_payload)
902            .await
903    }
904
905    async fn create_subscription(
906        &self,
907        mut subscription: Subscription,
908    ) -> MetaResult<NotificationVersion> {
909        tracing::debug!("create subscription");
910        let _permit = self
911            .creating_streaming_job_permits
912            .semaphore
913            .acquire()
914            .await
915            .unwrap();
916        let _reschedule_job_lock = self.stream_manager.reschedule_lock_read_guard().await;
917        self.metadata_manager
918            .catalog_controller
919            .create_subscription_catalog(&mut subscription)
920            .await?;
921        if let Err(err) = self.stream_manager.create_subscription(&subscription).await {
922            tracing::debug!(error = %err.as_report(), "failed to create subscription");
923            let _ = self
924                .metadata_manager
925                .catalog_controller
926                .try_abort_creating_subscription(subscription.id)
927                .await
928                .inspect_err(|e| {
929                    tracing::error!(
930                        error = %e.as_report(),
931                        "failed to abort create subscription after failure"
932                    );
933                });
934            return Err(err);
935        }
936
937        let version = self
938            .metadata_manager
939            .catalog_controller
940            .notify_create_subscription(subscription.id)
941            .await?;
942        tracing::debug!("finish create subscription");
943        Ok(version)
944    }
945
946    async fn drop_subscription(
947        &self,
948        subscription_id: SubscriptionId,
949        drop_mode: DropMode,
950    ) -> MetaResult<NotificationVersion> {
951        tracing::debug!("preparing drop subscription");
952        let _reschedule_job_lock = self.stream_manager.reschedule_lock_read_guard().await;
953        let subscription = self
954            .metadata_manager
955            .catalog_controller
956            .get_subscription_by_id(subscription_id)
957            .await?;
958        let table_id = subscription.dependent_table_id;
959        let database_id = subscription.database_id;
960        let (_, version) = self
961            .metadata_manager
962            .catalog_controller
963            .drop_object(ObjectType::Subscription, subscription_id, drop_mode)
964            .await?;
965        self.stream_manager
966            .drop_subscription(database_id, subscription_id, table_id)
967            .await;
968        tracing::debug!("finish drop subscription");
969        Ok(version)
970    }
971
972    async fn alter_subscription_retention(
973        &self,
974        subscription_id: SubscriptionId,
975        retention_seconds: u64,
976        definition: String,
977    ) -> MetaResult<NotificationVersion> {
978        tracing::debug!("alter subscription retention");
979        let _reschedule_job_lock = self.stream_manager.reschedule_lock_read_guard().await;
980        let version = self
981            .metadata_manager
982            .catalog_controller
983            .alter_subscription_retention(subscription_id, retention_seconds, definition)
984            .await?;
985        tracing::debug!("finish alter subscription retention");
986        Ok(version)
987    }
988
989    /// Validates the connect properties in the `cdc_table_desc` stored in the `StreamCdcScan` node
990    #[await_tree::instrument]
991    pub(crate) async fn validate_cdc_table(
992        &self,
993        table: &Table,
994        table_fragments: &StreamJobFragments,
995    ) -> MetaResult<()> {
996        let stream_scan_fragment =
997            Itertools::exactly_one(table_fragments.fragments.values().filter(|f| {
998                f.fragment_type_mask.contains(FragmentTypeFlag::StreamScan)
999                    || f.fragment_type_mask
1000                        .contains(FragmentTypeFlag::StreamCdcScan)
1001            }))
1002            .ok()
1003            .with_context(|| {
1004                format!(
1005                    "expect exactly one stream scan fragment, got: {:?}",
1006                    table_fragments.fragments
1007                )
1008            })?;
1009        fn assert_parallelism(
1010            distribution_type: PbFragmentDistributionType,
1011            node_body: &Option<NodeBody>,
1012        ) {
1013            if let Some(NodeBody::StreamCdcScan(node)) = node_body {
1014                if let Some(o) = node.options
1015                    && CdcScanOptions::from_proto(&o).is_parallelized_backfill()
1016                {
1017                    // Use parallel CDC backfill.
1018                } else {
1019                    assert_eq!(
1020                        distribution_type,
1021                        PbFragmentDistributionType::Single,
1022                        "Non-parallelized CDC scan fragment should have Single distribution"
1023                    );
1024                }
1025            }
1026        }
1027        let mut found_cdc_scan = false;
1028        match &stream_scan_fragment.nodes.node_body {
1029            Some(NodeBody::StreamCdcScan(_)) => {
1030                assert_parallelism(
1031                    stream_scan_fragment.distribution_type,
1032                    &stream_scan_fragment.nodes.node_body,
1033                );
1034                if self
1035                    .validate_cdc_table_inner(&stream_scan_fragment.nodes.node_body, table.id)
1036                    .await?
1037                {
1038                    found_cdc_scan = true;
1039                }
1040            }
1041            // When there's generated columns, the cdc scan node is wrapped in a project node
1042            Some(NodeBody::Project(_)) => {
1043                for input in &stream_scan_fragment.nodes.input {
1044                    assert_parallelism(stream_scan_fragment.distribution_type, &input.node_body);
1045                    if self
1046                        .validate_cdc_table_inner(&input.node_body, table.id)
1047                        .await?
1048                    {
1049                        found_cdc_scan = true;
1050                    }
1051                }
1052            }
1053            _ => {
1054                bail!("Unexpected node body for stream cdc scan");
1055            }
1056        };
1057        if !found_cdc_scan {
1058            bail!("No stream cdc scan node found in stream scan fragment");
1059        }
1060        Ok(())
1061    }
1062
1063    async fn validate_cdc_table_inner(
1064        &self,
1065        node_body: &Option<NodeBody>,
1066        table_id: TableId,
1067    ) -> MetaResult<bool> {
1068        if let Some(NodeBody::StreamCdcScan(stream_cdc_scan)) = node_body
1069            && let Some(ref cdc_table_desc) = stream_cdc_scan.cdc_table_desc
1070        {
1071            self.validate_cdc_table_desc(cdc_table_desc).await?;
1072            tracing::debug!(?table_id, "validate cdc table success");
1073            Ok(true)
1074        } else {
1075            Ok(false)
1076        }
1077    }
1078
1079    /// Validates a CDC table descriptor against its upstream table, by creating a throw-away
1080    /// split enumerator: the connector validator checks that the table exists and that the
1081    /// declared columns and primary key match the upstream ones.
1082    pub(crate) async fn validate_cdc_table_desc(
1083        &self,
1084        cdc_table_desc: &PbExternalTableDesc,
1085    ) -> MetaResult<()> {
1086        let options_with_secret = WithOptionsSecResolved::new(
1087            cdc_table_desc.connect_properties.clone(),
1088            cdc_table_desc.secret_refs.clone(),
1089        );
1090
1091        let mut props = ConnectorProperties::extract(options_with_secret, true)?;
1092        props.init_from_pb_cdc_table_desc(cdc_table_desc);
1093
1094        let _enumerator = props
1095            .create_split_enumerator(SourceEnumeratorContext::dummy().into())
1096            .await?;
1097
1098        Ok(())
1099    }
1100
1101    pub async fn validate_table_for_sink(&self, table_id: TableId) -> MetaResult<()> {
1102        let migrated = self
1103            .metadata_manager
1104            .catalog_controller
1105            .has_table_been_migrated(table_id)
1106            .await?;
1107        if !migrated {
1108            Err(anyhow::anyhow!("Creating sink into table is not allowed for unmigrated table {}. Please migrate it first.", table_id).into())
1109        } else {
1110            Ok(())
1111        }
1112    }
1113
1114    /// For [`CreateType::Foreground`], the function will only return after backfilling finishes
1115    /// ([`crate::manager::MetadataManager::wait_streaming_job_finished`]).
1116    #[await_tree::instrument(boxed, "create_streaming_job({streaming_job})")]
1117    pub async fn create_streaming_job(
1118        &self,
1119        mut streaming_job: StreamingJob,
1120        fragment_graph: StreamFragmentGraphProto,
1121        dependencies: HashSet<ObjectId>,
1122        resource_type: streaming_job_resource_type::ResourceType,
1123        if_not_exists: bool,
1124        refresh_interval_sec: Option<u64>,
1125        replace_sink: Option<SinkId>,
1126        since_timestamp_epoch: Option<u64>,
1127    ) -> MetaResult<NotificationVersion> {
1128        let replace_sink_info = if let Some(old_sink_id) = replace_sink {
1129            let StreamingJob::Sink(sink, _) = &streaming_job else {
1130                bail!("replace sink requires a sink job")
1131            };
1132            if sink.target_table.is_some() {
1133                bail_not_implemented!("replace sink into table")
1134            }
1135
1136            Some(old_sink_id)
1137        } else {
1138            if let StreamingJob::Sink(sink, _) = &streaming_job
1139                && let Some(target_table) = sink.target_table
1140            {
1141                self.validate_table_for_sink(target_table).await?;
1142            }
1143            None
1144        };
1145        self.validate_serverless_backfill_enabled(&resource_type)?;
1146        let ctx = StreamContext::from_protobuf(fragment_graph.get_ctx().unwrap());
1147        let adaptive_parallelism_strategy =
1148            (!fragment_graph.adaptive_parallelism_strategy.is_empty()).then(|| {
1149                parse_strategy(&fragment_graph.adaptive_parallelism_strategy)
1150                    .expect("adaptive parallelism strategy should be validated in frontend")
1151            });
1152        let backfill_adaptive_parallelism_strategy = (!fragment_graph
1153            .backfill_adaptive_parallelism_strategy
1154            .is_empty())
1155        .then(|| {
1156            parse_strategy(&fragment_graph.backfill_adaptive_parallelism_strategy)
1157                .expect("backfill adaptive parallelism strategy should be validated in frontend")
1158        });
1159
1160        let streaming_job_model = match self
1161            .metadata_manager
1162            .catalog_controller
1163            .create_job_catalog(
1164                &mut streaming_job,
1165                &ctx,
1166                &fragment_graph.parallelism,
1167                fragment_graph.max_parallelism as _,
1168                dependencies,
1169                resource_type.clone(),
1170                &fragment_graph.backfill_parallelism,
1171                adaptive_parallelism_strategy,
1172                backfill_adaptive_parallelism_strategy,
1173                replace_sink_info.as_ref(),
1174                refresh_interval_sec,
1175            )
1176            .await
1177        {
1178            Ok(model) => model,
1179            Err(meta_err) => {
1180                if !if_not_exists {
1181                    return Err(meta_err);
1182                }
1183                return if let MetaErrorInner::Duplicated(_, _, Some(job_id)) = meta_err.inner() {
1184                    if streaming_job.create_type() == CreateType::Foreground {
1185                        let database_id = streaming_job.database_id();
1186                        self.metadata_manager
1187                            .wait_streaming_job_finished(database_id, *job_id)
1188                            .await
1189                    } else {
1190                        Ok(IGNORED_NOTIFICATION_VERSION)
1191                    }
1192                } else {
1193                    Err(meta_err)
1194                };
1195            }
1196        };
1197        let job_id = streaming_job.id();
1198        if let Some(old_sink_id) = replace_sink_info.as_ref() {
1199            tracing::debug!(
1200                old_sink_id = %old_sink_id,
1201                new_sink_id = %job_id,
1202                definition = streaming_job.definition(),
1203                create_type = streaming_job.create_type().as_str_name(),
1204                "starting replacement sink",
1205            );
1206        } else {
1207            tracing::debug!(
1208                id = %job_id,
1209                definition = streaming_job.definition(),
1210                create_type = streaming_job.create_type().as_str_name(),
1211                job_type = ?streaming_job.job_type(),
1212                "starting streaming job",
1213            );
1214        }
1215        // TODO: acquire permits for recovered background DDLs.
1216        let permit = self
1217            .creating_streaming_job_permits
1218            .semaphore
1219            .clone()
1220            .acquire_owned()
1221            .instrument_await("acquire_creating_streaming_job_permit")
1222            .await
1223            .unwrap();
1224        let reschedule_job_lock = self.stream_manager.reschedule_lock_read_guard().await;
1225
1226        let name = streaming_job.name();
1227        let definition = streaming_job.definition();
1228        let source_id = match &streaming_job {
1229            StreamingJob::Table(Some(src), _, _) | StreamingJob::Source(src) => Some(src.id),
1230            _ => None,
1231        };
1232        let create_result = match self
1233            .generate_streaming_job(
1234                ctx,
1235                streaming_job,
1236                fragment_graph,
1237                resource_type.clone(),
1238                streaming_job_model,
1239                replace_sink_info,
1240                since_timestamp_epoch,
1241            )
1242            .await
1243        {
1244            Ok((stream_job_fragments, ctx)) => {
1245                self.stream_manager
1246                    .create_streaming_job(stream_job_fragments, ctx, permit, reschedule_job_lock)
1247                    .await
1248            }
1249            Err(err) => Err((err, false, None)),
1250        };
1251
1252        match create_result {
1253            Ok(version) => Ok(version),
1254            Err((err, is_cancelled, cancel_notifier)) => {
1255                tracing::error!(id = %job_id, error = %err.as_report(), "failed to create streaming job");
1256                let event = risingwave_pb::meta::event_log::EventCreateStreamJobFail {
1257                    id: job_id,
1258                    name,
1259                    definition,
1260                    error: err.as_report().to_string(),
1261                };
1262                self.env.event_log_manager_ref().add_event_logs(vec![
1263                    risingwave_pb::meta::event_log::Event::CreateStreamJobFail(event),
1264                ]);
1265                let abort_result = self
1266                    .metadata_manager
1267                    .catalog_controller
1268                    .try_abort_creating_streaming_job(job_id, is_cancelled)
1269                    .await?;
1270                let aborted = abort_result.aborted;
1271                self.stream_manager
1272                    .cleanup_aborted_streaming_job(abort_result)
1273                    .await?;
1274                if let Some(cancel_notifier) = cancel_notifier {
1275                    let _ = cancel_notifier.send(true).inspect_err(|err| {
1276                        tracing::warn!("failed to notify cancellation result: {err}")
1277                    });
1278                }
1279                if aborted {
1280                    tracing::warn!(id = %job_id, is_cancelled, "aborted streaming job");
1281                    // FIXME: might also need other cleanup here
1282                    if let Some(source_id) = source_id {
1283                        self.source_manager
1284                            .apply_source_change(SourceChange::DropSource {
1285                                dropped_source_ids: vec![source_id],
1286                            })
1287                            .await;
1288                    }
1289                }
1290                Err(err)
1291            }
1292        }
1293    }
1294
1295    #[await_tree::instrument(boxed)]
1296    async fn generate_streaming_job(
1297        &self,
1298        ctx: StreamContext,
1299        mut streaming_job: StreamingJob,
1300        fragment_graph: StreamFragmentGraphProto,
1301        resource_type: streaming_job_resource_type::ResourceType,
1302        streaming_job_model: streaming_job::Model,
1303        replace_sink: Option<SinkId>,
1304        since_timestamp_epoch: Option<u64>,
1305    ) -> MetaResult<(StreamJobFragmentsToCreate, CreateStreamingJobContext)> {
1306        let mut fragment_graph =
1307            StreamFragmentGraph::new(&self.env, fragment_graph, &streaming_job)?;
1308        streaming_job.set_info_from_graph(&fragment_graph);
1309
1310        let cross_db_upstream_table_ids = fragment_graph
1311            .collect_snapshot_backfill_info()?
1312            .1
1313            .upstream_mv_table_id_to_backfill_epoch
1314            .into_keys();
1315        let cross_db_subscriptions = self
1316            .metadata_manager
1317            .catalog_controller
1318            .create_cross_db_subscriptions(streaming_job.id(), cross_db_upstream_table_ids)
1319            .await?;
1320
1321        // create internal table catalogs and refill table id.
1322        let incomplete_internal_tables = fragment_graph
1323            .incomplete_internal_tables()
1324            .into_values()
1325            .collect_vec();
1326        let table_id_map = self
1327            .metadata_manager
1328            .catalog_controller
1329            .create_internal_table_catalog(&streaming_job, incomplete_internal_tables)
1330            .await?;
1331        fragment_graph.refill_internal_table_ids(table_id_map);
1332
1333        // create fragment and actor catalogs.
1334        tracing::debug!(id = %streaming_job.id(), "building streaming job");
1335        let (ctx, stream_job_fragments) = self
1336            .build_stream_job(
1337                ctx,
1338                streaming_job,
1339                fragment_graph,
1340                resource_type,
1341                streaming_job_model,
1342                since_timestamp_epoch,
1343                cross_db_subscriptions,
1344                replace_sink,
1345            )
1346            .await?;
1347
1348        let streaming_job = &ctx.streaming_job;
1349
1350        match streaming_job {
1351            StreamingJob::Table(None, table, TableJobType::SharedCdcSource) => {
1352                self.validate_cdc_table(table, &stream_job_fragments)
1353                    .await?;
1354            }
1355            StreamingJob::Table(Some(source), ..) => {
1356                // Register the source on the connector node.
1357                self.source_manager.register_source(source).await?;
1358                let connector_name = source
1359                    .get_with_properties()
1360                    .get(UPSTREAM_SOURCE_KEY)
1361                    .cloned();
1362                let attr = source.info.as_ref().map(|source_info| {
1363                    jsonbb::json!({
1364                            "format": source_info.format().as_str_name(),
1365                            "encode": source_info.row_encode().as_str_name(),
1366                    })
1367                });
1368                report_create_object(
1369                    streaming_job.id(),
1370                    "source",
1371                    PbTelemetryDatabaseObject::Source,
1372                    connector_name,
1373                    attr,
1374                );
1375            }
1376            StreamingJob::Sink(sink, _) => {
1377                if sink.auto_refresh_schema_from_table.is_some() {
1378                    check_sink_fragments_support_refresh_schema(&stream_job_fragments.fragments)?;
1379                }
1380                // Validate the sink on the connector node.
1381                validate_sink(sink).await?;
1382                // For Iceberg pk-index sinks, spawn the per-sink commit worker now
1383                // so it's ready to receive epoch reports from the very first
1384                // barrier instead of relying on lazy registration on every
1385                // commit.
1386                if crate::manager::iceberg_pk_index_sink::is_iceberg_pk_index_sink(&sink.properties)
1387                {
1388                    self.iceberg_pk_index_sink_manager
1389                        .register_sink(
1390                            sink.id,
1391                            crate::barrier::to_partial_graph_id(
1392                                sink.database_id,
1393                                Some(sink.id.as_job_id()),
1394                            ),
1395                        )
1396                        .await
1397                        .map_err(|e| anyhow!(e).context("register v3 sink worker"))?;
1398                }
1399                let connector_name = sink.get_properties().get(UPSTREAM_SOURCE_KEY).cloned();
1400                let attr = sink.format_desc.as_ref().map(|sink_info| {
1401                    jsonbb::json!({
1402                        "format": sink_info.format().as_str_name(),
1403                        "encode": sink_info.encode().as_str_name(),
1404                    })
1405                });
1406                report_create_object(
1407                    streaming_job.id(),
1408                    "sink",
1409                    PbTelemetryDatabaseObject::Sink,
1410                    connector_name,
1411                    attr,
1412                );
1413            }
1414            StreamingJob::Source(source) => {
1415                // Register the source on the connector node.
1416                self.source_manager.register_source(source).await?;
1417                let connector_name = source
1418                    .get_with_properties()
1419                    .get(UPSTREAM_SOURCE_KEY)
1420                    .cloned();
1421                let attr = source.info.as_ref().map(|source_info| {
1422                    jsonbb::json!({
1423                            "format": source_info.format().as_str_name(),
1424                            "encode": source_info.row_encode().as_str_name(),
1425                    })
1426                });
1427                report_create_object(
1428                    streaming_job.id(),
1429                    "source",
1430                    PbTelemetryDatabaseObject::Source,
1431                    connector_name,
1432                    attr,
1433                );
1434            }
1435            _ => {}
1436        }
1437
1438        let backfill_orders = ctx.fragment_backfill_ordering.to_meta_model();
1439        self.metadata_manager
1440            .catalog_controller
1441            .prepare_stream_job_fragments(
1442                &stream_job_fragments,
1443                streaming_job,
1444                false,
1445                Some(backfill_orders),
1446            )
1447            .await?;
1448
1449        Ok((stream_job_fragments, ctx))
1450    }
1451
1452    /// `target_replace_info`: when dropping a sink into table, we need to replace the table.
1453    pub async fn drop_object(
1454        &self,
1455        object_type: ObjectType,
1456        object_id: impl Into<ObjectId>,
1457        drop_mode: DropMode,
1458    ) -> MetaResult<NotificationVersion> {
1459        let object_id = object_id.into();
1460        // Fence reschedule and source tick before catalog deletion so post-collect split updates
1461        // cannot race with dropped fragments.
1462        let _reschedule_job_lock = self.stream_manager.reschedule_lock_read_guard().await;
1463        let _source_tick_pause_guard = self.source_manager.pause_tick().await;
1464
1465        let (release_ctx, version) = self
1466            .metadata_manager
1467            .catalog_controller
1468            .drop_object(object_type, object_id, drop_mode)
1469            .await?;
1470
1471        if object_type == ObjectType::Source {
1472            self.env
1473                .notification_manager_ref()
1474                .notify_local_subscribers(LocalNotification::SourceDropped(object_id));
1475        }
1476
1477        let ReleaseContext {
1478            database_id,
1479            removed_streaming_job_ids,
1480            removed_state_table_ids,
1481            removed_source_ids,
1482            removed_secret_ids: secret_ids,
1483            removed_source_fragments,
1484            removed_fragments,
1485            removed_sink_fragment_by_targets,
1486            removed_iceberg_table_sinks,
1487            removed_iceberg_sink_ids,
1488            removed_cross_db_subscriptions,
1489        } = release_ctx;
1490        self.iceberg_pk_index_sink_manager
1491            .retire_sinks(removed_iceberg_sink_ids);
1492
1493        // Notify serving module about deleted fragments so it can clean up serving vnode mappings.
1494        // This is driven by the fragment model deletion (cascade from Object::delete_many),
1495        // decoupled from the barrier-driven streaming mapping notifications.
1496        self.env
1497            .notification_manager_ref()
1498            .notify_serving_fragment_mapping_delete(
1499                removed_fragments.iter().map(|id| *id as _).collect(),
1500            );
1501
1502        self.stream_manager
1503            .drop_streaming_jobs(
1504                database_id,
1505                removed_streaming_job_ids,
1506                removed_state_table_ids,
1507                removed_sink_fragment_by_targets
1508                    .into_iter()
1509                    .map(|(target, sinks)| {
1510                        (target as _, sinks.into_iter().map(|id| id as _).collect())
1511                    })
1512                    .collect(),
1513            )
1514            .await;
1515
1516        // Cross-database subscriptions keep the upstream log store alive for the downstream job,
1517        // so remove them only after the downstream drop barrier has completed.
1518        for subscription in removed_cross_db_subscriptions {
1519            self.stream_manager
1520                .drop_cross_db_subscription(&subscription)
1521                .await;
1522        }
1523
1524        // clean up sources after dropping streaming jobs.
1525        // Otherwise, e.g., Kafka consumer groups might be recreated after deleted.
1526        self.source_manager
1527            .apply_source_change(SourceChange::DropSource {
1528                dropped_source_ids: removed_source_ids.into_iter().map(|id| id as _).collect(),
1529            })
1530            .await;
1531
1532        // unregister fragments and actors from source manager.
1533        // FIXME: need also unregister source backfill fragments.
1534        let dropped_source_fragments = removed_source_fragments;
1535        self.source_manager
1536            .apply_source_change(SourceChange::DropMv {
1537                dropped_source_fragments,
1538            })
1539            .await;
1540
1541        // clean up iceberg table sinks
1542        for sink in removed_iceberg_table_sinks {
1543            let sink_param = SinkParam::try_from_sink_catalog(sink.into())
1544                .expect("Iceberg sink should be valid");
1545            let iceberg_sink =
1546                IcebergSink::try_from(sink_param).expect("Iceberg sink should be valid");
1547            if let Ok(iceberg_catalog) = iceberg_sink.config.create_catalog().await {
1548                let table_identifier = iceberg_sink.config.full_table_name().unwrap();
1549                tracing::info!(
1550                    "dropping iceberg table {} for dropped sink",
1551                    table_identifier
1552                );
1553
1554                let _ = iceberg_catalog
1555                    .drop_table(&table_identifier)
1556                    .await
1557                    .inspect_err(|err| {
1558                        tracing::error!(
1559                            "failed to drop iceberg table {} during cleanup: {}",
1560                            table_identifier,
1561                            err.as_report()
1562                        );
1563                    });
1564            }
1565        }
1566
1567        // remove secrets.
1568        for secret in secret_ids {
1569            LocalSecretManager::global().remove_secret(secret);
1570        }
1571        Ok(version)
1572    }
1573
1574    /// This is used for `ALTER TABLE ADD/DROP COLUMN` / `ALTER SOURCE ADD COLUMN`.
1575    #[await_tree::instrument(boxed, "replace_streaming_job({streaming_job})")]
1576    pub async fn replace_job(
1577        &self,
1578        mut streaming_job: StreamingJob,
1579        fragment_graph: StreamFragmentGraphProto,
1580    ) -> MetaResult<NotificationVersion> {
1581        match &streaming_job {
1582            StreamingJob::Table(..)
1583            | StreamingJob::Source(..)
1584            | StreamingJob::MaterializedView(..) => {}
1585            StreamingJob::Sink(..) | StreamingJob::Index(..) => {
1586                bail_not_implemented!("schema change for {}", streaming_job.job_type_str())
1587            }
1588        }
1589
1590        let job_id = streaming_job.id();
1591
1592        let _reschedule_job_lock = self.stream_manager.reschedule_lock_write_guard().await;
1593        if let StreamingJob::Table(_, table, _) = &streaming_job
1594            && self
1595                .metadata_manager
1596                .catalog_controller
1597                .get_refresh_job_state(table.id)
1598                .await?
1599                .is_some_and(|state| state != RefreshState::Idle)
1600        {
1601            bail!(
1602                "Cannot alter table {} because it is being refreshed",
1603                table.name
1604            );
1605        }
1606        let ctx = StreamContext::from_protobuf(fragment_graph.get_ctx().unwrap());
1607
1608        // Ensure the max parallelism unchanged before replacing table.
1609        let original_max_parallelism = self
1610            .metadata_manager
1611            .get_job_max_parallelism(streaming_job.id())
1612            .await?;
1613        let fragment_graph = PbStreamFragmentGraph {
1614            max_parallelism: original_max_parallelism as _,
1615            ..fragment_graph
1616        };
1617
1618        // 1. build fragment graph.
1619        let fragment_graph = StreamFragmentGraph::new(&self.env, fragment_graph, &streaming_job)?;
1620        streaming_job.set_info_from_graph(&fragment_graph);
1621
1622        // make it immutable
1623        let streaming_job = streaming_job;
1624
1625        let auto_refresh_schema_sinks = if let StreamingJob::Table(_, table, _) = &streaming_job {
1626            let auto_refresh_schema_sinks = self
1627                .metadata_manager
1628                .catalog_controller
1629                .get_sink_auto_refresh_schema_from(table.id)
1630                .await?;
1631            if !auto_refresh_schema_sinks.is_empty() {
1632                let original_table_columns = self
1633                    .metadata_manager
1634                    .catalog_controller
1635                    .get_table_columns(table.id)
1636                    .await?;
1637                // compare column id to find newly added and removed columns
1638                let original_table_column_ids: HashSet<_> = original_table_columns
1639                    .iter()
1640                    .map(|col| col.column_id())
1641                    .collect();
1642                let new_table_column_ids: HashSet<_> = table
1643                    .columns
1644                    .iter()
1645                    .map(|col| ColumnId::new(col.column_desc.as_ref().unwrap().column_id as _))
1646                    .collect();
1647                let newly_added_columns = table
1648                    .columns
1649                    .iter()
1650                    .filter(|col| {
1651                        !original_table_column_ids.contains(&ColumnId::new(
1652                            col.column_desc.as_ref().unwrap().column_id as _,
1653                        ))
1654                    })
1655                    .map(|col| ColumnCatalog::from(col.clone()))
1656                    .collect_vec();
1657                let removed_columns = original_table_columns
1658                    .iter()
1659                    .filter(|col| !new_table_column_ids.contains(&col.column_id()))
1660                    .cloned()
1661                    .collect_vec();
1662                // Fail before any fragment rewrite or catalog persistence so a rejected ALTER
1663                // leaves no partial state.
1664                if let Some(variant_column) = first_variant_column(&newly_added_columns) {
1665                    let sink_names = auto_refresh_schema_sinks
1666                        .iter()
1667                        .map(|sink| format!("`{}`", sink.name))
1668                        .join(", ");
1669                    return Err(MetaError::invalid_parameter(format!(
1670                        "cannot add VARIANT column `{}` because sink(s) {} with auto schema refresh do not support VARIANT",
1671                        variant_column.name_with_hidden(),
1672                        sink_names,
1673                    )));
1674                }
1675                let mut sinks = Vec::with_capacity(auto_refresh_schema_sinks.len());
1676                for sink in auto_refresh_schema_sinks {
1677                    let sink_job_fragments = self
1678                        .metadata_manager
1679                        .get_job_fragments_by_id(sink.id.as_job_id())
1680                        .await?;
1681                    if sink_job_fragments.fragments.len() != 1 {
1682                        return Err(anyhow!(
1683                            "auto schema refresh sink must have only one fragment, but got {}",
1684                            sink_job_fragments.fragments.len()
1685                        )
1686                        .into());
1687                    }
1688                    let sink_ctx = sink_job_fragments.ctx;
1689                    let original_sink_fragment =
1690                        sink_job_fragments.fragments.into_values().next().unwrap();
1691                    let (new_sink_fragment, new_schema, new_log_store_table) =
1692                        rewrite_refresh_schema_sink_fragment(
1693                            &original_sink_fragment,
1694                            &sink,
1695                            &newly_added_columns,
1696                            &removed_columns,
1697                            table,
1698                            fragment_graph.table_fragment_id(),
1699                            self.env.id_gen_manager(),
1700                        )?;
1701
1702                    let streaming_job = StreamingJob::Sink(sink, None);
1703
1704                    let tmp_sink_model = self
1705                        .metadata_manager
1706                        .catalog_controller
1707                        .create_job_catalog_for_replace(&streaming_job, None, None, None)
1708                        .await?;
1709                    let tmp_sink_id = tmp_sink_model.job_id.as_sink_id();
1710                    let StreamingJob::Sink(sink, _) = streaming_job else {
1711                        unreachable!()
1712                    };
1713
1714                    sinks.push(AutoRefreshSchemaSinkContext {
1715                        tmp_sink_id,
1716                        original_sink: sink,
1717                        original_fragment: original_sink_fragment,
1718                        new_schema,
1719                        newly_add_fields: newly_added_columns
1720                            .iter()
1721                            .map(|col| Field::from(&col.column_desc))
1722                            .collect(),
1723                        removed_column_names: removed_columns
1724                            .iter()
1725                            .map(|col| col.name.clone())
1726                            .collect(),
1727                        new_fragment: new_sink_fragment,
1728                        new_log_store_table: new_log_store_table.map(Box::new),
1729                        ctx: sink_ctx,
1730                    });
1731                }
1732                Some(sinks)
1733            } else {
1734                None
1735            }
1736        } else {
1737            None
1738        };
1739
1740        let streaming_job_model = self
1741            .metadata_manager
1742            .catalog_controller
1743            .create_job_catalog_for_replace(
1744                &streaming_job,
1745                Some(&ctx),
1746                fragment_graph.specified_parallelism().as_ref(),
1747                Some(fragment_graph.max_parallelism()),
1748            )
1749            .await?;
1750        let tmp_id = streaming_job_model.job_id;
1751
1752        let tmp_sink_ids = auto_refresh_schema_sinks.as_ref().map(|sinks| {
1753            sinks
1754                .iter()
1755                .map(|sink| sink.tmp_sink_id.as_object_id())
1756                .collect_vec()
1757        });
1758
1759        tracing::debug!(id = %job_id, "building replace streaming job");
1760        let mut updated_sink_catalogs = vec![];
1761
1762        let mut drop_table_connector_ctx = None;
1763        let result: MetaResult<_> = try {
1764            let (mut ctx, mut stream_job_fragments) = self
1765                .build_replace_job(
1766                    ctx,
1767                    &streaming_job,
1768                    fragment_graph,
1769                    tmp_id,
1770                    auto_refresh_schema_sinks,
1771                    streaming_job_model,
1772                )
1773                .await?;
1774            drop_table_connector_ctx = ctx.drop_table_connector_ctx.clone();
1775            let auto_refresh_schema_sink_finish_ctx =
1776                ctx.auto_refresh_schema_sinks.as_ref().map(|sinks| {
1777                    sinks
1778                        .iter()
1779                        .map(|sink| FinishAutoRefreshSchemaSinkContext {
1780                            tmp_sink_id: sink.tmp_sink_id,
1781                            original_sink_id: sink.original_sink.id,
1782                            columns: sink.new_schema.clone(),
1783                            new_log_store_table: sink.new_log_store_table.clone(),
1784                        })
1785                        .collect()
1786                });
1787
1788            // Handle table that has incoming sinks.
1789            if let StreamingJob::Table(_, table, ..) = &streaming_job {
1790                let union_fragment = stream_job_fragments.inner.union_fragment_for_table();
1791                let upstream_infos = self
1792                    .metadata_manager
1793                    .catalog_controller
1794                    .get_all_upstream_sink_infos(table, union_fragment.fragment_id as _)
1795                    .await?;
1796                refill_upstream_sink_union_in_table(&mut union_fragment.nodes, &upstream_infos);
1797
1798                for upstream_info in &upstream_infos {
1799                    let upstream_fragment_id = upstream_info.sink_fragment_id;
1800                    ctx.upstream_fragment_downstreams
1801                        .entry(upstream_fragment_id)
1802                        .or_default()
1803                        .push(upstream_info.new_sink_downstream.clone());
1804                    if upstream_info.sink_original_target_columns.is_empty() {
1805                        updated_sink_catalogs.push(upstream_info.sink_id);
1806                    }
1807                }
1808            }
1809
1810            let replace_upstream = ctx.replace_upstream.clone();
1811
1812            if let Some(sinks) = &ctx.auto_refresh_schema_sinks {
1813                let empty_downstreams = FragmentDownstreamRelation::default();
1814                for sink in sinks {
1815                    self.metadata_manager
1816                        .catalog_controller
1817                        .prepare_streaming_job(
1818                            sink.tmp_sink_id.as_job_id(),
1819                            || [&sink.new_fragment].into_iter(),
1820                            &empty_downstreams,
1821                            true,
1822                            None,
1823                            None,
1824                        )
1825                        .await?;
1826                }
1827            }
1828
1829            self.metadata_manager
1830                .catalog_controller
1831                .prepare_stream_job_fragments(&stream_job_fragments, &streaming_job, true, None)
1832                .await?;
1833
1834            self.stream_manager
1835                .replace_stream_job(stream_job_fragments, ctx)
1836                .await?;
1837            (replace_upstream, auto_refresh_schema_sink_finish_ctx)
1838        };
1839
1840        match result {
1841            Ok((replace_upstream, auto_refresh_schema_sink_finish_ctx)) => {
1842                let version = self
1843                    .metadata_manager
1844                    .catalog_controller
1845                    .finish_replace_streaming_job(
1846                        tmp_id,
1847                        streaming_job,
1848                        replace_upstream,
1849                        SinkIntoTableContext {
1850                            updated_sink_catalogs,
1851                        },
1852                        drop_table_connector_ctx.as_ref(),
1853                        auto_refresh_schema_sink_finish_ctx,
1854                    )
1855                    .await?;
1856                if let Some(drop_table_connector_ctx) = &drop_table_connector_ctx {
1857                    self.source_manager
1858                        .apply_source_change(SourceChange::DropSource {
1859                            dropped_source_ids: vec![drop_table_connector_ctx.to_remove_source_id],
1860                        })
1861                        .await;
1862                }
1863                Ok(version)
1864            }
1865            Err(err) => {
1866                tracing::error!(id = %job_id, error = ?err.as_report(), "failed to replace job");
1867                let _ = self.metadata_manager
1868                    .catalog_controller
1869                    .try_abort_replacing_streaming_job(tmp_id, tmp_sink_ids)
1870                    .await.inspect_err(|err| {
1871                    tracing::error!(id = %job_id, error = ?err.as_report(), "failed to abort replacing job");
1872                });
1873                Err(err)
1874            }
1875        }
1876    }
1877
1878    #[await_tree::instrument(boxed, "drop_streaming_job{}({job_id})", if let DropMode::Cascade = drop_mode { "_cascade" } else { "" }
1879    )]
1880    async fn drop_streaming_job(
1881        &self,
1882        job_id: StreamingJobId,
1883        drop_mode: DropMode,
1884    ) -> MetaResult<NotificationVersion> {
1885        let (object_id, object_type) = match job_id {
1886            StreamingJobId::MaterializedView(id) => (id.as_object_id(), ObjectType::Table),
1887            StreamingJobId::Sink(id) => (id.as_object_id(), ObjectType::Sink),
1888            StreamingJobId::Table(_, id) => (id.as_object_id(), ObjectType::Table),
1889            StreamingJobId::Index(idx) => (idx.as_object_id(), ObjectType::Index),
1890        };
1891
1892        let job_status = self
1893            .metadata_manager
1894            .catalog_controller
1895            .get_streaming_job_status(job_id.id())
1896            .await?;
1897        let version = match job_status {
1898            JobStatus::Initial => {
1899                let abort_result = self
1900                    .metadata_manager
1901                    .catalog_controller
1902                    .try_abort_creating_streaming_job(job_id.id(), true)
1903                    .await?;
1904                self.stream_manager
1905                    .cleanup_aborted_streaming_job(abort_result)
1906                    .await?;
1907                IGNORED_NOTIFICATION_VERSION
1908            }
1909            JobStatus::Creating => {
1910                self.stream_manager
1911                    .cancel_streaming_jobs(vec![job_id.id()])
1912                    .await?;
1913                IGNORED_NOTIFICATION_VERSION
1914            }
1915            JobStatus::Created => self.drop_object(object_type, object_id, drop_mode).await?,
1916        };
1917
1918        Ok(version)
1919    }
1920
1921    /// Builds the actor graph:
1922    /// - Add the upstream fragments to the fragment graph
1923    /// - Schedule the fragments based on their distribution
1924    /// - Expand each fragment into one or several actors
1925    /// - Construct the fragment level backfill order control.
1926    #[await_tree::instrument]
1927    pub(crate) async fn build_stream_job(
1928        &self,
1929        stream_ctx: StreamContext,
1930        mut stream_job: StreamingJob,
1931        fragment_graph: StreamFragmentGraph,
1932        resource_type: streaming_job_resource_type::ResourceType,
1933        streaming_job_model: streaming_job::Model,
1934        since_timestamp_epoch: Option<u64>,
1935        cross_db_subscriptions: Vec<CrossDbSubscriptionInfo>,
1936        replace_sink: Option<SinkId>,
1937    ) -> MetaResult<(CreateStreamingJobContext, StreamJobFragmentsToCreate)> {
1938        let id = stream_job.id();
1939        let max_parallelism = NonZeroUsize::new(fragment_graph.max_parallelism()).unwrap();
1940        Self::validate_specified_parallelism(
1941            fragment_graph.specified_parallelism(),
1942            fragment_graph.specified_backfill_parallelism(),
1943            max_parallelism,
1944        )?;
1945
1946        // 1. Fragment Level ordering graph
1947        let fragment_backfill_ordering = fragment_graph.create_fragment_backfill_ordering();
1948
1949        // 2. Resolve the upstream fragments, extend the fragment graph to a complete graph that
1950        // contains all information needed for building the actor graph.
1951
1952        let (snapshot_backfill_info, cross_db_snapshot_backfill_info) =
1953            fragment_graph.collect_snapshot_backfill_info()?;
1954        assert!(
1955            snapshot_backfill_info
1956                .iter()
1957                .chain([&cross_db_snapshot_backfill_info])
1958                .flat_map(|info| info.upstream_mv_table_id_to_backfill_epoch.values())
1959                .all(|backfill_epoch| backfill_epoch.is_none()),
1960            "should not set backfill epoch when initially build the job: {:?} {:?}",
1961            snapshot_backfill_info,
1962            cross_db_snapshot_backfill_info
1963        );
1964
1965        let locality_fragment_state_table_mapping =
1966            fragment_graph.find_locality_provider_fragment_state_table_mapping();
1967
1968        let upstream_table_ids = fragment_graph
1969            .dependent_table_ids()
1970            .iter()
1971            .filter(|id| {
1972                !cross_db_snapshot_backfill_info
1973                    .upstream_mv_table_id_to_backfill_epoch
1974                    .contains_key(*id)
1975            })
1976            .cloned()
1977            .collect();
1978
1979        let upstream_root_fragments = self
1980            .metadata_manager
1981            .get_upstream_root_fragments(&upstream_table_ids)
1982            .await?;
1983
1984        if snapshot_backfill_info.is_some() {
1985            match stream_job {
1986                StreamingJob::MaterializedView(_)
1987                | StreamingJob::Sink(..)
1988                | StreamingJob::Index(_, _) => {}
1989                StreamingJob::Table(_, _, _) | StreamingJob::Source(_) => {
1990                    return Err(
1991                        anyhow!("snapshot_backfill not enabled for table and source").into(),
1992                    );
1993                }
1994            }
1995        }
1996
1997        let complete_graph = CompleteStreamFragmentGraph::with_upstreams(
1998            fragment_graph,
1999            FragmentGraphUpstreamContext {
2000                upstream_root_fragments,
2001            },
2002            (&stream_job).into(),
2003        )?;
2004        let database_resource_group = self
2005            .metadata_manager
2006            .get_database_resource_group(stream_job.database_id())
2007            .await?;
2008        let is_serverless_backfill = matches!(
2009            &resource_type,
2010            streaming_job_resource_type::ResourceType::ServerlessBackfill(true)
2011        );
2012
2013        // 3. Build the actor graph.
2014        let actor_graph_builder = ActorGraphBuilder::new(complete_graph)?;
2015
2016        let ActorGraphBuildResult {
2017            graph,
2018            downstream_fragment_relations,
2019            upstream_fragment_downstreams,
2020            replace_upstream,
2021        } = actor_graph_builder.generate_graph()?;
2022        assert!(replace_upstream.is_empty());
2023
2024        // 4. Build the table fragments structure that will be persisted in the stream manager,
2025        // and the context that contains all information needed for building the
2026        // actors on the compute nodes.
2027
2028        let stream_job_fragments =
2029            StreamJobFragments::new(id, graph, stream_ctx.clone(), max_parallelism.get());
2030
2031        if let Some(mview_fragment) = stream_job_fragments.mview_fragment() {
2032            stream_job.set_table_vnode_count(mview_fragment.vnode_count());
2033        }
2034
2035        let new_upstream_sink = if let StreamingJob::Sink(sink, _) = &stream_job
2036            && let Ok(table_id) = sink.get_target_table()
2037        {
2038            let tables = self
2039                .metadata_manager
2040                .get_table_catalog_by_ids(&[*table_id])
2041                .await?;
2042            let target_table = tables
2043                .first()
2044                .ok_or_else(|| MetaError::catalog_id_not_found("table", *table_id))?;
2045            let sink_fragment = stream_job_fragments
2046                .sink_fragment()
2047                .ok_or_else(|| anyhow::anyhow!("sink fragment not found for sink {}", sink.id))?;
2048            let mview_fragment_id = self
2049                .metadata_manager
2050                .catalog_controller
2051                .get_mview_fragment_by_id(table_id.as_job_id())
2052                .await?;
2053            let upstream_sink_info = build_upstream_sink_info(
2054                sink.id,
2055                sink.original_target_columns.clone(),
2056                sink_fragment.fragment_id as _,
2057                target_table,
2058                mview_fragment_id,
2059            )?;
2060            Some(upstream_sink_info)
2061        } else {
2062            None
2063        };
2064
2065        let mut cdc_table_snapshot_splits = None;
2066        if let StreamingJob::Table(None, table, TableJobType::SharedCdcSource) = &stream_job
2067            && let Some((_, stream_cdc_scan)) =
2068                parallel_cdc_table_backfill_fragment(stream_job_fragments.fragments.values())
2069        {
2070            {
2071                // Create parallel splits for a CDC table. The resulted split assignments are persisted and immutable.
2072                let splits = try_init_parallel_cdc_table_snapshot_splits(
2073                    table.id,
2074                    stream_cdc_scan.cdc_table_desc.as_ref().unwrap(),
2075                    self.env.meta_store_ref(),
2076                    stream_cdc_scan.options.as_ref().unwrap(),
2077                    self.env.opts.cdc_table_split_init_insert_batch_size,
2078                    self.env.opts.cdc_table_split_init_sleep_interval_splits,
2079                    self.env.opts.cdc_table_split_init_sleep_duration_millis,
2080                )
2081                .await?;
2082                cdc_table_snapshot_splits = Some(splits);
2083            }
2084        }
2085
2086        let ctx = CreateStreamingJobContext {
2087            upstream_fragment_downstreams,
2088            database_resource_group,
2089            definition: stream_job.definition(),
2090            create_type: stream_job.create_type(),
2091            job_type: (&stream_job).into(),
2092            streaming_job: stream_job,
2093            new_upstream_sink,
2094            option: CreateStreamingJobOption {},
2095            snapshot_backfill_info,
2096            cross_db_snapshot_backfill_info,
2097            cross_db_subscriptions,
2098            fragment_backfill_ordering,
2099            locality_fragment_state_table_mapping,
2100            cdc_table_snapshot_splits,
2101            is_serverless_backfill,
2102            resource_type,
2103            streaming_job_model: streaming_job_model.clone(),
2104            replace_sink,
2105            refresh_interval_sec: streaming_job_model.refresh_interval_sec.map(|s| s as u64),
2106            since_timestamp_epoch,
2107        };
2108
2109        Ok((
2110            ctx,
2111            StreamJobFragmentsToCreate {
2112                inner: stream_job_fragments,
2113                downstreams: downstream_fragment_relations,
2114            },
2115        ))
2116    }
2117
2118    /// `build_replace_table` builds a job replacement and returns the context and new job
2119    /// fragments.
2120    ///
2121    /// Note that we use a dummy ID for the new job fragments and replace it with the real one after
2122    /// replacement is finished.
2123    pub(crate) async fn build_replace_job(
2124        &self,
2125        stream_ctx: StreamContext,
2126        stream_job: &StreamingJob,
2127        mut fragment_graph: StreamFragmentGraph,
2128        tmp_job_id: JobId,
2129        auto_refresh_schema_sinks: Option<Vec<AutoRefreshSchemaSinkContext>>,
2130        streaming_job_model: streaming_job::Model,
2131    ) -> MetaResult<(ReplaceStreamJobContext, StreamJobFragmentsToCreate)> {
2132        match &stream_job {
2133            StreamingJob::Table(..)
2134            | StreamingJob::Source(..)
2135            | StreamingJob::MaterializedView(..) => {}
2136            StreamingJob::Sink(..) | StreamingJob::Index(..) => {
2137                bail_not_implemented!("schema change for {}", stream_job.job_type_str())
2138            }
2139        }
2140
2141        let id = stream_job.id();
2142
2143        // check if performing drop table connector
2144        let mut drop_table_associated_source_id = None;
2145        if let StreamingJob::Table(None, _, _) = &stream_job {
2146            drop_table_associated_source_id = self
2147                .metadata_manager
2148                .get_table_associated_source_id(id.as_mv_table_id())
2149                .await?;
2150        }
2151
2152        let old_fragments = self.metadata_manager.get_job_fragments_by_id(id).await?;
2153        let old_internal_table_ids = old_fragments.internal_table_ids();
2154
2155        // handle drop table's associated source
2156        let mut drop_table_connector_ctx = None;
2157        if let Some(to_remove_source_id) = drop_table_associated_source_id {
2158            let old_internal_tables = self
2159                .metadata_manager
2160                .get_table_catalog_by_ids(&old_internal_table_ids)
2161                .await?;
2162            let to_remove_state_table_ids = fragment_graph
2163                .fit_internal_tables_for_drop_connector(&old_fragments, old_internal_tables)?;
2164
2165            drop_table_connector_ctx = Some(DropTableConnectorContext {
2166                // we do not remove the original table catalog as it's still needed for the streaming job
2167                // just need to remove the refs to the state tables of the connector
2168                to_change_streaming_job_id: id,
2169                to_remove_state_table_ids,
2170                to_remove_source_id,
2171            });
2172        } else if stream_job.is_materialized_view() {
2173            // If it's ALTER MV, use `state::match` to match the internal tables, which is more complicated
2174            // but more robust.
2175            let old_fragments_upstreams = self
2176                .metadata_manager
2177                .catalog_controller
2178                .upstream_fragments(old_fragments.fragment_ids())
2179                .await?;
2180
2181            let old_state_graph =
2182                state_match::Graph::from_existing(&old_fragments, &old_fragments_upstreams);
2183            let new_state_graph = state_match::Graph::from_building(&fragment_graph);
2184            let result = state_match::match_graph(&new_state_graph, &old_state_graph)
2185                .context("incompatible altering on the streaming job states")?;
2186
2187            fragment_graph.fit_internal_table_ids_with_mapping(result.table_matches);
2188            fragment_graph.fit_snapshot_backfill_epochs(result.snapshot_backfill_epochs);
2189        } else {
2190            // If it's ALTER TABLE or SOURCE, use a trivial table id matching algorithm to keep the original behavior.
2191            // TODO(alter-mv): this is actually a special case of ALTER MV, can we merge the two branches?
2192            let old_internal_tables = self
2193                .metadata_manager
2194                .get_table_catalog_by_ids(&old_internal_table_ids)
2195                .await?;
2196            fragment_graph.fit_internal_tables_trivial(old_internal_tables)?;
2197        }
2198
2199        // 1. Resolve the edges to the downstream fragments, extend the fragment graph to a complete
2200        // graph that contains all information needed for building the actor graph.
2201        let original_root_fragment = old_fragments
2202            .root_fragment()
2203            .expect("root fragment not found");
2204
2205        let job_type = StreamingJobType::from(stream_job);
2206
2207        // Extract the downstream fragments from the fragment graph.
2208        let mut downstream_fragments = self.metadata_manager.get_downstream_fragments(id).await?;
2209
2210        if let Some(auto_refresh_schema_sinks) = &auto_refresh_schema_sinks {
2211            let mut remaining_fragment: HashSet<_> = auto_refresh_schema_sinks
2212                .iter()
2213                .map(|sink| sink.original_fragment.fragment_id)
2214                .collect();
2215            for (_, downstream_fragment) in &mut downstream_fragments {
2216                if let Some(sink) = auto_refresh_schema_sinks.iter().find(|sink| {
2217                    sink.original_fragment.fragment_id == downstream_fragment.fragment_id
2218                }) {
2219                    assert!(remaining_fragment.remove(&downstream_fragment.fragment_id));
2220                    // Actor locations will be resolved inside barrier worker during rendering.
2221                    // For now, just replace fragment info and nodes.
2222                    *downstream_fragment = sink.new_fragment.clone();
2223                }
2224            }
2225            assert!(remaining_fragment.is_empty());
2226        }
2227
2228        // build complete graph based on the table job type
2229        let complete_graph = match &job_type {
2230            StreamingJobType::Table(TableJobType::General) | StreamingJobType::Source => {
2231                CompleteStreamFragmentGraph::with_downstreams(
2232                    fragment_graph,
2233                    FragmentGraphDownstreamContext {
2234                        original_root_fragment_id: original_root_fragment.fragment_id,
2235                        downstream_fragments,
2236                    },
2237                    job_type,
2238                )?
2239            }
2240            StreamingJobType::Table(TableJobType::SharedCdcSource)
2241            | StreamingJobType::MaterializedView => {
2242                // CDC tables or materialized views can have upstream jobs as well.
2243                let upstream_root_fragments = self
2244                    .metadata_manager
2245                    .get_upstream_root_fragments(fragment_graph.dependent_table_ids())
2246                    .await?;
2247
2248                CompleteStreamFragmentGraph::with_upstreams_and_downstreams(
2249                    fragment_graph,
2250                    FragmentGraphUpstreamContext {
2251                        upstream_root_fragments,
2252                    },
2253                    FragmentGraphDownstreamContext {
2254                        original_root_fragment_id: original_root_fragment.fragment_id,
2255                        downstream_fragments,
2256                    },
2257                    job_type,
2258                )?
2259            }
2260            _ => unreachable!(),
2261        };
2262
2263        let resource_group = self
2264            .metadata_manager
2265            .get_database_resource_group(stream_job.database_id())
2266            .await?;
2267
2268        let actor_graph_builder = ActorGraphBuilder::new(complete_graph)?;
2269
2270        let ActorGraphBuildResult {
2271            graph,
2272            downstream_fragment_relations,
2273            upstream_fragment_downstreams,
2274            mut replace_upstream,
2275        } = actor_graph_builder.generate_graph()?;
2276
2277        // general table & source does not have upstream job, so the dispatchers should be empty
2278        if matches!(
2279            job_type,
2280            StreamingJobType::Source | StreamingJobType::Table(TableJobType::General)
2281        ) {
2282            assert!(upstream_fragment_downstreams.is_empty());
2283        }
2284
2285        // 3. Build the table fragments structure that will be persisted in the stream manager, and
2286        // the context that contains all information needed for building the actors on the compute
2287        // nodes.
2288        let stream_job_fragments =
2289            StreamJobFragments::new(tmp_job_id, graph, stream_ctx, old_fragments.max_parallelism);
2290
2291        if let Some(sinks) = &auto_refresh_schema_sinks {
2292            for sink in sinks {
2293                replace_upstream
2294                    .remove(&sink.new_fragment.fragment_id)
2295                    .expect("should exist");
2296            }
2297        }
2298
2299        // Note: no need to set `vnode_count` as it's already set by the frontend.
2300        // See `get_replace_table_plan`.
2301
2302        let ctx = ReplaceStreamJobContext {
2303            old_fragments,
2304            replace_upstream,
2305            upstream_fragment_downstreams,
2306            streaming_job: stream_job.clone(),
2307            database_resource_group: resource_group,
2308            tmp_id: tmp_job_id,
2309            drop_table_connector_ctx,
2310            auto_refresh_schema_sinks,
2311            streaming_job_model,
2312        };
2313
2314        Ok((
2315            ctx,
2316            StreamJobFragmentsToCreate {
2317                inner: stream_job_fragments,
2318                downstreams: downstream_fragment_relations,
2319            },
2320        ))
2321    }
2322
2323    async fn alter_name(
2324        &self,
2325        relation: alter_name_request::Object,
2326        new_name: &str,
2327    ) -> MetaResult<NotificationVersion> {
2328        let (obj_type, id): (ObjectType, ObjectId) = match relation {
2329            alter_name_request::Object::TableId(id) => (ObjectType::Table, id.into()),
2330            alter_name_request::Object::ViewId(id) => (ObjectType::View, id.into()),
2331            alter_name_request::Object::IndexId(id) => (ObjectType::Index, id.into()),
2332            alter_name_request::Object::SinkId(id) => (ObjectType::Sink, id.into()),
2333            alter_name_request::Object::SourceId(id) => (ObjectType::Source, id.into()),
2334            alter_name_request::Object::SchemaId(id) => (ObjectType::Schema, id.into()),
2335            alter_name_request::Object::DatabaseId(id) => (ObjectType::Database, id.into()),
2336            alter_name_request::Object::SubscriptionId(id) => (ObjectType::Subscription, id.into()),
2337        };
2338        self.metadata_manager
2339            .catalog_controller
2340            .alter_name(obj_type, id, new_name)
2341            .await
2342    }
2343
2344    async fn alter_swap_rename(
2345        &self,
2346        object: alter_swap_rename_request::Object,
2347    ) -> MetaResult<NotificationVersion> {
2348        let (obj_type, src_id, dst_id) = match object {
2349            alter_swap_rename_request::Object::Schema(_) => unimplemented!("schema swap"),
2350            alter_swap_rename_request::Object::Table(objs) => {
2351                let (src_id, dst_id) = (objs.src_object_id, objs.dst_object_id);
2352                (ObjectType::Table, src_id, dst_id)
2353            }
2354            alter_swap_rename_request::Object::View(objs) => {
2355                let (src_id, dst_id) = (objs.src_object_id, objs.dst_object_id);
2356                (ObjectType::View, src_id, dst_id)
2357            }
2358            alter_swap_rename_request::Object::Source(objs) => {
2359                let (src_id, dst_id) = (objs.src_object_id, objs.dst_object_id);
2360                (ObjectType::Source, src_id, dst_id)
2361            }
2362            alter_swap_rename_request::Object::Sink(objs) => {
2363                let (src_id, dst_id) = (objs.src_object_id, objs.dst_object_id);
2364                (ObjectType::Sink, src_id, dst_id)
2365            }
2366            alter_swap_rename_request::Object::Subscription(objs) => {
2367                let (src_id, dst_id) = (objs.src_object_id, objs.dst_object_id);
2368                (ObjectType::Subscription, src_id, dst_id)
2369            }
2370        };
2371
2372        self.metadata_manager
2373            .catalog_controller
2374            .alter_swap_rename(obj_type, src_id, dst_id)
2375            .await
2376    }
2377
2378    async fn alter_owner(
2379        &self,
2380        object: Object,
2381        owner_id: UserId,
2382    ) -> MetaResult<NotificationVersion> {
2383        let (obj_type, id): (ObjectType, ObjectId) = match object {
2384            Object::TableId(id) => (ObjectType::Table, id.into()),
2385            Object::ViewId(id) => (ObjectType::View, id.into()),
2386            Object::SourceId(id) => (ObjectType::Source, id.into()),
2387            Object::SinkId(id) => (ObjectType::Sink, id.into()),
2388            Object::SchemaId(id) => (ObjectType::Schema, id.into()),
2389            Object::DatabaseId(id) => (ObjectType::Database, id.into()),
2390            Object::SubscriptionId(id) => (ObjectType::Subscription, id.into()),
2391            Object::ConnectionId(id) => (ObjectType::Connection, id.into()),
2392            Object::FunctionId(id) => (ObjectType::Function, id.into()),
2393            Object::SecretId(id) => (ObjectType::Secret, id.into()),
2394        };
2395        self.metadata_manager
2396            .catalog_controller
2397            .alter_owner(obj_type, id, owner_id as _)
2398            .await
2399    }
2400
2401    async fn alter_set_schema(
2402        &self,
2403        object: alter_set_schema_request::Object,
2404        new_schema_id: SchemaId,
2405    ) -> MetaResult<NotificationVersion> {
2406        let (obj_type, id): (ObjectType, ObjectId) = match object {
2407            alter_set_schema_request::Object::TableId(id) => (ObjectType::Table, id.into()),
2408            alter_set_schema_request::Object::ViewId(id) => (ObjectType::View, id.into()),
2409            alter_set_schema_request::Object::SourceId(id) => (ObjectType::Source, id.into()),
2410            alter_set_schema_request::Object::SinkId(id) => (ObjectType::Sink, id.into()),
2411            alter_set_schema_request::Object::FunctionId(id) => (ObjectType::Function, id.into()),
2412            alter_set_schema_request::Object::ConnectionId(id) => {
2413                (ObjectType::Connection, id.into())
2414            }
2415            alter_set_schema_request::Object::SubscriptionId(id) => {
2416                (ObjectType::Subscription, id.into())
2417            }
2418        };
2419        self.metadata_manager
2420            .catalog_controller
2421            .alter_schema(obj_type, id, new_schema_id)
2422            .await
2423    }
2424
2425    pub async fn wait(&self, job_id: Option<JobId>) -> MetaResult<WaitVersion> {
2426        if let Some(job_id) = job_id {
2427            let database_id = self
2428                .metadata_manager
2429                .catalog_controller
2430                .get_object_database_id(job_id)
2431                .await?;
2432            let catalog_version = self
2433                .metadata_manager
2434                .wait_streaming_job_finished(database_id, job_id)
2435                .await?;
2436            let hummock_version_id = self.barrier_manager.get_hummock_version_id().await;
2437            return Ok(WaitVersion {
2438                catalog_version,
2439                hummock_version_id,
2440            });
2441        }
2442
2443        let timeout_ms = 2 * 60 * 60 * 1000;
2444        let poll_interval = Duration::from_millis(100);
2445        for _ in 0..(timeout_ms / poll_interval.as_millis() as usize) {
2446            let creating_jobs = self
2447                .metadata_manager
2448                .catalog_controller
2449                .list_creating_jobs(true, None)
2450                .await?;
2451            if creating_jobs.is_empty() {
2452                let catalog_version = self
2453                    .metadata_manager
2454                    .catalog_controller
2455                    .current_notification_version()
2456                    .await;
2457                let hummock_version_id = self.barrier_manager.get_hummock_version_id().await;
2458                return Ok(WaitVersion {
2459                    catalog_version,
2460                    hummock_version_id,
2461                });
2462            }
2463
2464            sleep(poll_interval).await;
2465        }
2466        Err(MetaError::cancelled(format!(
2467            "timeout after {timeout_ms}ms"
2468        )))
2469    }
2470
2471    async fn comment_on(&self, comment: Comment) -> MetaResult<NotificationVersion> {
2472        self.metadata_manager
2473            .catalog_controller
2474            .comment_on(comment)
2475            .await
2476    }
2477
2478    async fn alter_streaming_job_config(
2479        &self,
2480        job_id: JobId,
2481        entries_to_add: HashMap<String, String>,
2482        keys_to_remove: Vec<String>,
2483    ) -> MetaResult<NotificationVersion> {
2484        self.metadata_manager
2485            .catalog_controller
2486            .alter_streaming_job_config(job_id, entries_to_add, keys_to_remove)
2487            .await
2488    }
2489}
2490
2491fn report_create_object(
2492    job_id: JobId,
2493    event_name: &str,
2494    obj_type: PbTelemetryDatabaseObject,
2495    connector_name: Option<String>,
2496    attr_info: Option<jsonbb::Value>,
2497) {
2498    report_event(
2499        PbTelemetryEventStage::CreateStreamJob,
2500        event_name,
2501        job_id.as_raw_id() as _,
2502        connector_name,
2503        Some(obj_type),
2504        attr_info,
2505    );
2506}
2507
2508pub fn build_upstream_sink_info(
2509    sink_id: SinkId,
2510    original_target_columns: Vec<PbColumnCatalog>,
2511    sink_fragment_id: FragmentId,
2512    target_table: &PbTable,
2513    target_fragment_id: FragmentId,
2514) -> MetaResult<UpstreamSinkInfo> {
2515    let sink_columns = if !original_target_columns.is_empty() {
2516        original_target_columns.clone()
2517    } else {
2518        // This is due to the fact that the value did not exist in earlier versions,
2519        // which means no schema changes such as `ADD/DROP COLUMN` have been made to the table.
2520        // Therefore the columns of the table at this point are `original_target_columns`.
2521        // This value of sink will be filled on the meta.
2522        target_table.columns.clone()
2523    };
2524
2525    let sink_output_fields = sink_columns
2526        .iter()
2527        .map(|col| Field::from(col.column_desc.as_ref().unwrap()).to_prost())
2528        .collect_vec();
2529    let output_indices = (0..sink_output_fields.len())
2530        .map(|i| i as u32)
2531        .collect_vec();
2532
2533    let dist_key_indices: anyhow::Result<Vec<u32>> = try {
2534        let sink_idx_by_col_id = sink_columns
2535            .iter()
2536            .enumerate()
2537            .map(|(idx, col)| {
2538                let column_id = col.column_desc.as_ref().unwrap().column_id;
2539                (column_id, idx as u32)
2540            })
2541            .collect::<HashMap<_, _>>();
2542        target_table
2543            .distribution_key
2544            .iter()
2545            .map(|dist_idx| {
2546                let column_id = target_table.columns[*dist_idx as usize]
2547                    .column_desc
2548                    .as_ref()
2549                    .unwrap()
2550                    .column_id;
2551                let sink_idx = sink_idx_by_col_id
2552                    .get(&column_id)
2553                    .ok_or_else(|| anyhow::anyhow!("column id {} not found in sink", column_id))?;
2554                Ok(*sink_idx)
2555            })
2556            .collect::<anyhow::Result<Vec<_>>>()?
2557    };
2558    let dist_key_indices =
2559        dist_key_indices.map_err(|e| e.context("failed to get distribution key indices"))?;
2560    let downstream_fragment_id = target_fragment_id as _;
2561    let new_downstream_relation = DownstreamFragmentRelation {
2562        downstream_fragment_id,
2563        dispatcher_type: DispatcherType::Hash,
2564        dist_key_indices,
2565        output_mapping: PbDispatchOutputMapping::simple(output_indices),
2566    };
2567    let current_target_columns = target_table.get_columns();
2568    let project_exprs = build_select_node_list(&sink_columns, current_target_columns)?;
2569    Ok(UpstreamSinkInfo {
2570        sink_id,
2571        sink_fragment_id: sink_fragment_id as _,
2572        sink_output_fields,
2573        sink_original_target_columns: original_target_columns,
2574        project_exprs,
2575        new_sink_downstream: new_downstream_relation,
2576    })
2577}
2578
2579pub fn refill_upstream_sink_union_in_table(
2580    union_fragment_root: &mut PbStreamNode,
2581    upstream_sink_infos: &Vec<UpstreamSinkInfo>,
2582) {
2583    visit_stream_node_cont_mut(union_fragment_root, |node| {
2584        if let Some(NodeBody::UpstreamSinkUnion(upstream_sink_union)) = &mut node.node_body {
2585            let init_upstreams = upstream_sink_infos
2586                .iter()
2587                .map(|info| PbUpstreamSinkInfo {
2588                    upstream_fragment_id: info.sink_fragment_id,
2589                    sink_output_schema: info.sink_output_fields.clone(),
2590                    project_exprs: info.project_exprs.clone(),
2591                })
2592                .collect();
2593            upstream_sink_union.init_upstreams = init_upstreams;
2594            false
2595        } else {
2596            true
2597        }
2598    });
2599}
2600
2601#[cfg(test)]
2602mod tests {
2603    use std::num::NonZeroUsize;
2604
2605    use super::*;
2606
2607    #[test]
2608    fn test_validate_specified_parallelism_accepts_within_max() {
2609        DdlController::validate_specified_parallelism(
2610            Some(NonZeroUsize::new(4).unwrap()),
2611            Some(NonZeroUsize::new(8).unwrap()),
2612            NonZeroUsize::new(8).unwrap(),
2613        )
2614        .unwrap();
2615    }
2616
2617    #[test]
2618    fn test_validate_specified_parallelism_rejects_parallelism_over_max() {
2619        let result = DdlController::validate_specified_parallelism(
2620            Some(NonZeroUsize::new(9).unwrap()),
2621            None,
2622            NonZeroUsize::new(8).unwrap(),
2623        );
2624        assert!(matches!(
2625            result,
2626            Err(ref e) if matches!(e.inner(), MetaErrorInner::InvalidParameter(_))
2627        ));
2628    }
2629
2630    #[test]
2631    fn test_validate_specified_parallelism_rejects_backfill_parallelism_over_max() {
2632        let result = DdlController::validate_specified_parallelism(
2633            None,
2634            Some(NonZeroUsize::new(9).unwrap()),
2635            NonZeroUsize::new(8).unwrap(),
2636        );
2637        assert!(matches!(
2638            result,
2639            Err(ref e) if matches!(e.inner(), MetaErrorInner::InvalidParameter(_))
2640        ));
2641    }
2642}