Skip to main content

risingwave_meta/controller/
streaming_job.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::{BTreeMap, HashMap, HashSet};
16use std::num::NonZeroUsize;
17
18use anyhow::anyhow;
19use indexmap::IndexMap;
20use itertools::Itertools;
21use risingwave_common::catalog::{
22    ColumnCatalog, FragmentTypeFlag, FragmentTypeMask, ICEBERG_SINK_PREFIX, ICEBERG_SOURCE_PREFIX,
23    RISINGWAVE_ICEBERG_ROW_ID, ROW_ID_COLUMN_NAME, max_column_id,
24};
25use risingwave_common::config::DefaultParallelism;
26use risingwave_common::hash::VnodeCountCompat;
27use risingwave_common::id::JobId;
28use risingwave_common::secret::LocalSecretManager;
29use risingwave_common::system_param::AdaptiveParallelismStrategy;
30use risingwave_common::system_param::adaptive_parallelism_strategy::parse_strategy;
31use risingwave_common::util::iter_util::ZipEqDebug;
32use risingwave_common::util::stream_graph_visitor::{
33    visit_stream_node_body, visit_stream_node_mut, visit_stream_node_stream_scan,
34};
35use risingwave_common::{bail, current_cluster_version};
36use risingwave_connector::allow_alter_on_fly_fields::check_sink_allow_alter_on_fly_fields;
37use risingwave_connector::connector_common::validate_connection;
38use risingwave_connector::error::ConnectorError;
39use risingwave_connector::sink::file_sink::fs::FsSink;
40use risingwave_connector::sink::{CONNECTOR_TYPE_KEY, SinkError};
41use risingwave_connector::source::cdc::{CdcSourceDdlValidator, CdcSourceType};
42use risingwave_connector::source::ingest_mode::IngestMode;
43use risingwave_connector::source::{
44    ConnectorProperties, UPSTREAM_SOURCE_KEY, pb_connection_type_to_connection_type,
45};
46use risingwave_connector::{
47    WithOptionsSecResolved, WithPropertiesExt, dispatch_cdc_source_type, match_sink_name_str,
48};
49use risingwave_meta_model::object::ObjectType;
50use risingwave_meta_model::prelude::{StreamingJob as StreamingJobModel, *};
51use risingwave_meta_model::refresh_job::RefreshState;
52use risingwave_meta_model::streaming_job::BackfillOrders;
53use risingwave_meta_model::user_privilege::Action;
54use risingwave_meta_model::*;
55use risingwave_pb::catalog::table::PbEngine;
56use risingwave_pb::catalog::{PbConnection, PbCreateType, PbTable};
57use risingwave_pb::common::ThrottleType;
58use risingwave_pb::ddl_service::streaming_job_resource_type;
59use risingwave_pb::meta::alter_connector_props_request::AlterIcebergTableIds;
60use risingwave_pb::meta::list_rate_limits_response::RateLimitInfo;
61use risingwave_pb::meta::object::PbObjectInfo;
62use risingwave_pb::meta::subscribe_response::{
63    Info as NotificationInfo, Operation as NotificationOperation, Operation,
64};
65use risingwave_pb::meta::{ObjectDependency as PbObjectDependency, PbObject, PbObjectGroup};
66use risingwave_pb::plan_common::PbColumnCatalog;
67use risingwave_pb::secret::PbSecretRef;
68use risingwave_pb::stream_plan::stream_fragment_graph::Parallelism;
69use risingwave_pb::stream_plan::stream_node::PbNodeBody;
70use risingwave_pb::stream_plan::{PbSinkLogStoreType, PbStreamNode, StreamScanType};
71use risingwave_pb::user::PbUserInfo;
72use risingwave_sqlparser::ast::{Engine, SqlOption, Statement};
73use risingwave_sqlparser::parser::{Parser, ParserError};
74use sea_orm::ActiveValue::Set;
75use sea_orm::sea_query::{Expr, Query, SimpleExpr};
76use sea_orm::{
77    ActiveModelTrait, ColumnTrait, Condition, DatabaseTransaction, EntityTrait, IntoActiveModel,
78    JoinType, NotSet, PaginatorTrait, QueryFilter, QuerySelect, RelationTrait, TransactionTrait,
79};
80use thiserror_ext::AsReport;
81
82use super::rename::IndexItemRewriter;
83use crate::barrier::Command;
84use crate::controller::ObjectModel;
85use crate::controller::catalog::{
86    CatalogController, CrossDbSubscriptionInfo, DropTableConnectorContext, load_object_models,
87    resolve_cross_db_subscriptions,
88};
89use crate::controller::fragment::FragmentTypeMaskExt;
90use crate::controller::utils::{
91    PartialObject, build_object_group_for_delete, check_if_belongs_to_iceberg_table,
92    check_relation_name_duplicate, check_sink_into_table_cycle, ensure_job_not_canceled,
93    ensure_object_id, ensure_user_id, fetch_target_fragments, format_with_option_secret_resolved,
94    get_belong_objects, get_belong_objects_by_ids, get_referring_objects, get_table_columns,
95    grant_default_privileges_automatically, insert_fragment_relations,
96    list_object_dependencies_by_object_id, list_user_info_by_ids, upsert_user_privileges,
97};
98use crate::error::MetaErrorInner;
99use crate::manager::{NotificationVersion, StreamingJob, StreamingJobType};
100use crate::model::{
101    FragmentDownstreamRelation, FragmentReplaceUpstream, StreamContext, StreamJobFragments,
102    StreamJobFragmentsToCreate,
103};
104use crate::stream::SplitAssignment;
105use crate::{MetaError, MetaResult};
106
107/// Result of [`CatalogController::try_abort_creating_streaming_job`].
108pub struct AbortCreatingJobResult {
109    /// The job was aborted by this call or already gone. `false` means the job was left untouched.
110    pub aborted: bool,
111    /// The database of the job, if the job was found.
112    pub database_id: Option<DatabaseId>,
113    /// The aborted sinks; the caller should retire their maintenance state and stop their
114    /// coordinators, using only sinks actually removed.
115    pub aborted_sink_ids: Vec<SinkId>,
116    /// Runtime and state cleanup information captured before deleting the catalog rows.
117    /// This is returned only when handling an explicit cancellation.
118    pub cancel_info: Option<CancelStreamingJobInfo>,
119    /// Internal subscriptions to drop from upstream databases after downstream cleanup.
120    pub cross_db_subscriptions: Vec<CrossDbSubscriptionInfo>,
121}
122
123/// Runtime and state cleanup information for canceling a creating streaming job.
124pub struct CancelStreamingJobInfo {
125    /// Barrier command that stops every affected streaming job.
126    pub command: Command,
127    /// Streaming jobs included in `command`.
128    pub streaming_job_ids: Vec<JobId>,
129    /// State tables to unregister after the barrier is collected.
130    pub state_table_ids: Vec<TableId>,
131}
132
133#[derive(Debug)]
134pub struct CommittedEpochTruncateJob {
135    pub job_id: JobId,
136    pub state_table_ids: HashSet<TableId>,
137    pub upstream_table_snapshot_epochs: HashMap<TableId, Option<u64>>,
138}
139
140#[derive(Debug)]
141pub struct TableChangeLogTruncateInfo {
142    pub subscription_retention_seconds: HashMap<TableId, u64>,
143    pub progress_table_subscribers: Vec<ProgressTableChangeLogSubscriber>,
144    pub committed_epoch_truncate_jobs: Vec<CommittedEpochTruncateJob>,
145}
146
147#[derive(Debug)]
148pub struct ProgressTableChangeLogSubscriber {
149    pub subscriber_job_id: JobId,
150    pub upstream_table_id: TableId,
151    pub progress_table_id: TableId,
152}
153fn serverless_backfill_resource_group_placeholder(job_id: JobId) -> String {
154    format!("SERVERLESS_BACKFILL_RESOURCE_GROUP_TBD_FOR_{job_id}")
155}
156
157fn job_initial_catalog_resource_group(
158    resource_type: &streaming_job_resource_type::ResourceType,
159    job_id: JobId,
160) -> Option<String> {
161    match resource_type {
162        streaming_job_resource_type::ResourceType::Regular(_)
163        | streaming_job_resource_type::ResourceType::ServerlessBackfill(false) => None,
164        streaming_job_resource_type::ResourceType::SpecificResourceGroup(group) => {
165            Some(group.clone())
166        }
167        streaming_job_resource_type::ResourceType::ServerlessBackfill(true) => {
168            Some(serverless_backfill_resource_group_placeholder(job_id))
169        }
170    }
171}
172
173/// A planned fragment update for dependent sources when a connection's properties change.
174///
175/// We keep it as a named struct (instead of a tuple) for readability and to avoid clippy
176/// `type_complexity` warnings.
177#[derive(Debug)]
178struct DependentSourceFragmentUpdate {
179    job_ids: Vec<JobId>,
180    with_properties: BTreeMap<String, String>,
181    secret_refs: BTreeMap<String, PbSecretRef>,
182    is_shared_source: bool,
183}
184
185#[derive(Debug)]
186struct ReplaceOriginalJobInfo {
187    max_parallelism: i32,
188    timezone: Option<String>,
189    config_override: Option<String>,
190    adaptive_parallelism_strategy: Option<String>,
191    parallelism: StreamingParallelism,
192    specific_resource_group: Option<String>,
193}
194
195impl ReplaceOriginalJobInfo {
196    fn resolved_parallelism(
197        &self,
198        specified_parallelism: Option<&NonZeroUsize>,
199    ) -> StreamingParallelism {
200        specified_parallelism
201            .map(|n| StreamingParallelism::Fixed(n.get() as _))
202            .unwrap_or_else(|| self.parallelism.clone())
203    }
204
205    fn stream_context(&self, ctx_override: Option<&StreamContext>) -> StreamContext {
206        StreamContext {
207            timezone: ctx_override
208                .and_then(|ctx| ctx.timezone.clone())
209                .or_else(|| self.timezone.clone()),
210            // We don't expect replacing a job with a different config override.
211            // Thus always use the original config override.
212            config_override: self.config_override.clone().unwrap_or_default().into(),
213        }
214    }
215
216    fn resource_type(&self) -> streaming_job_resource_type::ResourceType {
217        match &self.specific_resource_group {
218            Some(group) => {
219                streaming_job_resource_type::ResourceType::SpecificResourceGroup(group.clone())
220            }
221            None => streaming_job_resource_type::ResourceType::Regular(true),
222        }
223    }
224}
225
226impl From<streaming_job::Model> for ReplaceOriginalJobInfo {
227    fn from(model: streaming_job::Model) -> Self {
228        Self {
229            max_parallelism: model.max_parallelism,
230            timezone: model.timezone,
231            config_override: model.config_override,
232            adaptive_parallelism_strategy: model.adaptive_parallelism_strategy,
233            parallelism: model.parallelism,
234            specific_resource_group: model.specific_resource_group,
235        }
236    }
237}
238
239fn update_source_node_rate_limit(
240    node: &mut PbNodeBody,
241    rate_limit: Option<u32>,
242) -> MetaResult<bool> {
243    let (properties, current_limit) = match node {
244        PbNodeBody::Source(node) => match &mut node.source_inner {
245            Some(inner) => (&inner.with_properties, &mut inner.rate_limit),
246            None => return Ok(false),
247        },
248        PbNodeBody::StreamFsFetch(node) => match &mut node.node_inner {
249            Some(inner) => (&inner.with_properties, &mut inner.rate_limit),
250            None => return Ok(false),
251        },
252        _ => return Ok(false),
253    };
254    if properties.is_iceberg_update_source() {
255        return Err(MetaError::invalid_parameter(
256            "Iceberg streaming_updates does not support rate limiting",
257        ));
258    }
259    *current_limit = rate_limit;
260    Ok(true)
261}
262
263fn update_sink_node_rate_limit(node: &mut PbNodeBody, rate_limit: Option<u32>) -> MetaResult<bool> {
264    let PbNodeBody::Sink(node) = node else {
265        return Ok(false);
266    };
267    if node.log_store_type != PbSinkLogStoreType::KvLogStore as i32 {
268        return Err(MetaError::invalid_parameter(
269            "sink rate limit is only supported for kv log store, please SET sink_decouple = TRUE before CREATE SINK",
270        ));
271    }
272    node.rate_limit = rate_limit;
273    Ok(true)
274}
275
276impl CatalogController {
277    pub async fn get_table_change_log_truncate_info(
278        &self,
279    ) -> MetaResult<TableChangeLogTruncateInfo> {
280        let inner = self.inner.read().await;
281
282        let subscriptions: Vec<(SubscriptionId, TableId, Option<i64>)> = Subscription::find()
283            .select_only()
284            .columns([
285                subscription::Column::SubscriptionId,
286                subscription::Column::DependentTableId,
287                subscription::Column::RetentionSeconds,
288            ])
289            .filter(subscription::Column::CrossDbDownstreamJobId.is_null())
290            .into_tuple()
291            .all(&inner.db)
292            .await?;
293        let mut subscription_retention_seconds = HashMap::new();
294        for (subscription_id, table_id, retention_seconds) in subscriptions {
295            let Some(retention_seconds) = retention_seconds else {
296                return Err(anyhow!(
297                    "user subscription {} on table {} has no retention",
298                    subscription_id,
299                    table_id
300                )
301                .into());
302            };
303            let retention_seconds = u64::try_from(retention_seconds).map_err(|_| {
304                anyhow!(
305                    "subscription on table {} has invalid retention seconds {}",
306                    table_id,
307                    retention_seconds
308                )
309            })?;
310            subscription_retention_seconds
311                .entry(table_id)
312                .and_modify(|retention: &mut u64| *retention = (*retention).max(retention_seconds))
313                .or_insert(retention_seconds);
314        }
315
316        let committed_epoch_truncate_job_ids: HashSet<JobId> = StreamingJobModel::find()
317            .select_only()
318            .column(streaming_job::Column::JobId)
319            .filter(
320                Condition::any()
321                    .add(streaming_job::Column::JobStatus.eq(JobStatus::Creating))
322                    .add(streaming_job::Column::RefreshIntervalSec.is_not_null()),
323            )
324            .into_tuple::<JobId>()
325            .all(&inner.db)
326            .await?
327            .into_iter()
328            .collect();
329        let fragments: Vec<(FragmentId, JobId, i32, StreamNode, TableIdArray)> = Fragment::find()
330            .select_only()
331            .columns([
332                fragment::Column::FragmentId,
333                fragment::Column::JobId,
334                fragment::Column::FragmentTypeMask,
335                fragment::Column::StreamNode,
336                fragment::Column::StateTableIds,
337            ])
338            .filter(FragmentTypeMask::intersects_any([
339                FragmentTypeFlag::IcebergWithPkIndexWriter,
340                FragmentTypeFlag::SnapshotBackfillStreamScan,
341                FragmentTypeFlag::CrossDbSnapshotBackfillStreamScan,
342            ]))
343            .into_tuple()
344            .all(&inner.db)
345            .await?;
346        let iceberg_job_ids: HashSet<_> = fragments
347            .iter()
348            .filter(|(_, _, fragment_type_mask, _, _)| {
349                FragmentTypeMask::from(*fragment_type_mask)
350                    .contains(FragmentTypeFlag::IcebergWithPkIndexWriter)
351            })
352            .map(|(_, job_id, _, _, _)| *job_id)
353            .collect();
354        let mut committed_epoch_truncate_job_info: HashMap<_, _> = committed_epoch_truncate_job_ids
355            .into_iter()
356            .filter(|job_id| !iceberg_job_ids.contains(job_id))
357            .map(|job_id| {
358                (
359                    job_id,
360                    CommittedEpochTruncateJob {
361                        job_id,
362                        state_table_ids: HashSet::new(),
363                        upstream_table_snapshot_epochs: HashMap::new(),
364                    },
365                )
366            })
367            .collect();
368        let mut progress_table_subscribers = Vec::new();
369        // Progress-table subscribers come from Iceberg snapshot backfills and cross-database
370        // snapshot backfills. Process cross-database fragments independently because one job may
371        // also participate in the local committed-epoch truncation path.
372        for (fragment_id, job_id, fragment_type_mask, stream_node, state_table_ids) in fragments {
373            let fragment_type_mask = FragmentTypeMask::from(fragment_type_mask);
374            if fragment_type_mask.contains(FragmentTypeFlag::SnapshotBackfillStreamScan) {
375                if iceberg_job_ids.contains(&job_id) {
376                    let mut collection_error = None;
377                    visit_stream_node_stream_scan(&stream_node.to_protobuf(), |stream_scan| {
378                        let scan_type = match StreamScanType::try_from(stream_scan.stream_scan_type)
379                        {
380                            Ok(scan_type) => scan_type,
381                            Err(err) => {
382                                collection_error = Some(anyhow::Error::new(err).context(format!(
383                                    "invalid persisted stream scan type {} in job {} fragment {}",
384                                    stream_scan.stream_scan_type, job_id, fragment_id
385                                )));
386                                return;
387                            }
388                        };
389                        if scan_type != StreamScanType::SnapshotBackfill {
390                            return;
391                        }
392                        let Some(progress_table) = stream_scan.state_table.as_ref() else {
393                            collection_error = Some(anyhow!(
394                                "snapshot backfill in Iceberg V3 job {} has no progress table",
395                                job_id
396                            ));
397                            return;
398                        };
399                        progress_table_subscribers.push(ProgressTableChangeLogSubscriber {
400                            subscriber_job_id: job_id,
401                            upstream_table_id: stream_scan.table_id,
402                            progress_table_id: progress_table.id,
403                        });
404                    });
405                    if let Some(err) = collection_error {
406                        return Err(err.into());
407                    }
408                } else if let Some(info) = committed_epoch_truncate_job_info.get_mut(&job_id) {
409                    info.state_table_ids
410                        .extend(state_table_ids.inner_ref().iter().copied());
411                    let mut collection_error = None;
412                    visit_stream_node_stream_scan(&stream_node.to_protobuf(), |stream_scan| {
413                        let scan_type = match StreamScanType::try_from(stream_scan.stream_scan_type)
414                        {
415                            Ok(scan_type) => scan_type,
416                            Err(err) => {
417                                collection_error = Some(anyhow::Error::new(err).context(format!(
418                                    "invalid persisted stream scan type {} in job {} fragment {}",
419                                    stream_scan.stream_scan_type, job_id, fragment_id
420                                )));
421                                return;
422                            }
423                        };
424                        if scan_type != StreamScanType::SnapshotBackfill {
425                            return;
426                        }
427                        match info
428                            .upstream_table_snapshot_epochs
429                            .entry(stream_scan.table_id)
430                        {
431                            std::collections::hash_map::Entry::Occupied(entry) => {
432                                if entry.get() != &stream_scan.snapshot_backfill_epoch {
433                                    collection_error = Some(anyhow!(
434                                        "job {} has inconsistent snapshot epochs for upstream table {}",
435                                        job_id,
436                                        stream_scan.table_id
437                                    ));
438                                }
439                            }
440                            std::collections::hash_map::Entry::Vacant(entry) => {
441                                entry.insert(stream_scan.snapshot_backfill_epoch);
442                            }
443                        }
444                    });
445                    if let Some(err) = collection_error {
446                        return Err(err.into());
447                    }
448                }
449            }
450
451            if fragment_type_mask.contains(FragmentTypeFlag::CrossDbSnapshotBackfillStreamScan) {
452                let mut collection_error = None;
453                visit_stream_node_stream_scan(&stream_node.to_protobuf(), |stream_scan| {
454                    let scan_type = match StreamScanType::try_from(stream_scan.stream_scan_type) {
455                        Ok(scan_type) => scan_type,
456                        Err(err) => {
457                            collection_error = Some(anyhow::Error::new(err).context(format!(
458                                "invalid persisted stream scan type {} in job {} fragment {}",
459                                stream_scan.stream_scan_type, job_id, fragment_id
460                            )));
461                            return;
462                        }
463                    };
464                    if scan_type != StreamScanType::CrossDbSnapshotBackfill {
465                        return;
466                    }
467                    let Some(progress_table) = stream_scan.state_table.as_ref() else {
468                        collection_error = Some(anyhow!(
469                            "cross-database backfill in job {} has no progress table",
470                            job_id
471                        ));
472                        return;
473                    };
474                    progress_table_subscribers.push(ProgressTableChangeLogSubscriber {
475                        subscriber_job_id: job_id,
476                        upstream_table_id: stream_scan.table_id,
477                        progress_table_id: progress_table.id,
478                    });
479                });
480                if let Some(err) = collection_error {
481                    return Err(err.into());
482                }
483            }
484        }
485        let committed_epoch_truncate_jobs = committed_epoch_truncate_job_info
486            .into_values()
487            .filter(|info| !info.upstream_table_snapshot_epochs.is_empty())
488            .collect();
489        Ok(TableChangeLogTruncateInfo {
490            subscription_retention_seconds,
491            progress_table_subscribers,
492            committed_epoch_truncate_jobs,
493        })
494    }
495
496    pub async fn get_pinned_snapshot_epochs(&self) -> MetaResult<HashMap<TableId, HashSet<u64>>> {
497        // Hold the catalog read lock across both queries so a job cannot transition out of
498        // `Creating` while its fragments are being inspected.
499        let inner = self.inner.read().await;
500        let creating_job_ids = StreamingJobModel::find()
501            .select_only()
502            .column(streaming_job::Column::JobId)
503            .filter(streaming_job::Column::JobStatus.eq(JobStatus::Creating))
504            .into_tuple::<JobId>()
505            .all(&inner.db)
506            .await?;
507        if creating_job_ids.is_empty() {
508            return Ok(HashMap::new());
509        }
510        let fragments = Fragment::find()
511            .filter(fragment::Column::JobId.is_in(creating_job_ids))
512            .all(&inner.db)
513            .await?;
514        let mut pinned_snapshot_epochs: HashMap<TableId, HashSet<u64>> = HashMap::new();
515        for fragment in fragments {
516            visit_stream_node_stream_scan(&fragment.stream_node.to_protobuf(), |stream_scan| {
517                let scan_type = match StreamScanType::try_from(stream_scan.stream_scan_type) {
518                    Ok(scan_type) => scan_type,
519                    Err(err) => {
520                        tracing::warn!(
521                            job_id = %fragment.job_id,
522                            fragment_id = %fragment.fragment_id,
523                            stream_scan_type = stream_scan.stream_scan_type,
524                            error = %err.as_report(),
525                            "invalid persisted stream scan type, skip collecting snapshot pin"
526                        );
527                        return;
528                    }
529                };
530                if !matches!(
531                    scan_type,
532                    StreamScanType::SnapshotBackfill | StreamScanType::CrossDbSnapshotBackfill
533                ) {
534                    return;
535                }
536                let Some(epoch) = stream_scan.snapshot_backfill_epoch else {
537                    tracing::warn!(
538                        job_id = %fragment.job_id,
539                        fragment_id = %fragment.fragment_id,
540                        table_id = %stream_scan.table_id,
541                        "persisted snapshot backfill epoch is not set, skip collecting snapshot pin"
542                    );
543                    return;
544                };
545                pinned_snapshot_epochs
546                    .entry(stream_scan.table_id)
547                    .or_default()
548                    .insert(epoch);
549            });
550        }
551        Ok(pinned_snapshot_epochs)
552    }
553
554    #[expect(clippy::too_many_arguments)]
555    pub async fn create_streaming_job_obj(
556        txn: &DatabaseTransaction,
557        obj_type: ObjectType,
558        owner_id: UserId,
559        belong_to_oid: Option<ObjectId>,
560        create_type: PbCreateType,
561        ctx: StreamContext,
562        adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
563        streaming_parallelism: StreamingParallelism,
564        max_parallelism: usize,
565        resource_type: streaming_job_resource_type::ResourceType,
566        backfill_parallelism: Option<StreamingParallelism>,
567        backfill_adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
568        refresh_interval_sec: Option<u64>,
569    ) -> MetaResult<streaming_job::Model> {
570        let obj = Self::create_object(txn, obj_type, owner_id, belong_to_oid).await?;
571        let job_id = obj.oid.as_job_id();
572        let is_serverless_backfill = matches!(
573            &resource_type,
574            streaming_job_resource_type::ResourceType::ServerlessBackfill(true)
575        );
576        let model = streaming_job::Model {
577            job_id,
578            job_status: JobStatus::Initial,
579            create_type: create_type.into(),
580            timezone: ctx.timezone,
581            config_override: Some(ctx.config_override.to_string()),
582            adaptive_parallelism_strategy: adaptive_parallelism_strategy
583                .as_ref()
584                .map(ToString::to_string),
585            parallelism: streaming_parallelism,
586            backfill_parallelism,
587            backfill_adaptive_parallelism_strategy: backfill_adaptive_parallelism_strategy
588                .as_ref()
589                .map(ToString::to_string),
590            backfill_orders: None,
591            max_parallelism: max_parallelism as _,
592            specific_resource_group: job_initial_catalog_resource_group(&resource_type, job_id),
593            is_serverless_backfill,
594            refresh_interval_sec: refresh_interval_sec.map(|s| s as i64),
595        };
596        let job = model.clone().into_active_model();
597        StreamingJobModel::insert(job).exec(txn).await?;
598
599        Ok(model)
600    }
601
602    /// Create the initial catalogs for the streaming job.
603    ///
604    /// Some of the fields in the given streaming job are placeholders, which will
605    /// be updated later in `prepare_streaming_job`. The catalogs become visible to frontend after
606    /// the first barrier is collected in `post_collect_job_fragments`.
607    #[expect(clippy::too_many_arguments)]
608    #[await_tree::instrument]
609    pub async fn create_job_catalog(
610        &self,
611        streaming_job: &mut StreamingJob,
612        ctx: &StreamContext,
613        parallelism: &Option<Parallelism>,
614        max_parallelism: usize,
615        mut dependencies: HashSet<ObjectId>,
616        resource_type: streaming_job_resource_type::ResourceType,
617        backfill_parallelism: &Option<Parallelism>,
618        adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
619        backfill_adaptive_parallelism_strategy: Option<AdaptiveParallelismStrategy>,
620        replace_sink: Option<&SinkId>,
621        refresh_interval_sec: Option<u64>,
622    ) -> MetaResult<streaming_job::Model> {
623        let inner = self.inner.write().await;
624        let txn = inner.db.begin().await?;
625        let create_type = streaming_job.create_type();
626
627        let streaming_parallelism = match (parallelism, self.env.opts.default_parallelism) {
628            (None, DefaultParallelism::Full) => StreamingParallelism::Adaptive,
629            (None, DefaultParallelism::Default(n)) => StreamingParallelism::Fixed(n.get()),
630            (Some(n), _) => StreamingParallelism::Fixed(n.parallelism as _),
631        };
632        let backfill_parallelism = backfill_parallelism
633            .as_ref()
634            .map(|p| StreamingParallelism::Fixed(p.parallelism as _))
635            .or_else(|| {
636                backfill_adaptive_parallelism_strategy
637                    .as_ref()
638                    .map(|_| StreamingParallelism::Adaptive)
639            });
640
641        ensure_user_id(streaming_job.owner() as _, &txn).await?;
642        ensure_object_id(ObjectType::Database, streaming_job.database_id(), &txn).await?;
643        ensure_object_id(ObjectType::Schema, streaming_job.schema_id(), &txn).await?;
644        if let Some(old_sink_id) = replace_sink {
645            let StreamingJob::Sink(sink, _) = streaming_job else {
646                bail!("replacement sink catalog requires a sink job")
647            };
648            let (old_sink, old_object) = Sink::find_by_id(*old_sink_id)
649                .find_also_related(Object)
650                .one(&txn)
651                .await?
652                .and_then(|(sink, object)| object.map(|object| (sink, object)))
653                .ok_or_else(|| MetaError::catalog_id_not_found("sink", *old_sink_id))?;
654            let old_streaming_job = StreamingJobModel::find_by_id(old_sink_id.as_job_id())
655                .one(&txn)
656                .await?
657                .ok_or_else(|| MetaError::catalog_id_not_found("sink", *old_sink_id))?;
658            if old_object.obj_type != ObjectType::Sink
659                || old_object.database_id != Some(sink.database_id)
660                || old_object.schema_id != Some(sink.schema_id)
661                || old_sink.name != sink.name
662            {
663                bail!(
664                    "old sink {} does not match replacement sink {}",
665                    old_sink_id,
666                    sink.name
667                );
668            }
669            if old_sink.target_table.is_some() || sink.target_table.is_some() {
670                bail!("replace sink into table is not supported");
671            }
672            if old_streaming_job.job_status != JobStatus::Created {
673                bail!("sink {} is not ready to be replaced", old_sink_id);
674            }
675        } else {
676            check_relation_name_duplicate(
677                &streaming_job.name(),
678                streaming_job.database_id(),
679                streaming_job.schema_id(),
680                &txn,
681            )
682            .await?;
683        }
684
685        // check if any dependency is in altering status.
686        if !dependencies.is_empty() {
687            let altering_cnt = ObjectDependency::find()
688                .join(
689                    JoinType::InnerJoin,
690                    object_dependency::Relation::Object1.def(),
691                )
692                .join(JoinType::InnerJoin, object::Relation::StreamingJob.def())
693                .filter(
694                    object_dependency::Column::Oid
695                        .is_in(dependencies.clone())
696                        .and(object::Column::ObjType.eq(ObjectType::Table))
697                        .and(streaming_job::Column::JobStatus.ne(JobStatus::Created))
698                        .and(
699                            // It means the referring table is just dummy for altering.
700                            object::Column::Oid.not_in_subquery(
701                                Query::select()
702                                    .column(table::Column::TableId)
703                                    .from(Table)
704                                    .to_owned(),
705                            ),
706                        ),
707                )
708                .count(&txn)
709                .await?;
710            if altering_cnt != 0 {
711                return Err(MetaError::permission_denied(
712                    "some dependent relations are being altered",
713                ));
714            }
715
716            // Check if any dependency is a batch refresh job.
717            // Streaming on batch refresh materialized views is not supported.
718            let batch_refresh_cnt = StreamingJobModel::find()
719                .filter(
720                    streaming_job::Column::JobId
721                        .is_in(dependencies.iter().map(|id| JobId::new(id.as_raw_id())))
722                        .and(streaming_job::Column::RefreshIntervalSec.is_not_null()),
723                )
724                .count(&txn)
725                .await?;
726            if batch_refresh_cnt != 0 {
727                return Err(MetaError::permission_denied(
728                    "creating streaming jobs on batch refresh materialized views is not supported",
729                ));
730            }
731        }
732
733        let streaming_job_model = match streaming_job {
734            StreamingJob::MaterializedView(table) => {
735                let streaming_job_model = Self::create_streaming_job_obj(
736                    &txn,
737                    ObjectType::Table,
738                    table.owner as _,
739                    Some(table.schema_id.as_object_id()),
740                    create_type,
741                    ctx.clone(),
742                    adaptive_parallelism_strategy,
743                    streaming_parallelism,
744                    max_parallelism,
745                    resource_type.clone(),
746                    backfill_parallelism.clone(),
747                    backfill_adaptive_parallelism_strategy,
748                    refresh_interval_sec,
749                )
750                .await?;
751                table.id = streaming_job_model.job_id.as_mv_table_id();
752                let table_model: table::ActiveModel = table.clone().into();
753                Table::insert(table_model).exec(&txn).await?;
754                streaming_job_model
755            }
756            StreamingJob::Sink(sink, belong_to_table_id) => {
757                if let Some(target_table_id) = sink.target_table
758                    && check_sink_into_table_cycle(
759                        target_table_id.into(),
760                        dependencies.iter().cloned().collect(),
761                        &txn,
762                    )
763                    .await?
764                {
765                    bail!("Creating such a sink will result in circular dependency.");
766                }
767
768                let streaming_job_model = Self::create_streaming_job_obj(
769                    &txn,
770                    ObjectType::Sink,
771                    sink.owner as _,
772                    Some(
773                        belong_to_table_id
774                            .map(|table_id| table_id.as_object_id())
775                            .unwrap_or(sink.schema_id.as_object_id()),
776                    ),
777                    create_type,
778                    ctx.clone(),
779                    adaptive_parallelism_strategy,
780                    streaming_parallelism,
781                    max_parallelism,
782                    resource_type.clone(),
783                    backfill_parallelism.clone(),
784                    backfill_adaptive_parallelism_strategy,
785                    None, // refresh_interval_sec: only for MV
786                )
787                .await?;
788                sink.id = streaming_job_model.job_id.as_sink_id();
789                if let Some(old_sink_id) = replace_sink {
790                    let final_sink_name = sink.name.clone();
791                    // The replacement sink cannot reuse the old catalog name until the
792                    // cutover transaction deletes the old sink. Use a deterministic temporary
793                    // name and rename it back in `post_collect_job_fragments`.
794                    sink.name = format!("__rw_replacing_sink_{}_{}", old_sink_id, sink.id);
795                    tracing::debug!(
796                        old_sink_id = %old_sink_id,
797                        new_sink_id = %sink.id,
798                        final_name = %final_sink_name,
799                        temp_name = %sink.name,
800                        "created replacement sink catalog with temporary name"
801                    );
802                }
803                let sink_model: sink::ActiveModel = sink.clone().into();
804                Sink::insert(sink_model).exec(&txn).await?;
805                streaming_job_model
806            }
807            StreamingJob::Table(src, table, _) => {
808                let streaming_job_model = Self::create_streaming_job_obj(
809                    &txn,
810                    ObjectType::Table,
811                    table.owner as _,
812                    Some(table.schema_id.as_object_id()),
813                    create_type,
814                    ctx.clone(),
815                    adaptive_parallelism_strategy,
816                    streaming_parallelism,
817                    max_parallelism,
818                    resource_type.clone(),
819                    backfill_parallelism.clone(),
820                    backfill_adaptive_parallelism_strategy,
821                    None, // refresh_interval_sec: only for MV
822                )
823                .await?;
824                let job_id = streaming_job_model.job_id;
825                table.id = job_id.as_mv_table_id();
826                if let Some(src) = src {
827                    let src_obj = Self::create_object(
828                        &txn,
829                        ObjectType::Source,
830                        src.owner as _,
831                        Some(job_id.as_object_id()),
832                    )
833                    .await?;
834                    src.id = src_obj.oid.as_source_id();
835                    src.optional_associated_table_id = Some(job_id.as_mv_table_id().into());
836                    table.optional_associated_source_id = Some(src_obj.oid.as_source_id().into());
837                    let source: source::ActiveModel = src.clone().into();
838                    Source::insert(source).exec(&txn).await?;
839                }
840                let table_model: table::ActiveModel = table.clone().into();
841                Table::insert(table_model).exec(&txn).await?;
842
843                if table.refreshable {
844                    let trigger_interval_secs = IngestMode::from_proto(
845                        src.as_ref()
846                            .and_then(|source_catalog| source_catalog.ingest_mode.as_ref()),
847                    )?
848                    .refresh_interval_sec();
849
850                    RefreshJob::insert(refresh_job::ActiveModel {
851                        table_id: Set(table.id),
852                        last_trigger_time: Set(None),
853                        trigger_interval_secs: Set(trigger_interval_secs),
854                        current_status: Set(RefreshState::Idle),
855                        last_success_time: Set(None),
856                    })
857                    .exec(&txn)
858                    .await?;
859                }
860                streaming_job_model
861            }
862            StreamingJob::Index(index, table) => {
863                ensure_object_id(ObjectType::Table, index.primary_table_id, &txn).await?;
864                let streaming_job_model = Self::create_streaming_job_obj(
865                    &txn,
866                    ObjectType::Index,
867                    index.owner as _,
868                    Some(index.schema_id.as_object_id()),
869                    create_type,
870                    ctx.clone(),
871                    adaptive_parallelism_strategy,
872                    streaming_parallelism,
873                    max_parallelism,
874                    resource_type.clone(),
875                    backfill_parallelism.clone(),
876                    backfill_adaptive_parallelism_strategy,
877                    None, // refresh_interval_sec: only for MV
878                )
879                .await?;
880                // to be compatible with old implementation.
881                let job_id = streaming_job_model.job_id;
882                index.id = job_id.as_index_id();
883                index.index_table_id = job_id.as_mv_table_id();
884                table.id = job_id.as_mv_table_id();
885
886                ObjectDependency::insert(object_dependency::ActiveModel {
887                    oid: Set(index.primary_table_id.into()),
888                    used_by: Set(table.id.into()),
889                    ..Default::default()
890                })
891                .exec(&txn)
892                .await?;
893
894                let table_model: table::ActiveModel = table.clone().into();
895                Table::insert(table_model).exec(&txn).await?;
896                let index_model: index::ActiveModel = index.clone().into();
897                Index::insert(index_model).exec(&txn).await?;
898                streaming_job_model
899            }
900            StreamingJob::Source(src) => {
901                let streaming_job_model = Self::create_streaming_job_obj(
902                    &txn,
903                    ObjectType::Source,
904                    src.owner as _,
905                    Some(src.schema_id.as_object_id()),
906                    create_type,
907                    ctx.clone(),
908                    adaptive_parallelism_strategy,
909                    streaming_parallelism,
910                    max_parallelism,
911                    resource_type.clone(),
912                    backfill_parallelism.clone(),
913                    backfill_adaptive_parallelism_strategy,
914                    None, // refresh_interval_sec: only for MV
915                )
916                .await?;
917                src.id = streaming_job_model.job_id.as_shared_source_id();
918                let source_model: source::ActiveModel = src.clone().into();
919                Source::insert(source_model).exec(&txn).await?;
920                streaming_job_model
921            }
922        };
923
924        // collect dependent secrets.
925        dependencies.extend(
926            streaming_job
927                .dependent_secret_ids()?
928                .into_iter()
929                .map(|id| id.as_object_id()),
930        );
931        // collect dependent connection
932        dependencies.extend(
933            streaming_job
934                .dependent_connection_ids()?
935                .into_iter()
936                .map(|id| id.as_object_id()),
937        );
938
939        // record object dependency.
940        if !dependencies.is_empty() {
941            ObjectDependency::insert_many(dependencies.into_iter().map(|oid| {
942                object_dependency::ActiveModel {
943                    oid: Set(oid),
944                    used_by: Set(streaming_job.id().as_object_id()),
945                    ..Default::default()
946                }
947            }))
948            .exec(&txn)
949            .await?;
950        }
951
952        txn.commit().await?;
953
954        Ok(streaming_job_model)
955    }
956
957    /// Create the initial catalogs for internal tables.
958    ///
959    /// Some of the fields in the given "incomplete" internal tables are placeholders, which will
960    /// be updated later in `prepare_streaming_job`. The catalogs become visible to frontend after
961    /// the first barrier is collected in `post_collect_job_fragments`.
962    ///
963    /// Returns a mapping from the temporary table id to the actual global table id.
964    pub async fn create_internal_table_catalog(
965        &self,
966        job: &StreamingJob,
967        mut incomplete_internal_tables: Vec<PbTable>,
968    ) -> MetaResult<HashMap<TableId, TableId>> {
969        let job_id = job.id();
970        let inner = self.inner.write().await;
971        let txn = inner.db.begin().await?;
972
973        // Ensure the job exists.
974        ensure_job_not_canceled(job_id, &txn).await?;
975
976        let mut table_id_map = HashMap::new();
977        for table in &mut incomplete_internal_tables {
978            let table_id = Self::create_object(
979                &txn,
980                ObjectType::Table,
981                table.owner as _,
982                Some(job_id.as_object_id()),
983            )
984            .await?
985            .oid
986            .as_table_id();
987            table_id_map.insert(table.id, table_id);
988            table.id = table_id;
989            table.job_id = Some(job_id);
990
991            let table_model = table::ActiveModel {
992                table_id: Set(table_id),
993                belongs_to_job_id: Set(Some(job_id)),
994                fragment_id: NotSet,
995                ..table.clone().into()
996            };
997            Table::insert(table_model).exec(&txn).await?;
998        }
999        txn.commit().await?;
1000
1001        Ok(table_id_map)
1002    }
1003
1004    pub async fn update_streaming_job_resource_group(
1005        &self,
1006        job_id: JobId,
1007        resource_group: String,
1008    ) -> MetaResult<()> {
1009        let inner = self.inner.write().await;
1010        let txn = inner.db.begin().await?;
1011
1012        ensure_job_not_canceled(job_id, &txn).await?;
1013
1014        let job = streaming_job::ActiveModel {
1015            job_id: Set(job_id),
1016            specific_resource_group: Set(Some(resource_group)),
1017            ..Default::default()
1018        };
1019        StreamingJobModel::update(job).exec(&txn).await?;
1020
1021        txn.commit().await?;
1022
1023        Ok(())
1024    }
1025
1026    pub async fn prepare_stream_job_fragments(
1027        &self,
1028        stream_job_fragments: &StreamJobFragmentsToCreate,
1029        streaming_job: &StreamingJob,
1030        for_replace: bool,
1031        backfill_orders: Option<BackfillOrders>,
1032    ) -> MetaResult<()> {
1033        self.prepare_streaming_job(
1034            stream_job_fragments.stream_job_id(),
1035            || stream_job_fragments.fragments.values(),
1036            &stream_job_fragments.downstreams,
1037            for_replace,
1038            Some(streaming_job),
1039            backfill_orders,
1040        )
1041        .await
1042    }
1043
1044    // TODO: In this function, we also update the `Table` model in the meta store.
1045    // Given that we've ensured the tables inside `TableFragments` are complete, shall we consider
1046    // making them the source of truth and performing a full replacement for those in the meta store?
1047    /// Insert fragments and actors into the meta store. Used both for creating new jobs and
1048    /// replacing jobs. This does not make a new job visible to frontend.
1049    #[await_tree::instrument("prepare_streaming_job_for_{}", if for_replace { "replace" } else { "create" }
1050    )]
1051    pub async fn prepare_streaming_job<'a, I: Iterator<Item = &'a crate::model::Fragment> + 'a>(
1052        &self,
1053        job_id: JobId,
1054        get_fragments: impl Fn() -> I + 'a,
1055        downstreams: &FragmentDownstreamRelation,
1056        for_replace: bool,
1057        creating_streaming_job: Option<&'a StreamingJob>,
1058        backfill_orders: Option<BackfillOrders>,
1059    ) -> MetaResult<()> {
1060        let fragments = Self::prepare_fragment_models_from_fragments(job_id, get_fragments())?;
1061
1062        let inner = self.inner.write().await;
1063
1064        let txn = inner.db.begin().await?;
1065
1066        // Ensure the job exists.
1067        ensure_job_not_canceled(job_id, &txn).await?;
1068
1069        if let Some(backfill_orders) = backfill_orders {
1070            let job = streaming_job::ActiveModel {
1071                job_id: Set(job_id),
1072                backfill_orders: Set(Some(backfill_orders)),
1073                ..Default::default()
1074            };
1075            StreamingJobModel::update(job).exec(&txn).await?;
1076        }
1077
1078        let state_table_ids = fragments
1079            .iter()
1080            .flat_map(|fragment| fragment.state_table_ids.inner_ref().clone())
1081            .collect_vec();
1082
1083        // Collect fragment IDs before consuming `fragments` for serving mapping notification.
1084        let inserted_fragment_ids: Vec<crate::model::FragmentId> = fragments
1085            .iter()
1086            .map(|f| f.fragment_id as crate::model::FragmentId)
1087            .collect();
1088
1089        if !fragments.is_empty() {
1090            let fragment_models = fragments
1091                .into_iter()
1092                .map(|fragment| fragment.into_active_model())
1093                .collect_vec();
1094            Fragment::insert_many(fragment_models).exec(&txn).await?;
1095        }
1096
1097        // Fields including `fragment_id` and `vnode_count` were placeholder values before.
1098        // After table fragments are created, update them for all tables.
1099        if !for_replace {
1100            let all_tables = StreamJobFragments::collect_tables(get_fragments());
1101            for state_table_id in state_table_ids {
1102                // Table's vnode count is not always the fragment's vnode count, so we have to
1103                // look up the table from `TableFragments`.
1104                // See `ActorGraphBuilder::new`.
1105                let table = all_tables
1106                    .get(&state_table_id)
1107                    .unwrap_or_else(|| panic!("table {} not found", state_table_id));
1108                assert_eq!(table.id, state_table_id);
1109                let vnode_count = table.vnode_count();
1110
1111                Table::update(table::ActiveModel {
1112                    table_id: Set(state_table_id as _),
1113                    fragment_id: Set(Some(table.fragment_id)),
1114                    vnode_count: Set(vnode_count as _),
1115                    ..Default::default()
1116                })
1117                .exec(&txn)
1118                .await?;
1119            }
1120        }
1121
1122        insert_fragment_relations(&txn, downstreams).await?;
1123
1124        if !for_replace {
1125            // Update dml fragment id.
1126            if let Some(StreamingJob::Table(_, table, _)) = creating_streaming_job {
1127                Table::update(table::ActiveModel {
1128                    table_id: Set(table.id),
1129                    dml_fragment_id: Set(table.dml_fragment_id),
1130                    ..Default::default()
1131                })
1132                .exec(&txn)
1133                .await?;
1134            }
1135        }
1136
1137        txn.commit().await?;
1138
1139        // Notify serving module about newly inserted fragments so it can establish
1140        // serving vnode mappings. This is driven by the fragment model insertion,
1141        // decoupled from the barrier-driven streaming mapping notifications.
1142        self.env
1143            .notification_manager()
1144            .notify_serving_fragment_mapping_update(inserted_fragment_ids);
1145
1146        self.notify_hummock_table_cache_refill_policy_if_explicit(&inner, job_id)
1147            .await?;
1148
1149        Ok(())
1150    }
1151
1152    /// Tries to abort a creating streaming job.
1153    ///
1154    /// An explicit cancellation always aborts the job. An ordinary creation failure only aborts a
1155    /// job in the initial status; a job that has reached the creating status is left to recovery.
1156    #[await_tree::instrument]
1157    pub async fn try_abort_creating_streaming_job(
1158        &self,
1159        job_id: JobId,
1160        is_cancelled: bool,
1161    ) -> MetaResult<AbortCreatingJobResult> {
1162        let mut inner = self.inner.write().await;
1163        let txn = inner.db.begin().await?;
1164
1165        let obj = Object::find_by_id(job_id).one(&txn).await?;
1166        let Some(obj) = obj else {
1167            tracing::warn!(
1168                id = %job_id,
1169                "streaming job not found when aborting creating, might be cancelled already or cleaned by recovery"
1170            );
1171            return Ok(AbortCreatingJobResult {
1172                aborted: true,
1173                database_id: None,
1174                aborted_sink_ids: vec![],
1175                cancel_info: None,
1176                cross_db_subscriptions: vec![],
1177            });
1178        };
1179        let database_id = obj
1180            .database_id
1181            .ok_or_else(|| anyhow!("obj has no database id: {:?}", obj))?;
1182        let streaming_job = streaming_job::Entity::find_by_id(job_id).one(&txn).await?;
1183
1184        if let Some(streaming_job) = &streaming_job {
1185            if streaming_job.job_status == JobStatus::Created {
1186                tracing::warn!(%job_id, "streaming job is already created, ignore abort request");
1187                return Ok(AbortCreatingJobResult {
1188                    aborted: false,
1189                    database_id: Some(database_id),
1190                    aborted_sink_ids: vec![],
1191                    cancel_info: None,
1192                    cross_db_subscriptions: vec![],
1193                });
1194            }
1195
1196            if !is_cancelled && streaming_job.job_status == JobStatus::Creating {
1197                if (obj.obj_type == ObjectType::Table || obj.obj_type == ObjectType::Sink)
1198                    && check_if_belongs_to_iceberg_table(&txn, job_id).await?
1199                {
1200                    // If the job belongs to an Iceberg table, we still need to clean it.
1201                } else {
1202                    // If the job is created in background and still in creating status, we should
1203                    // not abort it and let recovery handle it.
1204                    tracing::warn!(
1205                        id = %job_id,
1206                        "streaming job is still in creating status"
1207                    );
1208                    return Ok(AbortCreatingJobResult {
1209                        aborted: false,
1210                        database_id: Some(database_id),
1211                        aborted_sink_ids: vec![],
1212                        cancel_info: None,
1213                        cross_db_subscriptions: vec![],
1214                    });
1215                }
1216            }
1217        }
1218
1219        let mut objects_to_abort = vec![obj];
1220        objects_to_abort.extend(get_belong_objects(&txn, job_id.as_object_id()).await?);
1221        let object_ids_to_abort = objects_to_abort
1222            .iter()
1223            .map(|object| object.oid)
1224            .collect_vec();
1225        let streaming_job_ids_to_abort: Vec<JobId> = StreamingJobModel::find()
1226            .select_only()
1227            .column(streaming_job::Column::JobId)
1228            .filter(streaming_job::Column::JobId.is_in(object_ids_to_abort.iter().copied()))
1229            .into_tuple()
1230            .all(&txn)
1231            .await?;
1232        let object_models = load_object_models(&txn, &objects_to_abort).await?;
1233        let cross_db_subscriptions = resolve_cross_db_subscriptions(&txn, &object_models).await?;
1234
1235        let fragments: Vec<(FragmentId, i32, TableIdArray)> = Fragment::find()
1236            .select_only()
1237            .columns([
1238                fragment::Column::FragmentId,
1239                fragment::Column::FragmentTypeMask,
1240                fragment::Column::StateTableIds,
1241            ])
1242            .filter(fragment::Column::JobId.is_in(streaming_job_ids_to_abort.iter().copied()))
1243            .into_tuple()
1244            .all(&txn)
1245            .await?;
1246        let cancel_info = if is_cancelled {
1247            let state_table_ids: HashSet<_> = fragments
1248                .iter()
1249                .flat_map(|(_, _, state_table_ids)| state_table_ids.inner_ref().iter().copied())
1250                .collect();
1251            let sink_fragment_ids = fragments
1252                .iter()
1253                .filter_map(|(fragment_id, fragment_type_mask, _)| {
1254                    FragmentTypeMask::from(*fragment_type_mask)
1255                        .contains(FragmentTypeFlag::Sink)
1256                        .then_some(*fragment_id)
1257                })
1258                .collect_vec();
1259            let sink_target_fragments = fetch_target_fragments(&txn, sink_fragment_ids).await?;
1260            let mut dropped_sink_fragment_by_targets = HashMap::new();
1261            for (sink_fragment, target_fragments) in sink_target_fragments {
1262                if let Some(target_fragment) = target_fragments.first() {
1263                    dropped_sink_fragment_by_targets
1264                        .entry(*target_fragment)
1265                        .or_insert_with(Vec::new)
1266                        .push(sink_fragment);
1267                }
1268            }
1269
1270            Some(CancelStreamingJobInfo {
1271                command: Command::DropStreamingJobs {
1272                    streaming_job_ids: streaming_job_ids_to_abort.iter().copied().collect(),
1273                    unregistered_state_table_ids: state_table_ids.clone(),
1274                    dropped_sink_fragment_by_targets,
1275                },
1276                streaming_job_ids: streaming_job_ids_to_abort.clone(),
1277                state_table_ids: state_table_ids.into_iter().collect(),
1278            })
1279        } else {
1280            None
1281        };
1282
1283        // A job becomes visible to frontend only after it enters the creating status.
1284        let need_notify = streaming_job
1285            .as_ref()
1286            .is_some_and(|job| job.job_status != JobStatus::Initial);
1287
1288        if is_cancelled {
1289            let dropped_tables = object_models.iter().filter_map(|object_info| {
1290                if let PbObjectInfo::Table(table) = object_info {
1291                    Some((table.id, table.clone()))
1292                } else {
1293                    None
1294                }
1295            });
1296            inner.dropped_tables.extend(dropped_tables);
1297        }
1298
1299        let objs = if need_notify {
1300            objects_to_abort
1301                .iter()
1302                .map(|object| PartialObject {
1303                    oid: object.oid,
1304                    obj_type: object.obj_type,
1305                    schema_id: object.schema_id,
1306                    database_id: object.database_id,
1307                })
1308                .collect_vec()
1309        } else {
1310            vec![]
1311        };
1312
1313        // Query fragment IDs before cascade-deleting them, for serving mapping cleanup.
1314        let abort_fragment_ids = fragments
1315            .iter()
1316            .map(|(fragment_id, _, _)| *fragment_id)
1317            .collect_vec();
1318
1319        // Do not walk from an implicit Iceberg sink to its parent table here. The Iceberg table
1320        // creation error path drops the table explicitly, which then cascades to all objects that
1321        // belong to it.
1322        Object::delete_by_id(job_id).exec(&txn).await?;
1323
1324        let err = if is_cancelled {
1325            MetaError::cancelled(format!("streaming job {job_id} is cancelled"))
1326        } else {
1327            MetaError::catalog_id_not_found("stream job", format!("streaming job {job_id} failed"))
1328        };
1329        let abort_reason = format!("streaming job aborted {}", err.as_report());
1330        for aborted_job_id in streaming_job_ids_to_abort {
1331            for tx in inner
1332                .creating_table_finish_notifier
1333                .get_mut(&database_id)
1334                .map(|creating_tables| creating_tables.remove(&aborted_job_id).into_iter())
1335                .into_iter()
1336                .flatten()
1337                .flatten()
1338            {
1339                let _ = tx.send(Err(abort_reason.clone()));
1340            }
1341        }
1342        txn.commit().await?;
1343
1344        // Notify serving module about deleted fragments from the aborted job.
1345        self.env
1346            .notification_manager()
1347            .notify_serving_fragment_mapping_delete(
1348                abort_fragment_ids.iter().map(|id| *id as _).collect(),
1349            );
1350
1351        if !objs.is_empty() {
1352            // We also have notified the frontend about these objects,
1353            // so we need to notify the frontend to delete them here.
1354            let _version = self
1355                .notify_frontend(Operation::Delete, build_object_group_for_delete(objs))
1356                .await;
1357        }
1358        let aborted_sink_ids = objects_to_abort
1359            .iter()
1360            .filter(|object| object.obj_type == ObjectType::Sink)
1361            .map(|object| object.oid.as_sink_id())
1362            .collect();
1363        Ok(AbortCreatingJobResult {
1364            aborted: true,
1365            database_id: Some(database_id),
1366            aborted_sink_ids,
1367            cancel_info,
1368            cross_db_subscriptions,
1369        })
1370    }
1371
1372    async fn build_creating_streaming_job_objects(
1373        txn: &DatabaseTransaction,
1374        job_id: JobId,
1375    ) -> MetaResult<Vec<PbObject>> {
1376        let job_type = Object::find_by_id(job_id)
1377            .select_only()
1378            .column(object::Column::ObjType)
1379            .into_tuple()
1380            .one(txn)
1381            .await?
1382            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", job_id))?;
1383        let streaming_job = StreamingJobModel::find_by_id(job_id)
1384            .one(txn)
1385            .await?
1386            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", job_id))?;
1387
1388        let table_objs = Table::find()
1389            .find_also_related(Object)
1390            .filter(
1391                table::Column::BelongsToJobId
1392                    .eq(job_id)
1393                    .or(table::Column::TableId.eq(job_id.as_mv_table_id())),
1394            )
1395            .all(txn)
1396            .await?;
1397        let associated_source_id = table_objs
1398            .iter()
1399            .find(|(table, _)| table.table_id == job_id.as_mv_table_id())
1400            .and_then(|(table, _)| table.optional_associated_source_id);
1401        let mut objects = table_objs
1402            .into_iter()
1403            .map(|(table, obj)| PbObject {
1404                object_info: Some(PbObjectInfo::Table(
1405                    ObjectModel(table, obj.unwrap(), Some(streaming_job.clone())).into(),
1406                )),
1407            })
1408            .collect_vec();
1409
1410        match job_type {
1411            ObjectType::Table => {
1412                if let Some(source_id) = associated_source_id {
1413                    let (source, obj) = Source::find_by_id(source_id)
1414                        .find_also_related(Object)
1415                        .one(txn)
1416                        .await?
1417                        .ok_or_else(|| MetaError::catalog_id_not_found("source", source_id))?;
1418                    objects.push(PbObject {
1419                        object_info: Some(PbObjectInfo::Source(
1420                            ObjectModel(source, obj.unwrap(), None).into(),
1421                        )),
1422                    });
1423                }
1424            }
1425            ObjectType::Sink => {
1426                let (sink, obj) = Sink::find_by_id(job_id.as_sink_id())
1427                    .find_also_related(Object)
1428                    .one(txn)
1429                    .await?
1430                    .ok_or_else(|| MetaError::catalog_id_not_found("sink", job_id))?;
1431                objects.push(PbObject {
1432                    object_info: Some(PbObjectInfo::Sink(
1433                        ObjectModel(sink, obj.unwrap(), Some(streaming_job)).into(),
1434                    )),
1435                });
1436            }
1437            ObjectType::Index => {
1438                let (index, obj) = Index::find_by_id(job_id.as_index_id())
1439                    .find_also_related(Object)
1440                    .one(txn)
1441                    .await?
1442                    .ok_or_else(|| MetaError::catalog_id_not_found("index", job_id))?;
1443                objects.push(PbObject {
1444                    object_info: Some(PbObjectInfo::Index(
1445                        ObjectModel(index, obj.unwrap(), Some(streaming_job)).into(),
1446                    )),
1447                });
1448            }
1449            ObjectType::Source => {
1450                let (source, obj) = Source::find_by_id(job_id.as_shared_source_id())
1451                    .find_also_related(Object)
1452                    .one(txn)
1453                    .await?
1454                    .ok_or_else(|| MetaError::catalog_id_not_found("source", job_id))?;
1455                objects.push(PbObject {
1456                    object_info: Some(PbObjectInfo::Source(
1457                        ObjectModel(source, obj.unwrap(), None).into(),
1458                    )),
1459                });
1460            }
1461            _ => unreachable!("invalid streaming job type: {job_type:?}"),
1462        }
1463
1464        Ok(objects)
1465    }
1466
1467    /// Mark a job as creating after its first barrier is collected and notify frontend to add its
1468    /// creating catalogs.
1469    #[await_tree::instrument]
1470    pub async fn post_collect_job_fragments(
1471        &self,
1472        job_id: JobId,
1473        upstream_fragment_new_downstreams: &FragmentDownstreamRelation,
1474        new_sink_downstream: Option<FragmentDownstreamRelation>,
1475        split_assignment: Option<&SplitAssignment>,
1476        replace_sink: Option<&SinkId>,
1477        notify_creating: bool,
1478    ) -> MetaResult<Option<Vec<TableId>>> {
1479        let mut inner = self.inner.write().await;
1480        let txn = inner.db.begin().await?;
1481        let mut replace_sink_post_collect = None;
1482
1483        insert_fragment_relations(&txn, upstream_fragment_new_downstreams).await?;
1484
1485        if let Some(new_downstream) = new_sink_downstream {
1486            insert_fragment_relations(&txn, &new_downstream).await?;
1487        }
1488
1489        // Mark job as CREATING.
1490        let mut streaming_job_model = streaming_job::ActiveModel {
1491            job_id: Set(job_id),
1492            job_status: Set(JobStatus::Creating),
1493            ..Default::default()
1494        };
1495        if replace_sink.is_some() {
1496            // The old sink is dropped in this transaction before the replacement job may be
1497            // marked Created by a later barrier. Preserve it across recovery even when the legacy
1498            // option to clean all foreground creating jobs is enabled.
1499            streaming_job_model.create_type = Set(CreateType::Background);
1500        }
1501        StreamingJobModel::update(streaming_job_model)
1502            .exec(&txn)
1503            .await?;
1504
1505        if let Some(split_assignment) = split_assignment {
1506            let fragment_splits = split_assignment
1507                .iter()
1508                .map(|(fragment_id, splits)| {
1509                    (
1510                        *fragment_id as _,
1511                        splits.values().flatten().cloned().collect_vec(),
1512                    )
1513                })
1514                .collect();
1515
1516            self.update_fragment_splits(&txn, &fragment_splits).await?;
1517        }
1518
1519        if let Some(old_sink_id) = replace_sink {
1520            let old_sink_id = *old_sink_id;
1521
1522            let (old_sink, old_sink_object) = Sink::find_by_id(old_sink_id)
1523                .find_also_related(Object)
1524                .one(&txn)
1525                .await?
1526                .and_then(|(sink, object)| object.map(|object| (sink, object)))
1527                .ok_or_else(|| MetaError::catalog_id_not_found("sink", old_sink_id))?;
1528            if old_sink_object.obj_type != ObjectType::Sink {
1529                bail!("object {} is not a sink", old_sink_id);
1530            }
1531            let final_sink_name = old_sink.name.clone();
1532
1533            let mut old_objects_to_delete = vec![old_sink_object];
1534            old_objects_to_delete
1535                .extend(get_belong_objects(&txn, old_sink_id.as_object_id()).await?);
1536            let old_object_models = load_object_models(&txn, &old_objects_to_delete).await?;
1537            let old_state_table_ids = old_object_models
1538                .iter()
1539                .filter_map(|object_info| match object_info {
1540                    PbObjectInfo::Table(table) => Some(table.id),
1541                    _ => None,
1542                })
1543                .collect_vec();
1544            let old_fragment_ids: Vec<FragmentId> = Fragment::find()
1545                .select_only()
1546                .column(fragment::Column::FragmentId)
1547                .filter(
1548                    fragment::Column::JobId.is_in(
1549                        old_objects_to_delete
1550                            .iter()
1551                            .map(|object| object.oid.as_job_id()),
1552                    ),
1553                )
1554                .into_tuple()
1555                .all(&txn)
1556                .await?;
1557            let dropped_tables = old_object_models
1558                .iter()
1559                .filter_map(|object_info| match object_info {
1560                    PbObjectInfo::Table(table) => Some(table.clone()),
1561                    _ => None,
1562                })
1563                .collect_vec();
1564
1565            Sink::update(sink::ActiveModel {
1566                sink_id: Set(job_id.as_sink_id()),
1567                name: Set(final_sink_name),
1568                ..Default::default()
1569            })
1570            .exec(&txn)
1571            .await?;
1572
1573            let old_objects = old_objects_to_delete
1574                .into_iter()
1575                .map(PartialObject::from)
1576                .collect_vec();
1577            let old_object_ids = old_objects.iter().map(|obj| obj.oid).collect_vec();
1578            let updated_user_ids: Vec<UserId> = UserPrivilege::find()
1579                .select_only()
1580                .distinct()
1581                .column(user_privilege::Column::UserId)
1582                .filter(user_privilege::Column::Oid.is_in(old_object_ids.clone()))
1583                .into_tuple()
1584                .all(&txn)
1585                .await?;
1586
1587            // Internal objects and their catalog rows follow the old sink's belong-to cascade.
1588            let res = Object::delete_by_id(old_sink_id).exec(&txn).await?;
1589            if res.rows_affected == 0 {
1590                return Err(MetaError::catalog_id_not_found("sink", old_sink_id));
1591            }
1592
1593            let new_root_object = Object::find_by_id(job_id)
1594                .one(&txn)
1595                .await?
1596                .ok_or_else(|| MetaError::catalog_id_not_found("sink", job_id))?;
1597            let mut new_objects_to_notify = vec![new_root_object];
1598            new_objects_to_notify.extend(get_belong_objects(&txn, job_id.as_object_id()).await?);
1599            let new_objects = load_object_models(&txn, &new_objects_to_notify)
1600                .await?
1601                .into_iter()
1602                .map(|object_info| PbObject {
1603                    object_info: Some(object_info),
1604                })
1605                .collect_vec();
1606            let dependencies =
1607                list_object_dependencies_by_object_id(&txn, job_id.as_object_id()).await?;
1608            let updated_user_info = list_user_info_by_ids(updated_user_ids, &txn).await?;
1609
1610            replace_sink_post_collect = Some((
1611                old_state_table_ids,
1612                old_fragment_ids,
1613                old_objects,
1614                dropped_tables,
1615                new_objects,
1616                dependencies,
1617                updated_user_info,
1618            ));
1619        }
1620
1621        let creating_objects = if notify_creating {
1622            Some(Self::build_creating_streaming_job_objects(&txn, job_id).await?)
1623        } else {
1624            None
1625        };
1626
1627        txn.commit().await?;
1628
1629        let mut notifications = self.frontend_notification_batch();
1630        if let Some(objects) = creating_objects {
1631            notifications.add(
1632                NotificationOperation::Add,
1633                NotificationInfo::ObjectGroup(PbObjectGroup {
1634                    objects,
1635                    dependencies: vec![],
1636                }),
1637            );
1638        }
1639
1640        let Some((
1641            old_state_table_ids,
1642            old_fragment_ids,
1643            old_objects,
1644            dropped_tables,
1645            new_objects,
1646            dependencies,
1647            updated_user_info,
1648        )) = replace_sink_post_collect
1649        else {
1650            if let Some(version) = notifications.publish().await {
1651                tracing::debug!(job_id = %job_id, version, "notified frontend of creating streaming job");
1652            }
1653            return Ok(None);
1654        };
1655
1656        inner
1657            .dropped_tables
1658            .extend(dropped_tables.into_iter().map(|table| (table.id, table)));
1659        drop(inner);
1660
1661        self.env
1662            .notification_manager()
1663            .notify_serving_fragment_mapping_delete(
1664                old_fragment_ids.iter().map(|id| *id as _).collect(),
1665            );
1666
1667        notifications.add(
1668            NotificationOperation::Delete,
1669            build_object_group_for_delete(old_objects),
1670        );
1671
1672        // The replacement sink is not pre-notified to frontend while creating, so the cutover
1673        // should add the new finalized sink after deleting the old one.
1674        notifications.add(
1675            NotificationOperation::Add,
1676            NotificationInfo::ObjectGroup(PbObjectGroup {
1677                objects: new_objects,
1678                dependencies,
1679            }),
1680        );
1681
1682        Self::add_users_update_notifications(&mut notifications, updated_user_info);
1683        let version = notifications
1684            .publish()
1685            .await
1686            .expect("the replacement notification batch contains the replacement sink");
1687        tracing::debug!(job_id = %job_id, version, "notified frontend of replacement streaming job");
1688
1689        Ok(Some(old_state_table_ids))
1690    }
1691
1692    pub async fn create_job_catalog_for_replace(
1693        &self,
1694        streaming_job: &StreamingJob,
1695        ctx: Option<&StreamContext>,
1696        specified_parallelism: Option<&NonZeroUsize>,
1697        expected_original_max_parallelism: Option<usize>,
1698    ) -> MetaResult<streaming_job::Model> {
1699        let id = streaming_job.id();
1700        let inner = self.inner.write().await;
1701        let txn = inner.db.begin().await?;
1702
1703        // 1. check version.
1704        streaming_job.verify_version_for_replace(&txn).await?;
1705        // 2. check concurrent replace.
1706        let referring_objects =
1707            get_referring_objects(id.as_object_id(), streaming_job.object_type(), &txn).await?;
1708        let referring_job_ids = referring_objects
1709            .iter()
1710            .map(|object| object.oid.as_job_id())
1711            .collect_vec();
1712        let non_created_referring_job_count = StreamingJobModel::find()
1713            .filter(
1714                streaming_job::Column::JobId
1715                    .is_in(referring_job_ids)
1716                    .and(streaming_job::Column::JobStatus.ne(JobStatus::Created)),
1717            )
1718            .count(&txn)
1719            .await?;
1720        if non_created_referring_job_count != 0 {
1721            return Err(MetaError::permission_denied(
1722                "job is being altered or referenced by some creating jobs",
1723            ));
1724        }
1725
1726        // Check if any dependent job is a batch refresh job.
1727        // Replace table is not supported when a batch refresh MV depends on it.
1728        let batch_refresh_dep_cnt = ObjectDependency::find()
1729            .join(
1730                JoinType::InnerJoin,
1731                object_dependency::Relation::Object1.def(),
1732            )
1733            .join(JoinType::InnerJoin, object::Relation::StreamingJob.def())
1734            .filter(
1735                object_dependency::Column::Oid
1736                    .eq(id)
1737                    .and(streaming_job::Column::RefreshIntervalSec.is_not_null()),
1738            )
1739            .count(&txn)
1740            .await?;
1741        if batch_refresh_dep_cnt != 0 {
1742            return Err(MetaError::permission_denied(
1743                "replacing a table with dependent batch refresh materialized views is not supported",
1744            ));
1745        }
1746
1747        // 3. check parallelism.
1748        let original_job = StreamingJobModel::find_by_id(id)
1749            .one(&txn)
1750            .await?
1751            .map(ReplaceOriginalJobInfo::from)
1752            .ok_or_else(|| MetaError::catalog_id_not_found(streaming_job.job_type_str(), id))?;
1753
1754        if let Some(max_parallelism) = expected_original_max_parallelism
1755            && original_job.max_parallelism != max_parallelism as i32
1756        {
1757            // We already override the max parallelism in `StreamFragmentGraph` before entering this function.
1758            // This should not happen in normal cases.
1759            bail!(
1760                "cannot use a different max parallelism \
1761                 when replacing streaming job, \
1762                 original: {}, new: {}",
1763                original_job.max_parallelism,
1764                max_parallelism
1765            );
1766        }
1767
1768        let parallelism = original_job.resolved_parallelism(specified_parallelism);
1769        let ctx = original_job.stream_context(ctx);
1770        let adaptive_parallelism_strategy = original_job
1771            .adaptive_parallelism_strategy
1772            .as_deref()
1773            .map(|s| parse_strategy(s).expect("strategy should be validated before persisting"));
1774        let resource_type = original_job.resource_type();
1775        let belong_to_oid = Object::find_by_id(id)
1776            .select_only()
1777            .column(object::Column::BelongToOid)
1778            .into_tuple::<Option<ObjectId>>()
1779            .one(&txn)
1780            .await?
1781            .ok_or_else(|| MetaError::catalog_id_not_found(streaming_job.job_type_str(), id))?;
1782
1783        // 4. create streaming object for new replace table.
1784        let tmp_model = Self::create_streaming_job_obj(
1785            &txn,
1786            streaming_job.object_type(),
1787            streaming_job.owner() as _,
1788            belong_to_oid,
1789            streaming_job.create_type(),
1790            ctx,
1791            adaptive_parallelism_strategy,
1792            parallelism,
1793            original_job.max_parallelism as _,
1794            resource_type,
1795            // `backfill_parallelism` is intentionally NOT inherited from the original job.
1796            // Replace has no "backfill finish -> restore parallelism" phase, so inheriting it
1797            // would render actors at the backfill parallelism and never recover to steady-state.
1798            None,
1799            None,
1800            None, // refresh_interval_sec: not applicable for replace jobs
1801        )
1802        .await?;
1803
1804        // 5. record dependency for new replace table.
1805        ObjectDependency::insert(object_dependency::ActiveModel {
1806            oid: Set(id.as_object_id()),
1807            used_by: Set(tmp_model.job_id.as_object_id()),
1808            ..Default::default()
1809        })
1810        .exec(&txn)
1811        .await?;
1812
1813        txn.commit().await?;
1814
1815        Ok(tmp_model)
1816    }
1817
1818    /// `finish_streaming_job` marks job related objects as `Created` and notify frontend.
1819    pub async fn finish_streaming_job(&self, job_id: JobId) -> MetaResult<()> {
1820        let mut inner = self.inner.write().await;
1821        let txn = inner.db.begin().await?;
1822
1823        // Check if the job belongs to iceberg table.
1824        if check_if_belongs_to_iceberg_table(&txn, job_id).await? {
1825            tracing::info!(
1826                "streaming job {} is for iceberg table, wait for manual finish operation",
1827                job_id
1828            );
1829            return Ok(());
1830        }
1831
1832        let (notification_op, objects, updated_user_info, dependencies) =
1833            self.finish_streaming_job_inner(&txn, job_id).await?;
1834
1835        txn.commit().await?;
1836
1837        let mut notifications = self.frontend_notification_batch();
1838        notifications.add(
1839            notification_op,
1840            NotificationInfo::ObjectGroup(PbObjectGroup {
1841                objects,
1842                dependencies,
1843            }),
1844        );
1845
1846        // notify users about the default privileges
1847        Self::add_users_update_notifications(&mut notifications, updated_user_info);
1848        let version = notifications
1849            .publish()
1850            .await
1851            .expect("the streaming job notification batch contains the streaming job");
1852
1853        inner
1854            .creating_table_finish_notifier
1855            .values_mut()
1856            .for_each(|creating_tables| {
1857                if let Some(txs) = creating_tables.remove(&job_id) {
1858                    for tx in txs {
1859                        let _ = tx.send(Ok(version));
1860                    }
1861                }
1862            });
1863
1864        Ok(())
1865    }
1866
1867    /// `finish_streaming_job` marks job related objects as `Created` and notify frontend.
1868    pub async fn finish_streaming_job_inner(
1869        &self,
1870        txn: &DatabaseTransaction,
1871        job_id: JobId,
1872    ) -> MetaResult<(
1873        Operation,
1874        Vec<risingwave_pb::meta::Object>,
1875        Vec<PbUserInfo>,
1876        Vec<PbObjectDependency>,
1877    )> {
1878        let job_type = Object::find_by_id(job_id)
1879            .select_only()
1880            .column(object::Column::ObjType)
1881            .into_tuple()
1882            .one(txn)
1883            .await?
1884            .ok_or_else(|| MetaError::catalog_id_not_found("streaming job", job_id))?;
1885
1886        // update `created_at` as now() and `created_at_cluster_version` as current cluster version.
1887        let res = Object::update_many()
1888            .col_expr(object::Column::CreatedAt, Expr::current_timestamp().into())
1889            .col_expr(
1890                object::Column::CreatedAtClusterVersion,
1891                current_cluster_version().into(),
1892            )
1893            .filter(object::Column::Oid.eq(job_id))
1894            .exec(txn)
1895            .await?;
1896        if res.rows_affected == 0 {
1897            return Err(MetaError::catalog_id_not_found("streaming job", job_id));
1898        }
1899
1900        // mark the target stream job as `Created`.
1901        let job = streaming_job::ActiveModel {
1902            job_id: Set(job_id),
1903            job_status: Set(JobStatus::Created),
1904            ..Default::default()
1905        };
1906        let streaming_job = Some(job.update(txn).await?);
1907
1908        // notify frontend: job, internal tables.
1909        let internal_table_objs = Table::find()
1910            .find_also_related(Object)
1911            .filter(table::Column::BelongsToJobId.eq(job_id))
1912            .all(txn)
1913            .await?;
1914        let mut objects = internal_table_objs
1915            .iter()
1916            .map(|(table, obj)| PbObject {
1917                object_info: Some(PbObjectInfo::Table(
1918                    ObjectModel(table.clone(), obj.clone().unwrap(), streaming_job.clone()).into(),
1919                )),
1920            })
1921            .collect_vec();
1922        let notification_op = NotificationOperation::Update;
1923        let mut updated_user_info = vec![];
1924        let mut need_grant_default_privileges = true;
1925
1926        match job_type {
1927            ObjectType::Table => {
1928                let (table, obj) = Table::find_by_id(job_id.as_mv_table_id())
1929                    .find_also_related(Object)
1930                    .one(txn)
1931                    .await?
1932                    .ok_or_else(|| MetaError::catalog_id_not_found("table", job_id))?;
1933                if let Some(source_id) = table.optional_associated_source_id {
1934                    let (src, obj) = Source::find_by_id(source_id)
1935                        .find_also_related(Object)
1936                        .one(txn)
1937                        .await?
1938                        .ok_or_else(|| MetaError::catalog_id_not_found("source", source_id))?;
1939                    objects.push(PbObject {
1940                        object_info: Some(PbObjectInfo::Source(
1941                            ObjectModel(src, obj.unwrap(), None).into(),
1942                        )),
1943                    });
1944                }
1945                objects.push(PbObject {
1946                    object_info: Some(PbObjectInfo::Table(
1947                        ObjectModel(table, obj.unwrap(), streaming_job).into(),
1948                    )),
1949                });
1950            }
1951            ObjectType::Sink => {
1952                let (sink, obj) = Sink::find_by_id(job_id.as_sink_id())
1953                    .find_also_related(Object)
1954                    .one(txn)
1955                    .await?
1956                    .ok_or_else(|| MetaError::catalog_id_not_found("sink", job_id))?;
1957                if sink.name.starts_with(ICEBERG_SINK_PREFIX) {
1958                    need_grant_default_privileges = false;
1959                }
1960                objects.push(PbObject {
1961                    object_info: Some(PbObjectInfo::Sink(
1962                        ObjectModel(sink, obj.unwrap(), streaming_job).into(),
1963                    )),
1964                });
1965            }
1966            ObjectType::Index => {
1967                need_grant_default_privileges = false;
1968                let (index, obj) = Index::find_by_id(job_id.as_index_id())
1969                    .find_also_related(Object)
1970                    .one(txn)
1971                    .await?
1972                    .ok_or_else(|| MetaError::catalog_id_not_found("index", job_id))?;
1973                {
1974                    let (table, obj) = Table::find_by_id(index.index_table_id)
1975                        .find_also_related(Object)
1976                        .one(txn)
1977                        .await?
1978                        .ok_or_else(|| {
1979                            MetaError::catalog_id_not_found("table", index.index_table_id)
1980                        })?;
1981                    objects.push(PbObject {
1982                        object_info: Some(PbObjectInfo::Table(
1983                            ObjectModel(table, obj.unwrap(), streaming_job.clone()).into(),
1984                        )),
1985                    });
1986                }
1987
1988                // If the index is created on a table with privileges, we should also
1989                // grant the privileges for the index and its state tables.
1990                let primary_table_privileges = UserPrivilege::find()
1991                    .filter(
1992                        user_privilege::Column::Oid
1993                            .eq(index.primary_table_id)
1994                            .and(user_privilege::Column::Action.eq(Action::Select)),
1995                    )
1996                    .all(txn)
1997                    .await?;
1998                if !primary_table_privileges.is_empty() {
1999                    let index_state_table_ids: Vec<TableId> = Table::find()
2000                        .select_only()
2001                        .column(table::Column::TableId)
2002                        .filter(
2003                            table::Column::BelongsToJobId
2004                                .eq(job_id)
2005                                .or(table::Column::TableId.eq(index.index_table_id)),
2006                        )
2007                        .into_tuple()
2008                        .all(txn)
2009                        .await?;
2010                    let mut new_privileges = vec![];
2011                    for privilege in &primary_table_privileges {
2012                        for state_table_id in &index_state_table_ids {
2013                            new_privileges.push(user_privilege::ActiveModel {
2014                                id: Default::default(),
2015                                oid: Set(state_table_id.as_object_id()),
2016                                user_id: Set(privilege.user_id),
2017                                action: Set(Action::Select),
2018                                dependent_id: Set(privilege.dependent_id),
2019                                granted_by: Set(privilege.granted_by),
2020                                with_grant_option: Set(privilege.with_grant_option),
2021                            });
2022                        }
2023                    }
2024                    upsert_user_privileges(txn, new_privileges).await?;
2025
2026                    updated_user_info = list_user_info_by_ids(
2027                        primary_table_privileges.into_iter().map(|p| p.user_id),
2028                        txn,
2029                    )
2030                    .await?;
2031                }
2032
2033                objects.push(PbObject {
2034                    object_info: Some(PbObjectInfo::Index(
2035                        ObjectModel(index, obj.unwrap(), streaming_job).into(),
2036                    )),
2037                });
2038            }
2039            ObjectType::Source => {
2040                let (source, obj) = Source::find_by_id(job_id.as_shared_source_id())
2041                    .find_also_related(Object)
2042                    .one(txn)
2043                    .await?
2044                    .ok_or_else(|| MetaError::catalog_id_not_found("source", job_id))?;
2045                objects.push(PbObject {
2046                    object_info: Some(PbObjectInfo::Source(
2047                        ObjectModel(source, obj.unwrap(), None).into(),
2048                    )),
2049                });
2050            }
2051            _ => unreachable!("invalid job type: {:?}", job_type),
2052        }
2053
2054        if need_grant_default_privileges {
2055            updated_user_info = grant_default_privileges_automatically(txn, job_id).await?;
2056        }
2057
2058        let dependencies =
2059            list_object_dependencies_by_object_id(txn, job_id.as_object_id()).await?;
2060
2061        Ok((notification_op, objects, updated_user_info, dependencies))
2062    }
2063
2064    pub async fn finish_replace_streaming_job(
2065        &self,
2066        tmp_id: JobId,
2067        streaming_job: StreamingJob,
2068        replace_upstream: FragmentReplaceUpstream,
2069        sink_into_table_context: SinkIntoTableContext,
2070        drop_table_connector_ctx: Option<&DropTableConnectorContext>,
2071        auto_refresh_schema_sinks: Option<Vec<FinishAutoRefreshSchemaSinkContext>>,
2072    ) -> MetaResult<NotificationVersion> {
2073        let inner = self.inner.write().await;
2074        let txn = inner.db.begin().await?;
2075
2076        let (objects, delete_notification_objs, old_fragment_ids, new_fragment_ids) =
2077            Self::finish_replace_streaming_job_inner(
2078                tmp_id,
2079                replace_upstream,
2080                sink_into_table_context,
2081                &txn,
2082                streaming_job,
2083                drop_table_connector_ctx,
2084                auto_refresh_schema_sinks,
2085            )
2086            .await?;
2087
2088        txn.commit().await?;
2089
2090        // Notify serving module: delete old fragment mappings, upsert new ones.
2091        let notification_manager = self.env.notification_manager();
2092        notification_manager.notify_serving_fragment_mapping_delete(
2093            old_fragment_ids.iter().map(|id| *id as _).collect(),
2094        );
2095        notification_manager.notify_serving_fragment_mapping_update(
2096            new_fragment_ids.iter().map(|id| *id as _).collect(),
2097        );
2098
2099        let mut notifications = self.frontend_notification_batch();
2100        notifications.add(
2101            NotificationOperation::Update,
2102            NotificationInfo::ObjectGroup(PbObjectGroup {
2103                objects,
2104                dependencies: vec![],
2105            }),
2106        );
2107
2108        if let Some((user_infos, to_drop_objects)) = delete_notification_objs {
2109            Self::add_users_update_notifications(&mut notifications, user_infos);
2110            notifications.add(
2111                NotificationOperation::Delete,
2112                build_object_group_for_delete(to_drop_objects),
2113            );
2114        }
2115        let version = notifications
2116            .publish()
2117            .await
2118            .expect("the replacement notification batch contains the updated object");
2119
2120        Ok(version)
2121    }
2122
2123    fn update_iceberg_source_columns(
2124        original_source_columns: &[ColumnCatalog],
2125        original_row_id_index: Option<usize>,
2126        new_table_columns: &[ColumnCatalog],
2127    ) -> (Vec<ColumnCatalog>, Option<usize>) {
2128        let row_id_column_name = original_row_id_index
2129            .and_then(|idx| original_source_columns.get(idx))
2130            .map(|col| col.name().to_owned());
2131        let mut next_column_id = max_column_id(original_source_columns).next();
2132        let existing_columns: HashMap<String, ColumnCatalog> = original_source_columns
2133            .iter()
2134            .cloned()
2135            .map(|col| (col.name().to_owned(), col))
2136            .collect();
2137
2138        let mut new_columns = Vec::new();
2139        for table_col in new_table_columns
2140            .iter()
2141            .filter(|col| !col.is_rw_sys_column())
2142        {
2143            let mut source_col_name = table_col.name().to_owned();
2144            if source_col_name == ROW_ID_COLUMN_NAME {
2145                source_col_name = RISINGWAVE_ICEBERG_ROW_ID.to_owned();
2146            }
2147
2148            if let Some(existing) = existing_columns.get(&source_col_name) {
2149                new_columns.push(existing.clone());
2150            } else {
2151                let mut new_col = table_col.clone();
2152                new_col.column_desc.name = source_col_name;
2153                new_col.column_desc.column_id = next_column_id;
2154                next_column_id = next_column_id.next();
2155                new_columns.push(new_col);
2156            }
2157        }
2158
2159        let mut seen_names: HashSet<String> = new_columns
2160            .iter()
2161            .map(|col| col.name().to_owned())
2162            .collect();
2163        for col in original_source_columns
2164            .iter()
2165            .filter(|col| col.is_iceberg_hidden_column())
2166        {
2167            if seen_names.insert(col.name().to_owned()) {
2168                new_columns.push(col.clone());
2169            }
2170        }
2171
2172        let new_row_id_index = row_id_column_name
2173            .as_ref()
2174            .and_then(|name| new_columns.iter().position(|col| col.name() == name));
2175
2176        (new_columns, new_row_id_index)
2177    }
2178
2179    pub async fn finish_replace_streaming_job_inner(
2180        tmp_id: JobId,
2181        replace_upstream: FragmentReplaceUpstream,
2182        SinkIntoTableContext {
2183            updated_sink_catalogs,
2184        }: SinkIntoTableContext,
2185        txn: &DatabaseTransaction,
2186        streaming_job: StreamingJob,
2187        drop_table_connector_ctx: Option<&DropTableConnectorContext>,
2188        auto_refresh_schema_sinks: Option<Vec<FinishAutoRefreshSchemaSinkContext>>,
2189    ) -> MetaResult<(
2190        Vec<PbObject>,
2191        Option<(Vec<PbUserInfo>, Vec<PartialObject>)>,
2192        Vec<FragmentId>,
2193        Vec<FragmentId>,
2194    )> {
2195        let original_job_id = streaming_job.id();
2196        let job_type = streaming_job.job_type();
2197
2198        // Query old fragment IDs (will be deleted) and new fragment IDs (will be reassigned).
2199        let old_fragment_ids: Vec<FragmentId> = Fragment::find()
2200            .select_only()
2201            .column(fragment::Column::FragmentId)
2202            .filter(fragment::Column::JobId.eq(original_job_id))
2203            .into_tuple()
2204            .all(txn)
2205            .await?;
2206        let new_fragment_ids: Vec<FragmentId> = Fragment::find()
2207            .select_only()
2208            .column(fragment::Column::FragmentId)
2209            .filter(fragment::Column::JobId.eq(tmp_id))
2210            .into_tuple()
2211            .all(txn)
2212            .await?;
2213
2214        let mut index_item_rewriter = None;
2215        let mut updated_iceberg_source_id: Option<SourceId> = None;
2216
2217        // Update catalog
2218        match streaming_job {
2219            StreamingJob::Table(_, table, _table_job_type) => {
2220                let original_column_catalogs =
2221                    get_table_columns(txn, original_job_id.as_mv_table_id()).await?;
2222                let schema_changed = original_column_catalogs.to_protobuf() != table.columns;
2223                let is_iceberg = table
2224                    .engine
2225                    .and_then(|engine| PbEngine::try_from(engine).ok())
2226                    == Some(PbEngine::Iceberg);
2227                if is_iceberg && schema_changed {
2228                    let iceberg_source_name = format!("{}{}", ICEBERG_SOURCE_PREFIX, table.name);
2229                    let source = Source::find()
2230                        .inner_join(Object)
2231                        .filter(
2232                            object::Column::DatabaseId
2233                                .eq(table.database_id)
2234                                .and(object::Column::SchemaId.eq(table.schema_id))
2235                                .and(source::Column::Name.eq(&iceberg_source_name)),
2236                        )
2237                        .one(txn)
2238                        .await?
2239                        .ok_or_else(|| {
2240                            MetaError::catalog_id_not_found("source", iceberg_source_name)
2241                        })?;
2242
2243                    let source_id = source.source_id;
2244                    let source_version = source.version;
2245                    let source_columns: Vec<ColumnCatalog> = source
2246                        .columns
2247                        .to_protobuf()
2248                        .into_iter()
2249                        .map(ColumnCatalog::from)
2250                        .collect();
2251                    let source_row_id_index = source
2252                        .row_id_index
2253                        .and_then(|idx| usize::try_from(idx).ok());
2254                    let table_columns: Vec<ColumnCatalog> = table
2255                        .columns
2256                        .iter()
2257                        .cloned()
2258                        .map(ColumnCatalog::from)
2259                        .collect();
2260                    let (updated_columns, updated_row_id_index) =
2261                        Self::update_iceberg_source_columns(
2262                            &source_columns,
2263                            source_row_id_index,
2264                            &table_columns,
2265                        );
2266                    let updated_columns: Vec<PbColumnCatalog> = updated_columns
2267                        .into_iter()
2268                        .map(|col| col.to_protobuf())
2269                        .collect();
2270
2271                    let mut source_active = source.into_active_model();
2272                    source_active.columns = Set(ColumnCatalogArray::from(updated_columns));
2273                    source_active.row_id_index = Set(updated_row_id_index.map(|idx| idx as i32));
2274                    source_active.version = Set(source_version + 1);
2275                    source_active.update(txn).await?;
2276                    updated_iceberg_source_id = Some(source_id);
2277                }
2278
2279                index_item_rewriter = Some({
2280                    let original_columns = original_column_catalogs
2281                        .to_protobuf()
2282                        .into_iter()
2283                        .map(|c| c.column_desc.unwrap())
2284                        .collect_vec();
2285                    let new_columns = table
2286                        .columns
2287                        .iter()
2288                        .map(|c| c.column_desc.clone().unwrap())
2289                        .collect_vec();
2290
2291                    IndexItemRewriter {
2292                        original_columns,
2293                        new_columns,
2294                    }
2295                });
2296
2297                // For sinks created in earlier versions, we need to set the original_target_columns.
2298                for sink_id in updated_sink_catalogs {
2299                    Sink::update(sink::ActiveModel {
2300                        sink_id: Set(sink_id as _),
2301                        original_target_columns: Set(Some(original_column_catalogs.clone())),
2302                        ..Default::default()
2303                    })
2304                    .exec(txn)
2305                    .await?;
2306                }
2307                // Update the table catalog with the new one. (column catalog is also updated here)
2308                let mut table = table::ActiveModel::from(table);
2309                if let Some(drop_table_connector_ctx) = drop_table_connector_ctx
2310                    && drop_table_connector_ctx.to_change_streaming_job_id == original_job_id
2311                {
2312                    // drop table connector, the rest logic is in `drop_table_associated_source`
2313                    table.optional_associated_source_id = Set(None);
2314                }
2315
2316                Table::update(table).exec(txn).await?;
2317            }
2318            StreamingJob::Source(source) => {
2319                // Update the source catalog with the new one.
2320                let source = source::ActiveModel::from(source);
2321                Source::update(source).exec(txn).await?;
2322            }
2323            StreamingJob::MaterializedView(table) => {
2324                // Update the table catalog with the new one.
2325                let table = table::ActiveModel::from(table);
2326                Table::update(table).exec(txn).await?;
2327            }
2328            _ => unreachable!(
2329                "invalid streaming job type: {:?}",
2330                streaming_job.job_type_str()
2331            ),
2332        }
2333
2334        async fn finish_fragments(
2335            txn: &DatabaseTransaction,
2336            tmp_id: JobId,
2337            original_job_id: JobId,
2338            replace_upstream: FragmentReplaceUpstream,
2339        ) -> MetaResult<()> {
2340            // 0. update internal tables
2341            // Fields including `fragment_id` were placeholder values before.
2342            // After table fragments are created, update them for all internal tables.
2343            let fragment_info: Vec<(FragmentId, I32Array)> = Fragment::find()
2344                .select_only()
2345                .columns([
2346                    fragment::Column::FragmentId,
2347                    fragment::Column::StateTableIds,
2348                ])
2349                .filter(fragment::Column::JobId.eq(tmp_id))
2350                .into_tuple()
2351                .all(txn)
2352                .await?;
2353            for (fragment_id, state_table_ids) in fragment_info {
2354                for state_table_id in state_table_ids.into_inner() {
2355                    let state_table_id = TableId::new(state_table_id as _);
2356                    Table::update(table::ActiveModel {
2357                        table_id: Set(state_table_id),
2358                        fragment_id: Set(Some(fragment_id)),
2359                        // No need to update `vnode_count` because it must remain the same.
2360                        ..Default::default()
2361                    })
2362                    .exec(txn)
2363                    .await?;
2364                }
2365            }
2366
2367            // 1. replace old fragments/actors with new ones.
2368            Fragment::delete_many()
2369                .filter(fragment::Column::JobId.eq(original_job_id))
2370                .exec(txn)
2371                .await?;
2372            Fragment::update_many()
2373                .col_expr(fragment::Column::JobId, SimpleExpr::from(original_job_id))
2374                .filter(fragment::Column::JobId.eq(tmp_id))
2375                .exec(txn)
2376                .await?;
2377
2378            // 2. update merges.
2379            // update downstream fragment's Merge node, and upstream_fragment_id
2380            for (fragment_id, fragment_replace_map) in replace_upstream {
2381                let (fragment_id, mut stream_node) =
2382                    Fragment::find_by_id(fragment_id as FragmentId)
2383                        .select_only()
2384                        .columns([fragment::Column::FragmentId, fragment::Column::StreamNode])
2385                        .into_tuple::<(FragmentId, StreamNode)>()
2386                        .one(txn)
2387                        .await?
2388                        .map(|(id, node)| (id, node.to_protobuf()))
2389                        .ok_or_else(|| MetaError::catalog_id_not_found("fragment", fragment_id))?;
2390
2391                visit_stream_node_mut(&mut stream_node, |body| {
2392                    if let PbNodeBody::Merge(m) = body
2393                        && let Some(new_fragment_id) =
2394                            fragment_replace_map.get(&m.upstream_fragment_id)
2395                    {
2396                        m.upstream_fragment_id = *new_fragment_id;
2397                    }
2398                });
2399                Fragment::update(fragment::ActiveModel {
2400                    fragment_id: Set(fragment_id),
2401                    stream_node: Set(StreamNode::from(&stream_node)),
2402                    ..Default::default()
2403                })
2404                .exec(txn)
2405                .await?;
2406            }
2407
2408            // 3. remove dummy object.
2409            Object::delete_by_id(tmp_id).exec(txn).await?;
2410
2411            Ok(())
2412        }
2413
2414        finish_fragments(txn, tmp_id, original_job_id, replace_upstream).await?;
2415
2416        // 4. update catalogs and notify.
2417        let mut objects = vec![];
2418        match job_type {
2419            StreamingJobType::Table(_) | StreamingJobType::MaterializedView => {
2420                let (table, table_obj) = Table::find_by_id(original_job_id.as_mv_table_id())
2421                    .find_also_related(Object)
2422                    .one(txn)
2423                    .await?
2424                    .ok_or_else(|| MetaError::catalog_id_not_found("object", original_job_id))?;
2425                let streaming_job = streaming_job::Entity::find_by_id(table.job_id())
2426                    .one(txn)
2427                    .await?;
2428                objects.push(PbObject {
2429                    object_info: Some(PbObjectInfo::Table(
2430                        ObjectModel(table, table_obj.unwrap(), streaming_job).into(),
2431                    )),
2432                })
2433            }
2434            StreamingJobType::Source => {
2435                let (source, source_obj) =
2436                    Source::find_by_id(original_job_id.as_shared_source_id())
2437                        .find_also_related(Object)
2438                        .one(txn)
2439                        .await?
2440                        .ok_or_else(|| {
2441                            MetaError::catalog_id_not_found("object", original_job_id)
2442                        })?;
2443                objects.push(PbObject {
2444                    object_info: Some(PbObjectInfo::Source(
2445                        ObjectModel(source, source_obj.unwrap(), None).into(),
2446                    )),
2447                })
2448            }
2449            _ => unreachable!("invalid streaming job type for replace: {:?}", job_type),
2450        }
2451
2452        if let Some(source_id) = updated_iceberg_source_id {
2453            let (source, source_obj) = Source::find_by_id(source_id)
2454                .find_also_related(Object)
2455                .one(txn)
2456                .await?
2457                .ok_or_else(|| MetaError::catalog_id_not_found("source", source_id))?;
2458            objects.push(PbObject {
2459                object_info: Some(PbObjectInfo::Source(
2460                    ObjectModel(source, source_obj.unwrap(), None).into(),
2461                )),
2462            });
2463        }
2464
2465        if let Some(expr_rewriter) = index_item_rewriter {
2466            let index_items: Vec<(IndexId, ExprNodeArray)> = Index::find()
2467                .select_only()
2468                .columns([index::Column::IndexId, index::Column::IndexItems])
2469                .filter(index::Column::PrimaryTableId.eq(original_job_id))
2470                .into_tuple()
2471                .all(txn)
2472                .await?;
2473            for (index_id, nodes) in index_items {
2474                let mut pb_nodes = nodes.to_protobuf();
2475                pb_nodes
2476                    .iter_mut()
2477                    .for_each(|x| expr_rewriter.rewrite_expr(x));
2478                let index = index::ActiveModel {
2479                    index_id: Set(index_id),
2480                    index_items: Set(pb_nodes.into()),
2481                    ..Default::default()
2482                }
2483                .update(txn)
2484                .await?;
2485                let (index_obj, streaming_job) = Object::find_by_id(index.index_id)
2486                    .find_also_related(streaming_job::Entity)
2487                    .one(txn)
2488                    .await?
2489                    .ok_or_else(|| MetaError::catalog_id_not_found("object", index.index_id))?;
2490                objects.push(PbObject {
2491                    object_info: Some(PbObjectInfo::Index(
2492                        ObjectModel(index, index_obj, streaming_job).into(),
2493                    )),
2494                });
2495            }
2496        }
2497
2498        if let Some(sinks) = auto_refresh_schema_sinks {
2499            for finish_sink_context in sinks {
2500                finish_fragments(
2501                    txn,
2502                    finish_sink_context.tmp_sink_id.as_job_id(),
2503                    finish_sink_context.original_sink_id.as_job_id(),
2504                    Default::default(),
2505                )
2506                .await?;
2507                let (mut sink, sink_obj) = Sink::find_by_id(finish_sink_context.original_sink_id)
2508                    .find_also_related(Object)
2509                    .one(txn)
2510                    .await?
2511                    .ok_or_else(|| MetaError::catalog_id_not_found("sink", original_job_id))?;
2512                let sink_streaming_job =
2513                    streaming_job::Entity::find_by_id(sink.sink_id.as_job_id())
2514                        .one(txn)
2515                        .await?;
2516                let columns = ColumnCatalogArray::from(finish_sink_context.columns);
2517                Sink::update(sink::ActiveModel {
2518                    sink_id: Set(finish_sink_context.original_sink_id),
2519                    columns: Set(columns.clone()),
2520                    ..Default::default()
2521                })
2522                .exec(txn)
2523                .await?;
2524                sink.columns = columns;
2525                objects.push(PbObject {
2526                    object_info: Some(PbObjectInfo::Sink(
2527                        ObjectModel(sink, sink_obj.unwrap(), sink_streaming_job.clone()).into(),
2528                    )),
2529                });
2530                if let Some(new_log_store_table) = finish_sink_context.new_log_store_table {
2531                    let log_store_table_id = new_log_store_table.id;
2532                    let new_log_store_table_columns: ColumnCatalogArray =
2533                        new_log_store_table.columns.clone().into();
2534                    let new_log_store_table_value_indices =
2535                        new_log_store_table.value_indices.clone();
2536                    let (mut table, table_obj) = Table::find_by_id(log_store_table_id)
2537                        .find_also_related(Object)
2538                        .one(txn)
2539                        .await?
2540                        .ok_or_else(|| MetaError::catalog_id_not_found("table", original_job_id))?;
2541                    Table::update(table::ActiveModel {
2542                        table_id: Set(log_store_table_id),
2543                        columns: Set(new_log_store_table_columns.clone()),
2544                        value_indices: Set(new_log_store_table_value_indices.clone().into()),
2545                        ..Default::default()
2546                    })
2547                    .exec(txn)
2548                    .await?;
2549                    table.columns = new_log_store_table_columns;
2550                    table.value_indices = new_log_store_table_value_indices.into();
2551                    objects.push(PbObject {
2552                        object_info: Some(PbObjectInfo::Table(
2553                            ObjectModel(table, table_obj.unwrap(), sink_streaming_job.clone())
2554                                .into(),
2555                        )),
2556                    });
2557                }
2558            }
2559        }
2560
2561        let mut notification_objs: Option<(Vec<PbUserInfo>, Vec<PartialObject>)> = None;
2562        if let Some(drop_table_connector_ctx) = drop_table_connector_ctx {
2563            notification_objs =
2564                Some(Self::drop_table_associated_source(txn, drop_table_connector_ctx).await?);
2565        }
2566
2567        Ok((
2568            objects,
2569            notification_objs,
2570            old_fragment_ids,
2571            new_fragment_ids,
2572        ))
2573    }
2574
2575    /// Abort the replacing streaming job by deleting the temporary job object.
2576    pub async fn try_abort_replacing_streaming_job(
2577        &self,
2578        tmp_job_id: JobId,
2579        tmp_sink_ids: Option<Vec<ObjectId>>,
2580    ) -> MetaResult<()> {
2581        let inner = self.inner.write().await;
2582        let txn = inner.db.begin().await?;
2583
2584        let mut root_ids: Vec<ObjectId> = vec![tmp_job_id.into()];
2585        if let Some(sink_ids) = &tmp_sink_ids {
2586            root_ids.extend(sink_ids.iter().copied());
2587        }
2588        let mut temporary_objects = Object::find()
2589            .filter(object::Column::Oid.is_in(root_ids.iter().copied()))
2590            .all(&txn)
2591            .await?;
2592        temporary_objects.extend(get_belong_objects_by_ids(&txn, root_ids.iter().copied()).await?);
2593
2594        // Query fragment IDs before cascade-deleting the temporary jobs and objects that belong to
2595        // them.
2596        let abort_fragment_ids: Vec<FragmentId> = Fragment::find()
2597            .select_only()
2598            .column(fragment::Column::FragmentId)
2599            .filter(
2600                fragment::Column::JobId.is_in(
2601                    temporary_objects
2602                        .iter()
2603                        .map(|object| object.oid.as_job_id()),
2604                ),
2605            )
2606            .into_tuple()
2607            .all(&txn)
2608            .await?;
2609
2610        Object::delete_many()
2611            .filter(object::Column::Oid.is_in(root_ids))
2612            .exec(&txn)
2613            .await?;
2614        txn.commit().await?;
2615
2616        // Notify serving module about deleted fragments from the aborted replace job.
2617        self.env
2618            .notification_manager()
2619            .notify_serving_fragment_mapping_delete(
2620                abort_fragment_ids.iter().map(|id| *id as _).collect(),
2621            );
2622
2623        Ok(())
2624    }
2625
2626    // edit the `rate_limit` of the `Source` node in given `source_id`'s fragments
2627    // return the actor_ids to be applied
2628    pub async fn update_source_rate_limit_by_source_id(
2629        &self,
2630        source_id: SourceId,
2631        rate_limit: Option<u32>,
2632    ) -> MetaResult<HashMap<FragmentId, PbStreamNode>> {
2633        let inner = self.inner.read().await;
2634        let txn = inner.db.begin().await?;
2635
2636        {
2637            let active_source = source::ActiveModel {
2638                source_id: Set(source_id),
2639                rate_limit: Set(rate_limit.map(|v| v as i32)),
2640                ..Default::default()
2641            };
2642            Source::update(active_source).exec(&txn).await?;
2643        }
2644
2645        let (source, obj) = Source::find_by_id(source_id)
2646            .find_also_related(Object)
2647            .one(&txn)
2648            .await?
2649            .ok_or_else(|| {
2650                MetaError::catalog_id_not_found(ObjectType::Source.as_str(), source_id)
2651            })?;
2652
2653        if source
2654            .with_properties
2655            .inner_ref()
2656            .is_iceberg_update_source()
2657        {
2658            return Err(MetaError::invalid_parameter(
2659                "Iceberg streaming_updates does not support rate limiting",
2660            ));
2661        }
2662        let streaming_job_ids: Vec<JobId> =
2663            if let Some(table_id) = source.optional_associated_table_id {
2664                vec![table_id.as_job_id()]
2665            } else if let Some(source_info) = &source.source_info
2666                && source_info.to_protobuf().is_shared()
2667            {
2668                vec![source_id.as_share_source_job_id()]
2669            } else {
2670                ObjectDependency::find()
2671                    .select_only()
2672                    .column(object_dependency::Column::UsedBy)
2673                    .filter(object_dependency::Column::Oid.eq(source_id))
2674                    .into_tuple()
2675                    .all(&txn)
2676                    .await?
2677            };
2678
2679        if streaming_job_ids.is_empty() {
2680            return Err(MetaError::invalid_parameter(format!(
2681                "source id {source_id} not used by any streaming job"
2682            )));
2683        }
2684
2685        let fragments: Vec<(FragmentId, JobId, i32, StreamNode)> = Fragment::find()
2686            .select_only()
2687            .columns([
2688                fragment::Column::FragmentId,
2689                fragment::Column::JobId,
2690                fragment::Column::FragmentTypeMask,
2691                fragment::Column::StreamNode,
2692            ])
2693            .filter(fragment::Column::JobId.is_in(streaming_job_ids))
2694            .into_tuple()
2695            .all(&txn)
2696            .await?;
2697        let mut fragments = fragments
2698            .into_iter()
2699            .map(|(id, job_id, mask, stream_node)| {
2700                (
2701                    id,
2702                    job_id,
2703                    FragmentTypeMask::from(mask as u32),
2704                    stream_node.to_protobuf(),
2705                )
2706            })
2707            .collect_vec();
2708
2709        fragments.retain_mut(|(_, _, fragment_type_mask, stream_node)| {
2710            let mut found = false;
2711            if fragment_type_mask.contains(FragmentTypeFlag::Source) {
2712                visit_stream_node_mut(stream_node, |node| {
2713                    if let PbNodeBody::Source(node) = node
2714                        && let Some(node_inner) = &mut node.source_inner
2715                        && node_inner.source_id == source_id
2716                    {
2717                        node_inner.rate_limit = rate_limit;
2718                        found = true;
2719                    }
2720                });
2721            }
2722            // Fragments from older versions carry no `FsFetch` flag, so scan every fragment
2723            // for the node and backfill the flag.
2724            visit_stream_node_mut(stream_node, |node| {
2725                if let PbNodeBody::StreamFsFetch(node) = node {
2726                    fragment_type_mask.add(FragmentTypeFlag::FsFetch);
2727                    if let Some(node_inner) = &mut node.node_inner
2728                        && node_inner.source_id == source_id
2729                    {
2730                        node_inner.rate_limit = rate_limit;
2731                        found = true;
2732                    }
2733                }
2734            });
2735            found
2736        });
2737
2738        assert!(
2739            !fragments.is_empty(),
2740            "source id should be used by at least one fragment"
2741        );
2742
2743        let fragment_nodes = fragments
2744            .iter()
2745            .map(|(fragment_id, _, _, stream_node)| (*fragment_id, stream_node.clone()))
2746            .collect();
2747
2748        for (fragment_id, _, fragment_type_mask, stream_node) in fragments {
2749            Fragment::update(fragment::ActiveModel {
2750                fragment_id: Set(fragment_id),
2751                fragment_type_mask: Set(fragment_type_mask.into()),
2752                stream_node: Set(StreamNode::from(&stream_node)),
2753                ..Default::default()
2754            })
2755            .exec(&txn)
2756            .await?;
2757        }
2758
2759        txn.commit().await?;
2760
2761        let relation_info = PbObjectInfo::Source(ObjectModel(source, obj.unwrap(), None).into());
2762        let _version = self
2763            .notify_frontend(
2764                NotificationOperation::Update,
2765                NotificationInfo::ObjectGroup(PbObjectGroup {
2766                    objects: vec![PbObject {
2767                        object_info: Some(relation_info),
2768                    }],
2769                    dependencies: vec![],
2770                }),
2771            )
2772            .await;
2773
2774        Ok(fragment_nodes)
2775    }
2776
2777    // edit the content of fragments in given `table_id`
2778    // return the updated stream nodes to be applied
2779    pub async fn mutate_fragments_by_job_id(
2780        &self,
2781        job_id: JobId,
2782        // returns true if the mutation is applied
2783        mut fragments_mutation_fn: impl FnMut(FragmentTypeMask, &mut PbStreamNode) -> MetaResult<bool>,
2784        // error message when no relevant fragments is found
2785        err_msg: &'static str,
2786    ) -> MetaResult<HashMap<FragmentId, PbStreamNode>> {
2787        let inner = self.inner.read().await;
2788        let txn = inner.db.begin().await?;
2789
2790        let fragments: Vec<(FragmentId, i32, StreamNode)> = Fragment::find()
2791            .select_only()
2792            .columns([
2793                fragment::Column::FragmentId,
2794                fragment::Column::FragmentTypeMask,
2795                fragment::Column::StreamNode,
2796            ])
2797            .filter(fragment::Column::JobId.eq(job_id))
2798            .into_tuple()
2799            .all(&txn)
2800            .await?;
2801        let mut fragments = fragments
2802            .into_iter()
2803            .map(|(id, mask, stream_node)| {
2804                (id, FragmentTypeMask::from(mask), stream_node.to_protobuf())
2805            })
2806            .collect_vec();
2807
2808        let fragments = fragments
2809            .iter_mut()
2810            .map(|(_, fragment_type_mask, stream_node)| {
2811                fragments_mutation_fn(*fragment_type_mask, stream_node)
2812            })
2813            .collect::<MetaResult<Vec<bool>>>()?
2814            .into_iter()
2815            .zip_eq_debug(std::mem::take(&mut fragments))
2816            .filter_map(|(keep, fragment)| if keep { Some(fragment) } else { None })
2817            .collect::<Vec<_>>();
2818
2819        if fragments.is_empty() {
2820            return Err(MetaError::invalid_parameter(format!(
2821                "job id {job_id}: {}",
2822                err_msg
2823            )));
2824        }
2825
2826        let fragment_nodes = fragments
2827            .iter()
2828            .map(|(id, _, stream_node)| (*id, stream_node.clone()))
2829            .collect();
2830        for (id, _, stream_node) in fragments {
2831            Fragment::update(fragment::ActiveModel {
2832                fragment_id: Set(id),
2833                stream_node: Set(StreamNode::from(&stream_node)),
2834                ..Default::default()
2835            })
2836            .exec(&txn)
2837            .await?;
2838        }
2839
2840        txn.commit().await?;
2841
2842        Ok(fragment_nodes)
2843    }
2844
2845    async fn mutate_fragment_by_fragment_id(
2846        &self,
2847        fragment_id: FragmentId,
2848        mut fragment_mutation_fn: impl FnMut(FragmentTypeMask, &mut PbStreamNode) -> MetaResult<bool>,
2849        err_msg: &'static str,
2850    ) -> MetaResult<PbStreamNode> {
2851        let inner = self.inner.read().await;
2852        let txn = inner.db.begin().await?;
2853
2854        let (fragment_type_mask, stream_node): (i32, StreamNode) =
2855            Fragment::find_by_id(fragment_id)
2856                .select_only()
2857                .columns([
2858                    fragment::Column::FragmentTypeMask,
2859                    fragment::Column::StreamNode,
2860                ])
2861                .into_tuple()
2862                .one(&txn)
2863                .await?
2864                .ok_or_else(|| MetaError::catalog_id_not_found("fragment", fragment_id))?;
2865        let mut pb_stream_node = stream_node.to_protobuf();
2866        let fragment_type_mask = FragmentTypeMask::from(fragment_type_mask);
2867
2868        if !fragment_mutation_fn(fragment_type_mask, &mut pb_stream_node)? {
2869            return Err(MetaError::invalid_parameter(format!(
2870                "fragment id {fragment_id}: {}",
2871                err_msg
2872            )));
2873        }
2874
2875        Fragment::update(fragment::ActiveModel {
2876            fragment_id: Set(fragment_id),
2877            stream_node: Set(StreamNode::from(&pb_stream_node)),
2878            ..Default::default()
2879        })
2880        .exec(&txn)
2881        .await?;
2882
2883        txn.commit().await?;
2884
2885        Ok(pb_stream_node)
2886    }
2887
2888    pub async fn update_backfill_orders_by_job_id(
2889        &self,
2890        job_id: JobId,
2891        backfill_orders: Option<BackfillOrders>,
2892    ) -> MetaResult<()> {
2893        let inner = self.inner.write().await;
2894        let txn = inner.db.begin().await?;
2895
2896        ensure_job_not_canceled(job_id, &txn).await?;
2897
2898        streaming_job::ActiveModel {
2899            job_id: Set(job_id),
2900            backfill_orders: Set(backfill_orders),
2901            ..Default::default()
2902        }
2903        .update(&txn)
2904        .await?;
2905
2906        txn.commit().await?;
2907
2908        Ok(())
2909    }
2910
2911    // edit the `rate_limit` of the `Chain` node in given `table_id`'s fragments
2912    // return the actor_ids to be applied
2913    pub async fn update_backfill_rate_limit_by_job_id(
2914        &self,
2915        job_id: JobId,
2916        rate_limit: Option<u32>,
2917    ) -> MetaResult<HashMap<FragmentId, PbStreamNode>> {
2918        let update_backfill_rate_limit =
2919            |fragment_type_mask: FragmentTypeMask, stream_node: &mut PbStreamNode| {
2920                let mut found = false;
2921                if fragment_type_mask
2922                    .contains_any(FragmentTypeFlag::backfill_rate_limit_fragments())
2923                {
2924                    visit_stream_node_mut(stream_node, |node| match node {
2925                        PbNodeBody::StreamCdcScan(node) => {
2926                            node.rate_limit = rate_limit;
2927                            found = true;
2928                        }
2929                        PbNodeBody::StreamScan(node) => {
2930                            node.rate_limit = rate_limit;
2931                            found = true;
2932                        }
2933                        PbNodeBody::SourceBackfill(node) => {
2934                            node.rate_limit = rate_limit;
2935                            found = true;
2936                        }
2937                        PbNodeBody::LocalityProvider(node) => {
2938                            node.rate_limit = rate_limit;
2939                            found = true;
2940                        }
2941                        _ => {}
2942                    });
2943                }
2944                Ok(found)
2945            };
2946
2947        self.mutate_fragments_by_job_id(
2948            job_id,
2949            update_backfill_rate_limit,
2950            "stream scan node or source node not found",
2951        )
2952        .await
2953    }
2954
2955    // edit the `rate_limit` of the `Sink` node in given `table_id`'s fragments
2956    // return the actor_ids to be applied
2957    pub async fn update_sink_rate_limit_by_job_id(
2958        &self,
2959        sink_id: SinkId,
2960        rate_limit: Option<u32>,
2961    ) -> MetaResult<HashMap<FragmentId, PbStreamNode>> {
2962        let update_sink_rate_limit =
2963            |fragment_type_mask: FragmentTypeMask, stream_node: &mut PbStreamNode| {
2964                let mut found = Ok(false);
2965                if fragment_type_mask.contains_any(FragmentTypeFlag::sink_rate_limit_fragments()) {
2966                    visit_stream_node_mut(stream_node, |node| {
2967                        if found.is_err() {
2968                            return;
2969                        }
2970                        match update_sink_node_rate_limit(node, rate_limit) {
2971                            Ok(true) => found = Ok(true),
2972                            Ok(false) => {}
2973                            Err(err) => found = Err(err),
2974                        }
2975                    });
2976                }
2977                found
2978            };
2979
2980        self.mutate_fragments_by_job_id(
2981            sink_id.as_job_id(),
2982            update_sink_rate_limit,
2983            "sink node not found",
2984        )
2985        .await
2986    }
2987
2988    pub async fn update_dml_rate_limit_by_job_id(
2989        &self,
2990        job_id: JobId,
2991        rate_limit: Option<u32>,
2992    ) -> MetaResult<HashMap<FragmentId, PbStreamNode>> {
2993        let update_dml_rate_limit =
2994            |fragment_type_mask: FragmentTypeMask, stream_node: &mut PbStreamNode| {
2995                let mut found = false;
2996                if fragment_type_mask.contains_any(FragmentTypeFlag::dml_rate_limit_fragments()) {
2997                    visit_stream_node_mut(stream_node, |node| {
2998                        if let PbNodeBody::Dml(node) = node {
2999                            node.rate_limit = rate_limit;
3000                            found = true;
3001                        }
3002                    });
3003                }
3004                Ok(found)
3005            };
3006
3007        self.mutate_fragments_by_job_id(job_id, update_dml_rate_limit, "dml node not found")
3008            .await
3009    }
3010
3011    pub async fn update_source_props_by_source_id(
3012        &self,
3013        source_id: SourceId,
3014        alter_props: BTreeMap<String, String>,
3015        alter_secret_refs: BTreeMap<String, PbSecretRef>,
3016        skip_alter_on_fly_check: bool,
3017    ) -> MetaResult<WithOptionsSecResolved> {
3018        let inner = self.inner.read().await;
3019        let txn = inner.db.begin().await?;
3020
3021        let (source, _obj) = Source::find_by_id(source_id)
3022            .find_also_related(Object)
3023            .one(&txn)
3024            .await?
3025            .ok_or_else(|| {
3026                MetaError::catalog_id_not_found(ObjectType::Source.as_str(), source_id)
3027            })?;
3028        ensure_source_props_not_set_by_connection(&txn, &source, &alter_props, &alter_secret_refs)
3029            .await?;
3030        let connector = source.with_properties.0.get_connector().unwrap();
3031        let is_shared_source = source.is_shared();
3032
3033        let mut dep_source_job_ids: Vec<JobId> = Vec::new();
3034        if !is_shared_source {
3035            // mv using non-shared source holds a copy of source in their fragments
3036            dep_source_job_ids = ObjectDependency::find()
3037                .select_only()
3038                .column(object_dependency::Column::UsedBy)
3039                .filter(object_dependency::Column::Oid.eq(source_id))
3040                .into_tuple()
3041                .all(&txn)
3042                .await?;
3043        }
3044
3045        // Validate that connector type is not being changed
3046        if let Some(new_connector) = alter_props.get(UPSTREAM_SOURCE_KEY)
3047            && new_connector != &connector
3048        {
3049            return Err(MetaError::invalid_parameter(format!(
3050                "Cannot change connector type from '{}' to '{}'. Drop and recreate the source instead.",
3051                connector, new_connector
3052            )));
3053        }
3054
3055        // Only check alter-on-fly restrictions for SQL ALTER SOURCE, not for admin risectl operations
3056        if !skip_alter_on_fly_check {
3057            dispatch_cdc_source_type!(
3058                CdcSourceType::from(connector.as_str()),
3059                T,
3060                T::check_alter_with_options(&alter_props, &alter_secret_refs)?,
3061                {
3062                    let prop_keys: Vec<String> = alter_props
3063                        .keys()
3064                        .chain(alter_secret_refs.keys())
3065                        .cloned()
3066                        .collect();
3067                    risingwave_connector::allow_alter_on_fly_fields::check_source_allow_alter_on_fly_fields(
3068                        &connector, &prop_keys,
3069                    )?
3070                }
3071            );
3072        }
3073
3074        let mut options_with_secret = WithOptionsSecResolved::new(
3075            source.with_properties.0.clone(),
3076            source
3077                .secret_ref
3078                .map(|secret_ref| secret_ref.to_protobuf())
3079                .unwrap_or_default(),
3080        );
3081        let altered_options_with_secret =
3082            WithOptionsSecResolved::new(alter_props.clone(), alter_secret_refs.clone());
3083        let (to_add_secret_dep, to_remove_secret_dep) =
3084            options_with_secret.handle_update(alter_props, alter_secret_refs)?;
3085
3086        tracing::info!(
3087            "applying new properties to source: source_id={}, options_with_secret={:?}",
3088            source_id,
3089            options_with_secret
3090        );
3091        // check if the alter-ed props are valid for each Connector
3092        let _ = ConnectorProperties::extract(options_with_secret.clone(), true)?;
3093        // todo: validate via source manager
3094
3095        let mut associate_table_id = None;
3096
3097        // can be source_id or table_id
3098        // if updating an associated source, the preferred_id is the table_id
3099        // otherwise, it is the source_id
3100        let mut preferred_id = source_id.as_object_id();
3101        let rewrite_sql = {
3102            let definition = source.definition.clone();
3103
3104            let [mut stmt]: [_; 1] = Parser::parse_sql(&definition)
3105                .map_err(|e| {
3106                    MetaError::from(MetaErrorInner::Connector(ConnectorError::from(
3107                        anyhow!(e).context("Failed to parse source definition SQL"),
3108                    )))
3109                })?
3110                .try_into()
3111                .unwrap();
3112
3113            match &mut stmt {
3114                Statement::CreateSource { stmt } => {
3115                    let altered_sql_options =
3116                        format_with_option_secret_resolved(&txn, &altered_options_with_secret)
3117                            .await?;
3118                    merge_with_options(&mut stmt.with_properties.0, altered_sql_options);
3119                }
3120                Statement::CreateTable { with_options, .. } => {
3121                    let altered_sql_options =
3122                        format_with_option_secret_resolved(&txn, &altered_options_with_secret)
3123                            .await?;
3124                    merge_with_options(with_options, altered_sql_options);
3125                    associate_table_id = source.optional_associated_table_id;
3126                    preferred_id = associate_table_id.unwrap().as_object_id();
3127                }
3128                _ => unreachable!(),
3129            }
3130
3131            stmt.to_string()
3132        };
3133
3134        {
3135            // Update secret dependencies atomically within the transaction.
3136            // Add new dependencies for secrets that are newly referenced.
3137            if !to_add_secret_dep.is_empty() {
3138                ObjectDependency::insert_many(to_add_secret_dep.into_iter().map(|secret_id| {
3139                    object_dependency::ActiveModel {
3140                        oid: Set(secret_id.into()),
3141                        used_by: Set(preferred_id),
3142                        ..Default::default()
3143                    }
3144                }))
3145                .exec(&txn)
3146                .await?;
3147            }
3148            // Remove dependencies for secrets that are no longer referenced.
3149            // This allows the secrets to be deleted after this source no longer uses them.
3150            if !to_remove_secret_dep.is_empty() {
3151                let _ = ObjectDependency::delete_many()
3152                    .filter(
3153                        object_dependency::Column::Oid
3154                            .is_in(to_remove_secret_dep)
3155                            .and(object_dependency::Column::UsedBy.eq(preferred_id)),
3156                    )
3157                    .exec(&txn)
3158                    .await?;
3159            }
3160        }
3161
3162        let active_source_model = source::ActiveModel {
3163            source_id: Set(source_id),
3164            definition: Set(rewrite_sql.clone()),
3165            with_properties: Set(options_with_secret.as_plaintext().clone().into()),
3166            secret_ref: Set((!options_with_secret.as_secret().is_empty())
3167                .then(|| SecretRef::from(options_with_secret.as_secret().clone()))),
3168            ..Default::default()
3169        };
3170        Source::update(active_source_model).exec(&txn).await?;
3171
3172        if let Some(associate_table_id) = associate_table_id {
3173            // update the associated table statement accordly
3174            let active_table_model = table::ActiveModel {
3175                table_id: Set(associate_table_id),
3176                definition: Set(rewrite_sql),
3177                ..Default::default()
3178            };
3179            Table::update(active_table_model).exec(&txn).await?;
3180        }
3181
3182        let to_check_job_ids = vec![if let Some(associate_table_id) = associate_table_id {
3183            // if updating table with connector, the fragment_id is table id
3184            associate_table_id.as_job_id()
3185        } else {
3186            source_id.as_share_source_job_id()
3187        }]
3188        .into_iter()
3189        .chain(dep_source_job_ids)
3190        .collect_vec();
3191
3192        // update fragments
3193        update_connector_props_fragments(
3194            &txn,
3195            to_check_job_ids,
3196            FragmentTypeFlag::Source,
3197            |node, found| {
3198                if let PbNodeBody::Source(node) = node
3199                    && let Some(source_inner) = &mut node.source_inner
3200                {
3201                    source_inner.with_properties = options_with_secret.as_plaintext().clone();
3202                    source_inner.secret_refs = options_with_secret.as_secret().clone();
3203                    *found = true;
3204                }
3205            },
3206            is_shared_source,
3207        )
3208        .await?;
3209
3210        let mut to_update_objs = Vec::with_capacity(2);
3211        let (source, obj) = Source::find_by_id(source_id)
3212            .find_also_related(Object)
3213            .one(&txn)
3214            .await?
3215            .ok_or_else(|| {
3216                MetaError::catalog_id_not_found(ObjectType::Source.as_str(), source_id)
3217            })?;
3218        to_update_objs.push(PbObject {
3219            object_info: Some(PbObjectInfo::Source(
3220                ObjectModel(source, obj.unwrap(), None).into(),
3221            )),
3222        });
3223
3224        if let Some(associate_table_id) = associate_table_id {
3225            let (table, obj) = Table::find_by_id(associate_table_id)
3226                .find_also_related(Object)
3227                .one(&txn)
3228                .await?
3229                .ok_or_else(|| MetaError::catalog_id_not_found("table", associate_table_id))?;
3230            let streaming_job = streaming_job::Entity::find_by_id(table.job_id())
3231                .one(&txn)
3232                .await?;
3233            to_update_objs.push(PbObject {
3234                object_info: Some(PbObjectInfo::Table(
3235                    ObjectModel(table, obj.unwrap(), streaming_job).into(),
3236                )),
3237            });
3238        }
3239
3240        txn.commit().await?;
3241
3242        let _version = self
3243            .notify_frontend(
3244                NotificationOperation::Update,
3245                NotificationInfo::ObjectGroup(PbObjectGroup {
3246                    objects: to_update_objs,
3247                    dependencies: vec![],
3248                }),
3249            )
3250            .await;
3251
3252        Ok(options_with_secret)
3253    }
3254
3255    pub async fn update_sink_props_by_sink_id(
3256        &self,
3257        sink_id: SinkId,
3258        props: BTreeMap<String, String>,
3259    ) -> MetaResult<HashMap<String, String>> {
3260        let inner = self.inner.read().await;
3261        let txn = inner.db.begin().await?;
3262
3263        let (sink, _obj) = Sink::find_by_id(sink_id)
3264            .find_also_related(Object)
3265            .one(&txn)
3266            .await?
3267            .ok_or_else(|| MetaError::catalog_id_not_found(ObjectType::Sink.as_str(), sink_id))?;
3268        validate_sink_props(&sink, &props, &props.keys().cloned().collect_vec())?;
3269        let definition = sink.definition.clone();
3270        let [mut stmt]: [_; 1] = Parser::parse_sql(&definition)
3271            .map_err(|e| SinkError::Config(anyhow!(e)))?
3272            .try_into()
3273            .unwrap();
3274        if let Statement::CreateSink { stmt } = &mut stmt {
3275            update_stmt_with_props(&mut stmt.with_properties.0, &props)?;
3276        } else {
3277            return Err(MetaError::invalid_parameter(
3278                "cannot alter an internal Iceberg sink; use ALTER TABLE ... CONNECTOR WITH (...) instead",
3279            ));
3280        }
3281        let mut new_config = sink.properties.clone().into_inner();
3282        new_config.extend(props.clone());
3283
3284        let definition = stmt.to_string();
3285        let active_sink = sink::ActiveModel {
3286            sink_id: Set(sink_id),
3287            properties: Set(risingwave_meta_model::Property(new_config.clone())),
3288            definition: Set(definition),
3289            ..Default::default()
3290        };
3291        Sink::update(active_sink).exec(&txn).await?;
3292
3293        update_sink_fragment_props(&txn, sink_id, new_config).await?;
3294        let (sink, obj) = Sink::find_by_id(sink_id)
3295            .find_also_related(Object)
3296            .one(&txn)
3297            .await?
3298            .ok_or_else(|| MetaError::catalog_id_not_found(ObjectType::Sink.as_str(), sink_id))?;
3299        let streaming_job = streaming_job::Entity::find_by_id(sink.sink_id.as_job_id())
3300            .one(&txn)
3301            .await?;
3302        txn.commit().await?;
3303        let relation_infos = vec![PbObject {
3304            object_info: Some(PbObjectInfo::Sink(
3305                ObjectModel(sink, obj.unwrap(), streaming_job).into(),
3306            )),
3307        }];
3308
3309        let _version = self
3310            .notify_frontend(
3311                NotificationOperation::Update,
3312                NotificationInfo::ObjectGroup(PbObjectGroup {
3313                    objects: relation_infos,
3314                    dependencies: vec![],
3315                }),
3316            )
3317            .await;
3318
3319        Ok(props.into_iter().collect())
3320    }
3321
3322    pub async fn update_iceberg_table_props_by_table_id(
3323        &self,
3324        table_id: TableId,
3325        props: BTreeMap<String, String>,
3326        alter_iceberg_table_props: Option<
3327            risingwave_pb::meta::alter_connector_props_request::PbExtraOptions,
3328        >,
3329    ) -> MetaResult<(HashMap<String, String>, SinkId)> {
3330        let risingwave_pb::meta::alter_connector_props_request::PbExtraOptions::AlterIcebergTableIds(AlterIcebergTableIds { sink_id, source_id }) = alter_iceberg_table_props.
3331            ok_or_else(|| MetaError::invalid_parameter("alter_iceberg_table_props is required"))?;
3332        let inner = self.inner.read().await;
3333        let txn = inner.db.begin().await?;
3334
3335        let (sink, _obj) = Sink::find_by_id(sink_id)
3336            .find_also_related(Object)
3337            .one(&txn)
3338            .await?
3339            .ok_or_else(|| MetaError::catalog_id_not_found(ObjectType::Sink.as_str(), sink_id))?;
3340        validate_sink_props(&sink, &props, &props.keys().cloned().collect_vec())?;
3341
3342        let definition = sink.definition.clone();
3343        let [mut stmt]: [_; 1] = Parser::parse_sql(&definition)
3344            .map_err(|e| SinkError::Config(anyhow!(e)))?
3345            .try_into()
3346            .unwrap();
3347        if let Statement::CreateTable {
3348            with_options,
3349            engine,
3350            ..
3351        } = &mut stmt
3352        {
3353            if !matches!(engine, Engine::Iceberg) {
3354                return Err(SinkError::Config(anyhow!(
3355                    "only iceberg table can be altered as sink"
3356                ))
3357                .into());
3358            }
3359            update_stmt_with_props(with_options, &props)?;
3360        } else {
3361            return Err(MetaError::invalid_parameter(
3362                "definition is not a create iceberg table statement",
3363            ));
3364        }
3365        let mut new_config = sink.properties.clone().into_inner();
3366        new_config.extend(props.clone());
3367
3368        let definition = stmt.to_string();
3369        let active_sink = sink::ActiveModel {
3370            sink_id: Set(sink_id),
3371            properties: Set(risingwave_meta_model::Property(new_config.clone())),
3372            definition: Set(definition.clone()),
3373            ..Default::default()
3374        };
3375        let active_source = source::ActiveModel {
3376            source_id: Set(source_id),
3377            definition: Set(definition.clone()),
3378            ..Default::default()
3379        };
3380        let active_table = table::ActiveModel {
3381            table_id: Set(table_id),
3382            definition: Set(definition),
3383            ..Default::default()
3384        };
3385        Sink::update(active_sink).exec(&txn).await?;
3386        Source::update(active_source).exec(&txn).await?;
3387        Table::update(active_table).exec(&txn).await?;
3388
3389        update_sink_fragment_props(&txn, sink_id, new_config).await?;
3390
3391        let (sink, sink_obj) = Sink::find_by_id(sink_id)
3392            .find_also_related(Object)
3393            .one(&txn)
3394            .await?
3395            .ok_or_else(|| MetaError::catalog_id_not_found(ObjectType::Sink.as_str(), sink_id))?;
3396        let sink_streaming_job = streaming_job::Entity::find_by_id(sink.sink_id.as_job_id())
3397            .one(&txn)
3398            .await?;
3399        let (source, source_obj) = Source::find_by_id(source_id)
3400            .find_also_related(Object)
3401            .one(&txn)
3402            .await?
3403            .ok_or_else(|| {
3404                MetaError::catalog_id_not_found(ObjectType::Source.as_str(), source_id)
3405            })?;
3406        let (table, table_obj) = Table::find_by_id(table_id)
3407            .find_also_related(Object)
3408            .one(&txn)
3409            .await?
3410            .ok_or_else(|| MetaError::catalog_id_not_found(ObjectType::Table.as_str(), table_id))?;
3411        let table_streaming_job = streaming_job::Entity::find_by_id(table.job_id())
3412            .one(&txn)
3413            .await?;
3414        txn.commit().await?;
3415        let relation_infos = vec![
3416            PbObject {
3417                object_info: Some(PbObjectInfo::Sink(
3418                    ObjectModel(sink, sink_obj.unwrap(), sink_streaming_job).into(),
3419                )),
3420            },
3421            PbObject {
3422                object_info: Some(PbObjectInfo::Source(
3423                    ObjectModel(source, source_obj.unwrap(), None).into(),
3424                )),
3425            },
3426            PbObject {
3427                object_info: Some(PbObjectInfo::Table(
3428                    ObjectModel(table, table_obj.unwrap(), table_streaming_job).into(),
3429                )),
3430            },
3431        ];
3432        let _version = self
3433            .notify_frontend(
3434                NotificationOperation::Update,
3435                NotificationInfo::ObjectGroup(PbObjectGroup {
3436                    objects: relation_infos,
3437                    dependencies: vec![],
3438                }),
3439            )
3440            .await;
3441
3442        Ok((props.into_iter().collect(), sink_id))
3443    }
3444
3445    /// Update connection properties and all dependent sources/sinks in a single transaction
3446    pub async fn update_connection_and_dependent_objects_props(
3447        &self,
3448        connection_id: ConnectionId,
3449        alter_props: BTreeMap<String, String>,
3450        alter_secret_refs: BTreeMap<String, PbSecretRef>,
3451    ) -> MetaResult<(
3452        WithOptionsSecResolved,                   // Connection's new properties
3453        Vec<(SourceId, HashMap<String, String>)>, // Source ID and their complete properties
3454        Vec<(SinkId, HashMap<String, String>)>,   // Sink ID and their complete properties
3455    )> {
3456        let inner = self.inner.read().await;
3457        let txn = inner.db.begin().await?;
3458
3459        // Find all dependent sources and sinks first
3460        let dependent_sources: Vec<SourceId> = Source::find()
3461            .select_only()
3462            .column(source::Column::SourceId)
3463            .filter(source::Column::ConnectionId.eq(connection_id))
3464            .into_tuple()
3465            .all(&txn)
3466            .await?;
3467
3468        let dependent_sinks: Vec<SinkId> = Sink::find()
3469            .select_only()
3470            .column(sink::Column::SinkId)
3471            .filter(sink::Column::ConnectionId.eq(connection_id))
3472            .into_tuple()
3473            .all(&txn)
3474            .await?;
3475
3476        let (connection_catalog, _obj) = Connection::find_by_id(connection_id)
3477            .find_also_related(Object)
3478            .one(&txn)
3479            .await?
3480            .ok_or_else(|| {
3481                MetaError::catalog_id_not_found(ObjectType::Connection.as_str(), connection_id)
3482            })?;
3483
3484        // Validate that props can be altered
3485        let prop_keys: Vec<String> = alter_props
3486            .keys()
3487            .chain(alter_secret_refs.keys())
3488            .cloned()
3489            .collect();
3490
3491        // Map the connection type enum to the string name expected by the validation function
3492        let connection_type_str = pb_connection_type_to_connection_type(
3493            &connection_catalog.params.to_protobuf().connection_type(),
3494        )
3495        .ok_or_else(|| MetaError::invalid_parameter("Unspecified connection type"))?;
3496
3497        risingwave_connector::allow_alter_on_fly_fields::check_connection_allow_alter_on_fly_fields(
3498            connection_type_str, &prop_keys,
3499        )?;
3500
3501        let connection_pb = connection_catalog.params.to_protobuf();
3502        let mut connection_options_with_secret = WithOptionsSecResolved::new(
3503            connection_pb.properties.into_iter().collect(),
3504            connection_pb.secret_refs.into_iter().collect(),
3505        );
3506
3507        let (to_add_secret_dep, to_remove_secret_dep) = connection_options_with_secret
3508            .handle_update(alter_props.clone(), alter_secret_refs.clone())?;
3509
3510        tracing::debug!(
3511            "applying new properties to connection and dependents: connection_id={}, sources={:?}, sinks={:?}",
3512            connection_id,
3513            dependent_sources,
3514            dependent_sinks
3515        );
3516
3517        // Validate connection
3518        {
3519            let conn_params_pb = risingwave_pb::catalog::ConnectionParams {
3520                connection_type: connection_pb.connection_type,
3521                properties: connection_options_with_secret
3522                    .as_plaintext()
3523                    .clone()
3524                    .into_iter()
3525                    .collect(),
3526                secret_refs: connection_options_with_secret
3527                    .as_secret()
3528                    .clone()
3529                    .into_iter()
3530                    .collect(),
3531            };
3532            let connection = PbConnection {
3533                id: connection_id as _,
3534                info: Some(risingwave_pb::catalog::connection::Info::ConnectionParams(
3535                    conn_params_pb,
3536                )),
3537                ..Default::default()
3538            };
3539            validate_connection(&connection).await?;
3540        }
3541
3542        // Update connection secret dependencies
3543        if !to_add_secret_dep.is_empty() {
3544            ObjectDependency::insert_many(to_add_secret_dep.into_iter().map(|secret_id| {
3545                object_dependency::ActiveModel {
3546                    oid: Set(secret_id.into()),
3547                    used_by: Set(connection_id.as_object_id()),
3548                    ..Default::default()
3549                }
3550            }))
3551            .exec(&txn)
3552            .await?;
3553        }
3554        if !to_remove_secret_dep.is_empty() {
3555            let _ = ObjectDependency::delete_many()
3556                .filter(
3557                    object_dependency::Column::Oid
3558                        .is_in(to_remove_secret_dep)
3559                        .and(object_dependency::Column::UsedBy.eq(connection_id.as_object_id())),
3560                )
3561                .exec(&txn)
3562                .await?;
3563        }
3564
3565        // Update the connection with new properties
3566        let updated_connection_params = risingwave_pb::catalog::ConnectionParams {
3567            connection_type: connection_pb.connection_type,
3568            properties: connection_options_with_secret
3569                .as_plaintext()
3570                .clone()
3571                .into_iter()
3572                .collect(),
3573            secret_refs: connection_options_with_secret
3574                .as_secret()
3575                .clone()
3576                .into_iter()
3577                .collect(),
3578        };
3579        let active_connection_model = connection::ActiveModel {
3580            connection_id: Set(connection_id),
3581            params: Set(ConnectionParams::from(&updated_connection_params)),
3582            ..Default::default()
3583        };
3584        Connection::update(active_connection_model)
3585            .exec(&txn)
3586            .await?;
3587
3588        // Batch update dependent sources and collect their complete properties
3589        let mut updated_sources_with_props: Vec<(SourceId, HashMap<String, String>)> = Vec::new();
3590
3591        if !dependent_sources.is_empty() {
3592            // Batch fetch all dependent sources
3593            let sources_with_objs = Source::find()
3594                .find_also_related(Object)
3595                .filter(source::Column::SourceId.is_in(dependent_sources.iter().cloned()))
3596                .all(&txn)
3597                .await?;
3598
3599            // Prepare batch updates
3600            let mut source_updates = Vec::new();
3601            let mut fragment_updates: Vec<DependentSourceFragmentUpdate> = Vec::new();
3602
3603            for (source, _obj) in sources_with_objs {
3604                let source_id = source.source_id;
3605
3606                let mut source_options_with_secret = WithOptionsSecResolved::new(
3607                    source.with_properties.0.clone(),
3608                    source
3609                        .secret_ref
3610                        .clone()
3611                        .map(|secret_ref| secret_ref.to_protobuf())
3612                        .unwrap_or_default(),
3613                );
3614                let (source_to_add_secret_dep, source_to_remove_secret_dep) =
3615                    source_options_with_secret
3616                        .handle_update(alter_props.clone(), alter_secret_refs.clone())?;
3617
3618                // Validate the updated source properties
3619                let _ = ConnectorProperties::extract(source_options_with_secret.clone(), true)?;
3620
3621                // Keep source-level secret dependencies in sync with the source properties that
3622                // are rewritten from the altered connection.
3623                let source_used_by_id = source
3624                    .optional_associated_table_id
3625                    .map(|table_id| table_id.as_object_id())
3626                    .unwrap_or_else(|| source_id.as_object_id());
3627                if !source_to_add_secret_dep.is_empty() {
3628                    ObjectDependency::insert_many(source_to_add_secret_dep.into_iter().map(
3629                        |secret_id| object_dependency::ActiveModel {
3630                            oid: Set(secret_id.into()),
3631                            used_by: Set(source_used_by_id),
3632                            ..Default::default()
3633                        },
3634                    ))
3635                    .exec(&txn)
3636                    .await?;
3637                }
3638                if !source_to_remove_secret_dep.is_empty() {
3639                    let _ = ObjectDependency::delete_many()
3640                        .filter(
3641                            object_dependency::Column::Oid
3642                                .is_in(source_to_remove_secret_dep)
3643                                .and(object_dependency::Column::UsedBy.eq(source_used_by_id)),
3644                        )
3645                        .exec(&txn)
3646                        .await?;
3647                }
3648
3649                // Prepare source update
3650                let active_source = source::ActiveModel {
3651                    source_id: Set(source_id),
3652                    with_properties: Set(Property(
3653                        source_options_with_secret.as_plaintext().clone(),
3654                    )),
3655                    secret_ref: Set((!source_options_with_secret.as_secret().is_empty()).then(
3656                        || {
3657                            risingwave_meta_model::SecretRef::from(
3658                                source_options_with_secret.as_secret().clone(),
3659                            )
3660                        },
3661                    )),
3662                    ..Default::default()
3663                };
3664                source_updates.push(active_source);
3665
3666                // Prepare fragment update:
3667                // - If the source is a table-associated source, update fragments for the table job.
3668                // - Otherwise update the shared source job.
3669                // - For non-shared sources, also update any dependent streaming jobs that embed a copy.
3670                let is_shared_source = source.is_shared();
3671                let mut dep_source_job_ids: Vec<JobId> = Vec::new();
3672                if !is_shared_source {
3673                    dep_source_job_ids = ObjectDependency::find()
3674                        .select_only()
3675                        .column(object_dependency::Column::UsedBy)
3676                        .filter(object_dependency::Column::Oid.eq(source_id))
3677                        .into_tuple()
3678                        .all(&txn)
3679                        .await?;
3680                }
3681
3682                let base_job_id =
3683                    if let Some(associate_table_id) = source.optional_associated_table_id {
3684                        associate_table_id.as_job_id()
3685                    } else {
3686                        source_id.as_share_source_job_id()
3687                    };
3688                let job_ids = vec![base_job_id]
3689                    .into_iter()
3690                    .chain(dep_source_job_ids)
3691                    .collect_vec();
3692
3693                fragment_updates.push(DependentSourceFragmentUpdate {
3694                    job_ids,
3695                    with_properties: source_options_with_secret.as_plaintext().clone(),
3696                    secret_refs: source_options_with_secret.as_secret().clone(),
3697                    is_shared_source,
3698                });
3699
3700                // Collect the complete properties for runtime broadcast
3701                let complete_source_props = LocalSecretManager::global()
3702                    .fill_secrets(
3703                        source_options_with_secret.as_plaintext().clone(),
3704                        source_options_with_secret.as_secret().clone(),
3705                    )
3706                    .map_err(MetaError::from)?
3707                    .into_iter()
3708                    .collect::<HashMap<String, String>>();
3709                updated_sources_with_props.push((source_id, complete_source_props));
3710            }
3711
3712            for source_update in source_updates {
3713                Source::update(source_update).exec(&txn).await?;
3714            }
3715
3716            // Batch execute fragment updates
3717            for DependentSourceFragmentUpdate {
3718                job_ids,
3719                with_properties,
3720                secret_refs,
3721                is_shared_source,
3722            } in fragment_updates
3723            {
3724                update_connector_props_fragments(
3725                    &txn,
3726                    job_ids,
3727                    FragmentTypeFlag::Source,
3728                    |node, found| {
3729                        if let PbNodeBody::Source(node) = node
3730                            && let Some(source_inner) = &mut node.source_inner
3731                        {
3732                            source_inner.with_properties = with_properties.clone();
3733                            source_inner.secret_refs = secret_refs.clone();
3734                            *found = true;
3735                        }
3736                    },
3737                    is_shared_source,
3738                )
3739                .await?;
3740            }
3741        }
3742
3743        // Batch update dependent sinks and collect their complete properties
3744        let mut updated_sinks_with_props: Vec<(SinkId, HashMap<String, String>)> = Vec::new();
3745
3746        if !dependent_sinks.is_empty() {
3747            // Batch fetch all dependent sinks
3748            let sinks_with_objs = Sink::find()
3749                .find_also_related(Object)
3750                .filter(sink::Column::SinkId.is_in(dependent_sinks.iter().cloned()))
3751                .all(&txn)
3752                .await?;
3753
3754            // Prepare batch updates
3755            let mut sink_updates = Vec::new();
3756            let mut sink_fragment_updates = Vec::new();
3757
3758            for (sink, _obj) in sinks_with_objs {
3759                let sink_id = sink.sink_id;
3760
3761                validate_sink_props(&sink, &alter_props, &prop_keys)?;
3762
3763                let mut new_sink_props = sink.properties.0.clone();
3764                new_sink_props.extend(alter_props.clone());
3765
3766                // Prepare sink update
3767                let active_sink = sink::ActiveModel {
3768                    sink_id: Set(sink_id),
3769                    properties: Set(risingwave_meta_model::Property(new_sink_props.clone())),
3770                    ..Default::default()
3771                };
3772                sink_updates.push(active_sink);
3773
3774                // Prepare fragment updates for this sink
3775                sink_fragment_updates.push((sink_id, new_sink_props.clone()));
3776
3777                // Collect the complete properties for runtime broadcast
3778                let complete_sink_props: HashMap<String, String> =
3779                    new_sink_props.into_iter().collect();
3780                updated_sinks_with_props.push((sink_id, complete_sink_props));
3781            }
3782
3783            // Batch execute sink updates
3784            for sink_update in sink_updates {
3785                Sink::update(sink_update).exec(&txn).await?;
3786            }
3787
3788            // Batch execute sink fragment updates using the reusable function
3789            for (sink_id, new_sink_props) in sink_fragment_updates {
3790                update_connector_props_fragments(
3791                    &txn,
3792                    vec![sink_id.as_job_id()],
3793                    FragmentTypeFlag::Sink,
3794                    |node, found| {
3795                        if let PbNodeBody::Sink(node) = node
3796                            && let Some(sink_desc) = &mut node.sink_desc
3797                            && sink_desc.id == sink_id.as_raw_id()
3798                        {
3799                            sink_desc.properties = new_sink_props.clone();
3800                            *found = true;
3801                        }
3802                    },
3803                    true,
3804                )
3805                .await?;
3806            }
3807        }
3808
3809        // Collect all updated objects for frontend notification
3810        let mut updated_objects = Vec::new();
3811
3812        // Add connection
3813        let (connection, obj) = Connection::find_by_id(connection_id)
3814            .find_also_related(Object)
3815            .one(&txn)
3816            .await?
3817            .ok_or_else(|| {
3818                MetaError::catalog_id_not_found(ObjectType::Connection.as_str(), connection_id)
3819            })?;
3820        updated_objects.push(PbObject {
3821            object_info: Some(PbObjectInfo::Connection(
3822                ObjectModel(connection, obj.unwrap(), None).into(),
3823            )),
3824        });
3825
3826        // Add sources
3827        for source_id in &dependent_sources {
3828            let (source, obj) = Source::find_by_id(*source_id)
3829                .find_also_related(Object)
3830                .one(&txn)
3831                .await?
3832                .ok_or_else(|| {
3833                    MetaError::catalog_id_not_found(ObjectType::Source.as_str(), *source_id)
3834                })?;
3835            updated_objects.push(PbObject {
3836                object_info: Some(PbObjectInfo::Source(
3837                    ObjectModel(source, obj.unwrap(), None).into(),
3838                )),
3839            });
3840        }
3841
3842        // Add sinks
3843        for sink_id in &dependent_sinks {
3844            let (sink, obj) = Sink::find_by_id(*sink_id)
3845                .find_also_related(Object)
3846                .one(&txn)
3847                .await?
3848                .ok_or_else(|| {
3849                    MetaError::catalog_id_not_found(ObjectType::Sink.as_str(), *sink_id)
3850                })?;
3851            let streaming_job = streaming_job::Entity::find_by_id(sink.sink_id.as_job_id())
3852                .one(&txn)
3853                .await?;
3854            updated_objects.push(PbObject {
3855                object_info: Some(PbObjectInfo::Sink(
3856                    ObjectModel(sink, obj.unwrap(), streaming_job).into(),
3857                )),
3858            });
3859        }
3860
3861        // Commit the transaction
3862        txn.commit().await?;
3863
3864        // Notify frontend about all updated objects
3865        if !updated_objects.is_empty() {
3866            let _version = self
3867                .notify_frontend(
3868                    NotificationOperation::Update,
3869                    NotificationInfo::ObjectGroup(PbObjectGroup {
3870                        objects: updated_objects,
3871                        dependencies: vec![],
3872                    }),
3873                )
3874                .await;
3875        }
3876
3877        Ok((
3878            connection_options_with_secret,
3879            updated_sources_with_props,
3880            updated_sinks_with_props,
3881        ))
3882    }
3883
3884    pub async fn update_fragment_rate_limit_by_fragment_id(
3885        &self,
3886        fragment_id: FragmentId,
3887        throttle_type: ThrottleType,
3888        rate_limit: Option<u32>,
3889    ) -> MetaResult<PbStreamNode> {
3890        let update_rate_limit = |fragment_type_mask: FragmentTypeMask,
3891                                 stream_node: &mut PbStreamNode| {
3892            let mut found = Ok(false);
3893            match throttle_type {
3894                ThrottleType::Source => {
3895                    visit_stream_node_mut(stream_node, |node| {
3896                        if found.is_err() {
3897                            return;
3898                        }
3899                        match update_source_node_rate_limit(node, rate_limit) {
3900                            Ok(true) => found = Ok(true),
3901                            Ok(false) => {}
3902                            Err(err) => found = Err(err),
3903                        }
3904                    });
3905                }
3906                ThrottleType::Backfill => {
3907                    if fragment_type_mask
3908                        .contains_any(FragmentTypeFlag::backfill_rate_limit_fragments())
3909                    {
3910                        visit_stream_node_mut(stream_node, |node| match node {
3911                            PbNodeBody::StreamCdcScan(node) => {
3912                                node.rate_limit = rate_limit;
3913                                found = Ok(true);
3914                            }
3915                            PbNodeBody::StreamScan(node) => {
3916                                node.rate_limit = rate_limit;
3917                                found = Ok(true);
3918                            }
3919                            PbNodeBody::SourceBackfill(node) => {
3920                                node.rate_limit = rate_limit;
3921                                found = Ok(true);
3922                            }
3923                            PbNodeBody::LocalityProvider(node) => {
3924                                node.rate_limit = rate_limit;
3925                                found = Ok(true);
3926                            }
3927                            _ => {}
3928                        });
3929                    }
3930                }
3931                ThrottleType::Sink => {
3932                    if fragment_type_mask
3933                        .contains_any(FragmentTypeFlag::sink_rate_limit_fragments())
3934                    {
3935                        visit_stream_node_mut(stream_node, |node| {
3936                            if found.is_err() {
3937                                return;
3938                            }
3939                            match update_sink_node_rate_limit(node, rate_limit) {
3940                                Ok(true) => found = Ok(true),
3941                                Ok(false) => {}
3942                                Err(err) => found = Err(err),
3943                            }
3944                        });
3945                    }
3946                }
3947                ThrottleType::Dml => {
3948                    if fragment_type_mask.contains_any(FragmentTypeFlag::dml_rate_limit_fragments())
3949                    {
3950                        visit_stream_node_mut(stream_node, |node| {
3951                            if let PbNodeBody::Dml(node) = node {
3952                                node.rate_limit = rate_limit;
3953                                found = Ok(true);
3954                            }
3955                        });
3956                    }
3957                }
3958                ThrottleType::Unspecified => {}
3959            }
3960            found
3961        };
3962        self.mutate_fragment_by_fragment_id(
3963            fragment_id,
3964            update_rate_limit,
3965            "rate limit node not found",
3966        )
3967        .await
3968    }
3969
3970    /// Note: `FsFetch` created in old versions are not included.
3971    /// Since this is only used for debugging, it should be fine.
3972    pub async fn list_rate_limits(&self) -> MetaResult<Vec<RateLimitInfo>> {
3973        let inner = self.inner.read().await;
3974        let txn = inner.db.begin().await?;
3975
3976        let fragments: Vec<(FragmentId, JobId, i32, StreamNode)> = Fragment::find()
3977            .select_only()
3978            .columns([
3979                fragment::Column::FragmentId,
3980                fragment::Column::JobId,
3981                fragment::Column::FragmentTypeMask,
3982                fragment::Column::StreamNode,
3983            ])
3984            .filter(FragmentTypeMask::intersects_any(
3985                FragmentTypeFlag::rate_limit_fragments(),
3986            ))
3987            .into_tuple()
3988            .all(&txn)
3989            .await?;
3990
3991        let mut rate_limits = Vec::new();
3992        for (fragment_id, job_id, fragment_type_mask, stream_node) in fragments {
3993            let stream_node = stream_node.to_protobuf();
3994            visit_stream_node_body(&stream_node, |node| {
3995                let mut rate_limit = None;
3996                let mut node_name = None;
3997
3998                match node {
3999                    // source rate limit
4000                    PbNodeBody::Source(node) => {
4001                        if let Some(node_inner) = &node.source_inner {
4002                            rate_limit = node_inner.rate_limit;
4003                            node_name = Some("SOURCE");
4004                        }
4005                    }
4006                    PbNodeBody::StreamFsFetch(node) => {
4007                        if let Some(node_inner) = &node.node_inner {
4008                            rate_limit = node_inner.rate_limit;
4009                            node_name = Some("FS_FETCH");
4010                        }
4011                    }
4012                    // backfill rate limit
4013                    PbNodeBody::SourceBackfill(node) => {
4014                        rate_limit = node.rate_limit;
4015                        node_name = Some("SOURCE_BACKFILL");
4016                    }
4017                    PbNodeBody::StreamScan(node) => {
4018                        rate_limit = node.rate_limit;
4019                        node_name = Some("STREAM_SCAN");
4020                    }
4021                    PbNodeBody::StreamCdcScan(node) => {
4022                        rate_limit = node.rate_limit;
4023                        node_name = Some("STREAM_CDC_SCAN");
4024                    }
4025                    PbNodeBody::LocalityProvider(node) => {
4026                        rate_limit = node.rate_limit;
4027                        node_name = Some("LOCALITY_PROVIDER");
4028                    }
4029                    PbNodeBody::Sink(node) => {
4030                        rate_limit = node.rate_limit;
4031                        node_name = Some("SINK");
4032                    }
4033                    PbNodeBody::Dml(node) => {
4034                        rate_limit = node.rate_limit;
4035                        node_name = Some("DML");
4036                    }
4037                    _ => {}
4038                }
4039
4040                if let Some(rate_limit) = rate_limit {
4041                    rate_limits.push(RateLimitInfo {
4042                        fragment_id,
4043                        job_id,
4044                        fragment_type_mask: fragment_type_mask as u32,
4045                        rate_limit,
4046                        node_name: node_name.unwrap().to_owned(),
4047                    });
4048                }
4049            });
4050        }
4051
4052        Ok(rate_limits)
4053    }
4054}
4055
4056/// Validates altering `alter_props` of a sink. `altered_field_names` are all the keys being
4057/// altered, including secret-backed ones that are not part of `alter_props`.
4058fn validate_sink_props(
4059    sink: &sink::Model,
4060    alter_props: &BTreeMap<String, String>,
4061    altered_field_names: &[String],
4062) -> MetaResult<()> {
4063    let Some(connector) = sink.properties.inner_ref().get(CONNECTOR_TYPE_KEY) else {
4064        return Err(SinkError::Config(anyhow!("connector not specified when alter sink")).into());
4065    };
4066    let connector_type = connector.to_lowercase();
4067    check_sink_allow_alter_on_fly_fields(&connector_type, altered_field_names)
4068        .map_err(|e| SinkError::Config(anyhow!(e)))?;
4069
4070    // Validate against the config the sink actually runs with: properties stored as secrets
4071    // live in `secret_ref` rather than `properties`, and some of them are required fields.
4072    let mut new_props = LocalSecretManager::global()
4073        .fill_secrets(
4074            sink.properties.0.clone(),
4075            sink.secret_ref
4076                .as_ref()
4077                .map(|secret_ref| secret_ref.to_protobuf())
4078                .unwrap_or_default(),
4079        )
4080        .map_err(MetaError::from)?;
4081    new_props.extend(alter_props.clone());
4082
4083    match_sink_name_str!(
4084        connector_type.as_str(),
4085        SinkType,
4086        SinkType::validate_alter_config_change(&new_props, alter_props),
4087        |sink: &str| Err(SinkError::Config(anyhow!("unsupported sink type {}", sink)))
4088    )?;
4089    Ok(())
4090}
4091
4092fn update_stmt_with_props(
4093    with_properties: &mut Vec<SqlOption>,
4094    props: &BTreeMap<String, String>,
4095) -> MetaResult<()> {
4096    let mut new_sql_options = with_properties
4097        .iter()
4098        .map(|sql_option| (&sql_option.name, sql_option))
4099        .collect::<IndexMap<_, _>>();
4100    let add_sql_options = props
4101        .iter()
4102        .map(|(k, v)| SqlOption::try_from((k, v)))
4103        .collect::<Result<Vec<SqlOption>, ParserError>>()
4104        .map_err(|e| SinkError::Config(anyhow!(e)))?;
4105    new_sql_options.extend(
4106        add_sql_options
4107            .iter()
4108            .map(|sql_option| (&sql_option.name, sql_option)),
4109    );
4110    *with_properties = new_sql_options.into_values().cloned().collect();
4111    Ok(())
4112}
4113
4114fn merge_with_options(with_properties: &mut Vec<SqlOption>, altered_options: Vec<SqlOption>) {
4115    for altered_option in altered_options {
4116        if let Some(existing_option) = with_properties
4117            .iter_mut()
4118            .find(|option| option.name.real_value() == altered_option.name.real_value())
4119        {
4120            *existing_option = altered_option;
4121        } else {
4122            with_properties.push(altered_option);
4123        }
4124    }
4125}
4126
4127async fn ensure_source_props_not_set_by_connection(
4128    txn: &DatabaseTransaction,
4129    source: &source::Model,
4130    alter_props: &BTreeMap<String, String>,
4131    alter_secret_refs: &BTreeMap<String, PbSecretRef>,
4132) -> MetaResult<()> {
4133    let Some(connection_id) = source.connection_id else {
4134        return Ok(());
4135    };
4136
4137    let connection = Connection::find_by_id(connection_id)
4138        .one(txn)
4139        .await?
4140        .ok_or_else(|| {
4141            MetaError::catalog_id_not_found(ObjectType::Connection.as_str(), connection_id)
4142        })?;
4143    let connection_params = connection.params.to_protobuf();
4144
4145    if let Some(key) = alter_props
4146        .keys()
4147        .chain(alter_secret_refs.keys())
4148        .find(|key| {
4149            connection_params.properties.contains_key(*key)
4150                || connection_params.secret_refs.contains_key(*key)
4151        })
4152    {
4153        return Err(MetaError::invalid_parameter(format!(
4154            "Cannot alter source connector property `{key}` because it is set by CONNECTION `{}`. Use ALTER CONNECTION instead.",
4155            connection.name
4156        )));
4157    }
4158
4159    Ok(())
4160}
4161
4162fn update_sink_node_props(
4163    node: &mut PbNodeBody,
4164    sink_id: SinkId,
4165    props: &BTreeMap<String, String>,
4166) -> bool {
4167    let sink_desc = match node {
4168        PbNodeBody::Sink(node) => &mut node.sink_desc,
4169        PbNodeBody::IcebergWithPkIndexWriter(node) => &mut node.sink_desc,
4170        PbNodeBody::IcebergWithPkIndexPositionDeleteMerger(node) => &mut node.sink_desc,
4171        PbNodeBody::CompactionResolver(node) if node.sink_id == sink_id => {
4172            node.properties.extend(props.clone());
4173            return true;
4174        }
4175        _ => return false,
4176    };
4177    if let Some(sink_desc) = sink_desc
4178        && sink_desc.id == sink_id
4179    {
4180        sink_desc.properties.extend(props.clone());
4181        true
4182    } else {
4183        false
4184    }
4185}
4186
4187async fn update_sink_fragment_props(
4188    txn: &DatabaseTransaction,
4189    sink_id: SinkId,
4190    props: BTreeMap<String, String>,
4191) -> MetaResult<()> {
4192    let fragments: Vec<(FragmentId, StreamNode)> = Fragment::find()
4193        .select_only()
4194        .columns([fragment::Column::FragmentId, fragment::Column::StreamNode])
4195        .filter(fragment::Column::JobId.eq(sink_id))
4196        .into_tuple()
4197        .all(txn)
4198        .await?;
4199    let fragments = fragments
4200        .into_iter()
4201        .filter_map(|(id, stream_node)| {
4202            let mut stream_node = stream_node.to_protobuf();
4203            let mut found = false;
4204            visit_stream_node_mut(&mut stream_node, |node| {
4205                found |= update_sink_node_props(node, sink_id, &props);
4206            });
4207            if found { Some((id, stream_node)) } else { None }
4208        })
4209        .collect_vec();
4210    if fragments.is_empty() {
4211        return Err(MetaError::invalid_parameter(format!(
4212            "sink {sink_id} is not used by any fragment"
4213        )));
4214    }
4215    for (id, stream_node) in fragments {
4216        Fragment::update(fragment::ActiveModel {
4217            fragment_id: Set(id),
4218            stream_node: Set(StreamNode::from(&stream_node)),
4219            ..Default::default()
4220        })
4221        .exec(txn)
4222        .await?;
4223    }
4224    Ok(())
4225}
4226
4227pub struct SinkIntoTableContext {
4228    /// For alter table (e.g., add column), this is the list of existing sink ids
4229    /// otherwise empty.
4230    pub updated_sink_catalogs: Vec<SinkId>,
4231}
4232
4233pub struct FinishAutoRefreshSchemaSinkContext {
4234    pub tmp_sink_id: SinkId,
4235    pub original_sink_id: SinkId,
4236    pub columns: Vec<PbColumnCatalog>,
4237    pub new_log_store_table: Option<Box<PbTable>>,
4238}
4239
4240async fn update_connector_props_fragments<F>(
4241    txn: &DatabaseTransaction,
4242    job_ids: Vec<JobId>,
4243    expect_flag: FragmentTypeFlag,
4244    mut alter_stream_node_fn: F,
4245    is_shared_source: bool,
4246) -> MetaResult<()>
4247where
4248    F: FnMut(&mut PbNodeBody, &mut bool),
4249{
4250    let fragments: Vec<(FragmentId, StreamNode)> = Fragment::find()
4251        .select_only()
4252        .columns([fragment::Column::FragmentId, fragment::Column::StreamNode])
4253        .filter(
4254            fragment::Column::JobId
4255                .is_in(job_ids.clone())
4256                .and(FragmentTypeMask::intersects(expect_flag)),
4257        )
4258        .into_tuple()
4259        .all(txn)
4260        .await?;
4261    let fragments = fragments
4262        .into_iter()
4263        .filter_map(|(id, stream_node)| {
4264            let mut stream_node = stream_node.to_protobuf();
4265            let mut found = false;
4266            visit_stream_node_mut(&mut stream_node, |node| {
4267                alter_stream_node_fn(node, &mut found);
4268            });
4269            if found { Some((id, stream_node)) } else { None }
4270        })
4271        .collect_vec();
4272    if is_shared_source || job_ids.len() > 1 {
4273        // the first element is the source_id or associated table_id
4274        // if the source is non-shared, there is no updated fragments
4275        // job_ids.len() > 1 means the source is used by other streaming jobs, so there should be at least one fragment updated
4276        assert!(
4277            !fragments.is_empty(),
4278            "job ids {:?} (type: {:?}) should be used by at least one fragment",
4279            job_ids,
4280            expect_flag
4281        );
4282    }
4283
4284    for (id, stream_node) in fragments {
4285        Fragment::update(fragment::ActiveModel {
4286            fragment_id: Set(id),
4287            stream_node: Set(StreamNode::from(&stream_node)),
4288            ..Default::default()
4289        })
4290        .exec(txn)
4291        .await?;
4292    }
4293
4294    Ok(())
4295}
4296
4297#[cfg(test)]
4298mod tests {
4299    use std::collections::BTreeMap;
4300
4301    use risingwave_pb::stream_plan::{
4302        CompactionResolverNode, IcebergWithPkIndexPositionDeleteMergerNode,
4303        IcebergWithPkIndexWriterNode, SinkDesc, SinkNode,
4304    };
4305    use risingwave_sqlparser::ast::{SqlOption, Statement};
4306
4307    use super::{Parser, PbNodeBody, SinkId, merge_with_options, update_sink_node_props};
4308
4309    #[test]
4310    fn test_update_sink_props_in_all_sink_nodes() {
4311        let sink_id = SinkId::new(42);
4312        let props = BTreeMap::from([("enable_compaction".to_owned(), "true".to_owned())]);
4313        let sink_desc = SinkDesc {
4314            id: sink_id,
4315            properties: BTreeMap::from([
4316                ("connector".to_owned(), "iceberg".to_owned()),
4317                ("enable_compaction".to_owned(), "false".to_owned()),
4318            ]),
4319            ..Default::default()
4320        };
4321        let nodes = [
4322            PbNodeBody::Sink(Box::new(SinkNode {
4323                sink_desc: Some(sink_desc.clone()),
4324                ..Default::default()
4325            })),
4326            PbNodeBody::IcebergWithPkIndexWriter(Box::new(IcebergWithPkIndexWriterNode {
4327                sink_desc: Some(sink_desc.clone()),
4328                ..Default::default()
4329            })),
4330            PbNodeBody::IcebergWithPkIndexPositionDeleteMerger(Box::new(
4331                IcebergWithPkIndexPositionDeleteMergerNode {
4332                    sink_desc: Some(sink_desc.clone()),
4333                },
4334            )),
4335            PbNodeBody::CompactionResolver(Box::new(CompactionResolverNode {
4336                sink_id,
4337                properties: sink_desc.properties,
4338                ..Default::default()
4339            })),
4340        ];
4341        for mut node in nodes {
4342            assert!(!update_sink_node_props(&mut node, SinkId::new(43), &props));
4343            assert!(update_sink_node_props(&mut node, sink_id, &props));
4344            let properties = match &node {
4345                PbNodeBody::Sink(node) => &node.sink_desc.as_ref().unwrap().properties,
4346                PbNodeBody::IcebergWithPkIndexWriter(node) => {
4347                    &node.sink_desc.as_ref().unwrap().properties
4348                }
4349                PbNodeBody::IcebergWithPkIndexPositionDeleteMerger(node) => {
4350                    &node.sink_desc.as_ref().unwrap().properties
4351                }
4352                PbNodeBody::CompactionResolver(node) => &node.properties,
4353                _ => unreachable!(),
4354            };
4355            assert_eq!(properties["enable_compaction"], "true");
4356            assert_eq!(properties["connector"], "iceberg");
4357        }
4358    }
4359
4360    #[test]
4361    fn test_merge_with_options_normalizes_altered_option_name() {
4362        let mut statements = Parser::parse_sql(
4363            "CREATE SOURCE s WITH (properties.receive.message.max.bytes = 'old', \
4364             connection = kafka_conn) FORMAT PLAIN ENCODE JSON",
4365        )
4366        .unwrap();
4367        let Statement::CreateSource { stmt } = statements.remove(0) else {
4368            unreachable!()
4369        };
4370        let mut with_properties = stmt.with_properties.0;
4371        let altered_name = "properties.receive.message.max.bytes".to_owned();
4372        let altered_value = "new".to_owned();
4373
4374        merge_with_options(
4375            &mut with_properties,
4376            vec![SqlOption::try_from((&altered_name, &altered_value)).unwrap()],
4377        );
4378
4379        assert_eq!(with_properties.len(), 2);
4380        assert_eq!(
4381            with_properties[0].to_string(),
4382            "properties.receive.\"message\".\"max\".bytes = 'new'"
4383        );
4384        assert_eq!(with_properties[1].to_string(), "connection = kafka_conn");
4385    }
4386}