Skip to main content

risingwave_meta/controller/
fragment.rs

1// Copyright 2023 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::hash_map::Entry;
16use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
17use std::sync::Arc;
18
19use anyhow::{Context, anyhow};
20use futures::TryStreamExt;
21use itertools::{Either, Itertools};
22use risingwave_common::bail;
23use risingwave_common::bitmap::Bitmap;
24use risingwave_common::catalog::{FragmentTypeFlag, FragmentTypeMask};
25use risingwave_common::hash::{VnodeCount, VnodeCountCompat};
26use risingwave_common::id::JobId;
27use risingwave_common::system_param::AdaptiveParallelismStrategy;
28use risingwave_common::system_param::adaptive_parallelism_strategy::parse_strategy;
29use risingwave_common::util::stream_graph_visitor::visit_stream_node_body;
30use risingwave_connector::source::SplitImpl;
31use risingwave_connector::source::cdc::CdcScanOptions;
32use risingwave_meta_model::fragment::DistributionType;
33use risingwave_meta_model::object::ObjectType;
34use risingwave_meta_model::prelude::{
35    Fragment as FragmentModel, FragmentRelation, FragmentSplits, Sink, StreamingJob,
36};
37use risingwave_meta_model::{
38    ActorId, ConnectorSplits, DatabaseId, DispatcherType, ExprContext, FragmentId, I32Array,
39    JobStatus, ObjectId, SchemaId, SinkId, SourceId, StreamNode, StreamingParallelism, TableId,
40    TableIdArray, VnodeBitmap, WorkerId, database, fragment, fragment_relation, fragment_splits,
41    object, sink, source, streaming_job, table,
42};
43use risingwave_meta_model_migration::{ExprTrait, OnConflict, SimpleExpr};
44use risingwave_pb::catalog::PbTable;
45use risingwave_pb::common::PbActorLocation;
46use risingwave_pb::meta::subscribe_response::{
47    Info as NotificationInfo, Operation as NotificationOperation,
48};
49use risingwave_pb::meta::table_fragments::fragment::{
50    FragmentDistributionType, PbFragmentDistributionType,
51};
52use risingwave_pb::meta::table_fragments::{PbActorStatus, PbState};
53use risingwave_pb::meta::{FragmentDistribution, PbFragmentWorkerSlotMapping};
54use risingwave_pb::source::{ConnectorSplit, PbConnectorSplits};
55use risingwave_pb::stream_plan;
56use risingwave_pb::stream_plan::stream_node::NodeBody;
57use risingwave_pb::stream_plan::{
58    PbDispatchOutputMapping, PbDispatcherType, PbStreamNode, PbStreamScanType, SinkLogStoreType,
59    StreamScanType,
60};
61use sea_orm::ActiveValue::Set;
62use sea_orm::sea_query::Expr;
63use sea_orm::{
64    ColumnTrait, ConnectionTrait, DatabaseTransaction, EntityTrait, FromQueryResult, JoinType,
65    PaginatorTrait, QueryFilter, QuerySelect, RelationTrait, StreamTrait, TransactionTrait,
66};
67use serde::{Deserialize, Serialize};
68
69use crate::barrier::{SharedActorInfos, SharedFragmentInfo, SnapshotBackfillInfo};
70use crate::controller::catalog::{CatalogController, CatalogControllerInner};
71use crate::controller::scale::{
72    FragmentRenderMap, LoadedFragmentContext, NoShuffleEnsemble, RenderedGraph,
73    find_fragment_no_shuffle_dags_detailed, load_fragment_context_for_jobs,
74    render_actor_assignments, resolve_streaming_job_definition,
75};
76use crate::controller::utils::{
77    FragmentDesc, PartialActorLocation, PartialFragmentStateTables, compose_dispatchers,
78    get_sink_fragment_by_ids, has_table_been_migrated, rebuild_fragment_mapping,
79    resolve_no_shuffle_actor_mapping,
80};
81use crate::error::MetaError;
82use crate::manager::{ActiveStreamingWorkerNodes, LocalNotification, NotificationManager};
83use crate::model::{
84    DownstreamFragmentRelation, Fragment, FragmentActorDispatchers, FragmentDownstreamRelation,
85    StreamActor, StreamContext, StreamJobFragments, StreamingJobModelContextExt as _,
86};
87use crate::rpc::ddl_controller::build_upstream_sink_info;
88use crate::stream::UpstreamSinkInfo;
89use crate::{MetaResult, model};
90
91/// Some information of running (inflight) actors.
92#[derive(Debug)]
93pub struct InflightActorInfo {
94    pub worker_id: WorkerId,
95    pub vnode_bitmap: Option<Bitmap>,
96    pub splits: Vec<SplitImpl>,
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
100struct ActorInfo {
101    pub actor_id: ActorId,
102    pub fragment_id: FragmentId,
103    pub splits: ConnectorSplits,
104    pub worker_id: WorkerId,
105    pub vnode_bitmap: Option<VnodeBitmap>,
106    pub expr_context: ExprContext,
107    pub config_override: Arc<str>,
108}
109
110#[derive(Debug)]
111struct FragmentDescRow {
112    fragment_id: FragmentId,
113    job_id: JobId,
114    fragment_type_mask: i32,
115    distribution_type: DistributionType,
116    state_table_ids: TableIdArray,
117    vnode_count: i32,
118    parallelism_override: Option<StreamingParallelism>,
119    stream_node: Option<StreamNode>,
120}
121
122#[derive(Debug)]
123pub struct InflightFragmentInfo {
124    pub fragment_id: FragmentId,
125    pub distribution_type: DistributionType,
126    pub fragment_type_mask: FragmentTypeMask,
127    pub vnode_count: usize,
128    pub nodes: PbStreamNode,
129    pub actors: HashMap<ActorId, InflightActorInfo>,
130    pub state_table_ids: HashSet<TableId>,
131}
132
133#[derive(Clone, Debug)]
134pub struct FragmentServingInfo {
135    /// The query-visible result table for this job, if it has one.
136    /// Sink/source jobs have no serving target.
137    pub result_table_id: Option<TableId>,
138    pub distribution_type: FragmentDistributionType,
139    pub vnode_count: usize,
140}
141
142#[easy_ext::ext(FragmentTypeMaskExt)]
143pub impl FragmentTypeMask {
144    /// Matches fragments whose creation progress cannot be recovered after a failure.
145    fn contains_non_recoverable_fragment() -> SimpleExpr {
146        Self::intersects(FragmentTypeFlag::Values)
147    }
148
149    fn intersects(flag: FragmentTypeFlag) -> SimpleExpr {
150        Expr::col(fragment::Column::FragmentTypeMask)
151            .bit_and(Expr::value(flag as i32))
152            .ne(0)
153    }
154
155    fn intersects_any(flags: impl IntoIterator<Item = FragmentTypeFlag>) -> SimpleExpr {
156        Expr::col(fragment::Column::FragmentTypeMask)
157            .bit_and(Expr::value(FragmentTypeFlag::raw_flag(flags) as i32))
158            .ne(0)
159    }
160
161    fn disjoint(flag: FragmentTypeFlag) -> SimpleExpr {
162        Expr::col(fragment::Column::FragmentTypeMask)
163            .bit_and(Expr::value(flag as i32))
164            .eq(0)
165    }
166}
167
168#[derive(Clone, Debug, FromQueryResult, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")] // for dashboard
170pub struct StreamingJobInfo {
171    pub job_id: JobId,
172    pub obj_type: ObjectType,
173    pub name: String,
174    pub job_status: JobStatus,
175    pub parallelism: StreamingParallelism,
176    pub adaptive_parallelism_strategy: Option<String>,
177    // These backfill fields are only used to derive the effective parallelism shown for
178    // in-progress jobs. They are skipped in JSON responses so existing dashboard payloads keep
179    // the same schema.
180    #[serde(skip)]
181    pub backfill_parallelism: Option<StreamingParallelism>,
182    #[serde(skip)]
183    pub backfill_adaptive_parallelism_strategy: Option<String>,
184    pub max_parallelism: i32,
185    pub resource_group: String,
186    pub config_override: String,
187    pub database_id: DatabaseId,
188    pub schema_id: SchemaId,
189}
190
191impl NotificationManager {
192    /// Notify frontend about streaming worker slot mapping changes.
193    ///
194    /// This only sends streaming mapping updates to frontends. Serving mapping
195    /// notifications are decoupled and driven by fragment model changes (insert/delete)
196    /// instead of barrier-driven actor set changes.
197    pub(crate) fn notify_streaming_fragment_mapping(
198        &self,
199        operation: NotificationOperation,
200        fragment_mappings: Vec<PbFragmentWorkerSlotMapping>,
201    ) {
202        if fragment_mappings.is_empty() {
203            return;
204        }
205        // notify all fragment mappings to frontend.
206        for fragment_mapping in fragment_mappings {
207            self.notify_frontend_without_version(
208                operation,
209                NotificationInfo::StreamingWorkerSlotMapping(fragment_mapping),
210            );
211        }
212    }
213
214    /// Notify the serving module about fragment mapping changes.
215    ///
216    /// This should be called when fragments are inserted into or deleted from the meta store,
217    /// so that serving vnode mappings are kept in sync with the fragment model.
218    pub(crate) fn notify_serving_fragment_mapping_update(
219        &self,
220        fragment_ids: Vec<crate::model::FragmentId>,
221    ) {
222        if fragment_ids.is_empty() {
223            return;
224        }
225        self.notify_local_subscribers(LocalNotification::ServingFragmentMappingsUpsert(
226            fragment_ids,
227        ));
228    }
229
230    /// Notify the serving module about fragment mapping deletions.
231    ///
232    /// This should be called when fragments are deleted from the meta store,
233    /// so that serving vnode mappings are cleaned up.
234    pub(crate) fn notify_serving_fragment_mapping_delete(
235        &self,
236        fragment_ids: Vec<crate::model::FragmentId>,
237    ) {
238        if fragment_ids.is_empty() {
239            return;
240        }
241        self.notify_local_subscribers(LocalNotification::ServingFragmentMappingsDelete(
242            fragment_ids,
243        ));
244    }
245}
246
247impl CatalogControllerInner {
248    /// Returns distribution type, vnode count and query-visible result table for all fragments.
249    ///
250    /// Reads directly from the persistent catalog rather than from the in-memory
251    /// `shared_actor_infos`. This is critical because the serving vnode mapping
252    /// must be available even before recovery has populated `shared_actor_infos`.
253    pub async fn fragment_serving_infos(
254        &self,
255    ) -> MetaResult<HashMap<FragmentId, FragmentServingInfo>> {
256        let query = FragmentModel::find().select_only().columns([
257            fragment::Column::FragmentId,
258            fragment::Column::JobId,
259            fragment::Column::DistributionType,
260            fragment::Column::VnodeCount,
261            fragment::Column::StateTableIds,
262        ]);
263        let fragments: Vec<(FragmentId, JobId, DistributionType, i32, TableIdArray)> =
264            query.into_tuple().all(&self.db).await?;
265
266        Ok(fragments
267            .into_iter()
268            .map(
269                |(fragment_id, job_id, distribution_type, vnode_count, state_table_ids)| {
270                    // Table/MV/index result tables reuse the job id and appear only in their
271                    // owning fragment; sink/source jobs therefore have no matching state table.
272                    let result_table_id = job_id.as_mv_table_id();
273                    (
274                        fragment_id,
275                        FragmentServingInfo {
276                            result_table_id: state_table_ids
277                                .0
278                                .contains(&result_table_id)
279                                .then_some(result_table_id),
280                            distribution_type: PbFragmentDistributionType::from(distribution_type),
281                            vnode_count: vnode_count as usize,
282                        },
283                    )
284                },
285            )
286            .collect())
287    }
288}
289
290impl CatalogController {
291    pub fn prepare_fragment_models_from_fragments(
292        job_id: JobId,
293        fragments: impl Iterator<Item = &Fragment>,
294    ) -> MetaResult<Vec<fragment::Model>> {
295        fragments
296            .map(|fragment| Self::prepare_fragment_model_for_new_job(job_id, fragment))
297            .try_collect()
298    }
299
300    pub fn prepare_fragment_model_for_new_job(
301        job_id: JobId,
302        fragment: &Fragment,
303    ) -> MetaResult<fragment::Model> {
304        let vnode_count = fragment.vnode_count();
305        let Fragment {
306            fragment_id: pb_fragment_id,
307            fragment_type_mask: pb_fragment_type_mask,
308            distribution_type: pb_distribution_type,
309            state_table_ids: pb_state_table_ids,
310            nodes,
311            ..
312        } = fragment;
313
314        let state_table_ids = pb_state_table_ids.clone().into();
315
316        let fragment_parallelism = nodes
317            .node_body
318            .as_ref()
319            .and_then(|body| match body {
320                NodeBody::StreamCdcScan(node) => Some(node),
321                _ => None,
322            })
323            .and_then(|node| node.options.as_ref())
324            .map(CdcScanOptions::from_proto)
325            .filter(|opts| opts.is_parallelized_backfill())
326            .map(|opts| StreamingParallelism::Fixed(opts.backfill_parallelism as usize));
327
328        let stream_node = StreamNode::from(nodes);
329
330        let distribution_type = PbFragmentDistributionType::try_from(*pb_distribution_type)
331            .unwrap()
332            .into();
333
334        #[expect(deprecated)]
335        let fragment = fragment::Model {
336            fragment_id: *pb_fragment_id as _,
337            job_id,
338            fragment_type_mask: (*pb_fragment_type_mask).into(),
339            distribution_type,
340            stream_node,
341            state_table_ids,
342            upstream_fragment_id: Default::default(),
343            vnode_count: vnode_count as _,
344            parallelism: fragment_parallelism,
345        };
346
347        Ok(fragment)
348    }
349
350    #[expect(clippy::type_complexity)]
351    fn compose_table_fragments(
352        job_id: JobId,
353        state: PbState,
354        ctx: StreamContext,
355        fragments: Vec<(fragment::Model, Vec<ActorInfo>)>,
356        max_parallelism: usize,
357        job_definition: Option<String>,
358    ) -> MetaResult<(
359        StreamJobFragments,
360        HashMap<FragmentId, Vec<StreamActor>>,
361        HashMap<crate::model::ActorId, PbActorStatus>,
362    )> {
363        let mut pb_fragments = BTreeMap::new();
364        let mut fragment_actors = HashMap::new();
365        let mut all_actor_status = HashMap::new();
366
367        for (fragment, actors) in fragments {
368            let (fragment, actors, actor_status, _) =
369                Self::compose_fragment(fragment, actors, job_definition.clone())?;
370            let fragment_id = fragment.fragment_id;
371            fragment_actors.insert(fragment_id, actors);
372            all_actor_status.extend(actor_status);
373
374            pb_fragments.insert(fragment_id, fragment);
375        }
376
377        let table_fragments = StreamJobFragments {
378            stream_job_id: job_id,
379            state: state as _,
380            fragments: pb_fragments,
381            ctx,
382            max_parallelism,
383        };
384
385        Ok((table_fragments, fragment_actors, all_actor_status))
386    }
387
388    #[expect(clippy::type_complexity)]
389    fn compose_fragment(
390        fragment: fragment::Model,
391        actors: Vec<ActorInfo>,
392        job_definition: Option<String>,
393    ) -> MetaResult<(
394        Fragment,
395        Vec<StreamActor>,
396        HashMap<crate::model::ActorId, PbActorStatus>,
397        HashMap<crate::model::ActorId, PbConnectorSplits>,
398    )> {
399        let fragment::Model {
400            fragment_id,
401            fragment_type_mask,
402            distribution_type,
403            stream_node,
404            state_table_ids,
405            vnode_count,
406            ..
407        } = fragment;
408
409        let stream_node = stream_node.to_protobuf();
410        let mut upstream_fragments = HashSet::new();
411        visit_stream_node_body(&stream_node, |body| {
412            if let NodeBody::Merge(m) = body {
413                assert!(
414                    upstream_fragments.insert(m.upstream_fragment_id),
415                    "non-duplicate upstream fragment"
416                );
417            }
418        });
419
420        let mut pb_actors = vec![];
421
422        let mut pb_actor_status = HashMap::new();
423        let mut pb_actor_splits = HashMap::new();
424
425        for actor in actors {
426            if actor.fragment_id != fragment_id {
427                bail!(
428                    "fragment id {} from actor {} is different from fragment {}",
429                    actor.fragment_id,
430                    actor.actor_id,
431                    fragment_id
432                )
433            }
434
435            let ActorInfo {
436                actor_id,
437                fragment_id,
438                worker_id,
439                splits,
440                vnode_bitmap,
441                expr_context,
442                config_override,
443                ..
444            } = actor;
445
446            let vnode_bitmap =
447                vnode_bitmap.map(|vnode_bitmap| Bitmap::from(vnode_bitmap.to_protobuf()));
448            let pb_expr_context = Some(expr_context.to_protobuf());
449
450            pb_actor_status.insert(
451                actor_id as _,
452                PbActorStatus {
453                    location: PbActorLocation::from_worker(worker_id),
454                },
455            );
456
457            pb_actor_splits.insert(actor_id as _, splits.to_protobuf());
458
459            pb_actors.push(StreamActor {
460                actor_id: actor_id as _,
461                fragment_id: fragment_id as _,
462                vnode_bitmap,
463                mview_definition: job_definition.clone().unwrap_or("".to_owned()),
464                expr_context: pb_expr_context,
465                config_override,
466            })
467        }
468
469        let pb_state_table_ids = state_table_ids.0;
470        let pb_distribution_type = PbFragmentDistributionType::from(distribution_type) as _;
471        let pb_fragment = Fragment {
472            fragment_id: fragment_id as _,
473            fragment_type_mask: fragment_type_mask.into(),
474            distribution_type: pb_distribution_type,
475            state_table_ids: pb_state_table_ids,
476            maybe_vnode_count: VnodeCount::set(vnode_count).to_protobuf(),
477            nodes: stream_node,
478        };
479
480        Ok((pb_fragment, pb_actors, pb_actor_status, pb_actor_splits))
481    }
482
483    pub async fn fragment_serving_infos(
484        &self,
485    ) -> MetaResult<HashMap<FragmentId, FragmentServingInfo>> {
486        let inner = self.inner.read().await;
487        inner.fragment_serving_infos().await
488    }
489
490    pub async fn fragment_job_mapping(&self) -> MetaResult<HashMap<FragmentId, JobId>> {
491        let inner = self.inner.read().await;
492        let fragment_jobs: Vec<(FragmentId, JobId)> = FragmentModel::find()
493            .select_only()
494            .columns([fragment::Column::FragmentId, fragment::Column::JobId])
495            .into_tuple()
496            .all(&inner.db)
497            .await?;
498        Ok(fragment_jobs.into_iter().collect())
499    }
500
501    pub async fn get_fragment_job_id(
502        &self,
503        fragment_ids: Vec<FragmentId>,
504    ) -> MetaResult<Vec<ObjectId>> {
505        let inner = self.inner.read().await;
506        self.get_fragment_job_id_in_txn(&inner.db, fragment_ids)
507            .await
508    }
509
510    pub async fn get_fragment_job_id_in_txn<C>(
511        &self,
512        txn: &C,
513        fragment_ids: Vec<FragmentId>,
514    ) -> MetaResult<Vec<ObjectId>>
515    where
516        C: ConnectionTrait + Send,
517    {
518        let object_ids: Vec<ObjectId> = FragmentModel::find()
519            .select_only()
520            .column(fragment::Column::JobId)
521            .filter(fragment::Column::FragmentId.is_in(fragment_ids))
522            .into_tuple()
523            .all(txn)
524            .await?;
525
526        Ok(object_ids)
527    }
528
529    pub async fn get_fragment_desc_by_id(
530        &self,
531        fragment_id: FragmentId,
532    ) -> MetaResult<Option<(FragmentDesc, Vec<FragmentId>)>> {
533        let inner = self.inner.read().await;
534
535        let fragment_model = match FragmentModel::find_by_id(fragment_id)
536            .one(&inner.db)
537            .await?
538        {
539            Some(fragment) => fragment,
540            None => return Ok(None),
541        };
542
543        let job_parallelism: Option<(StreamingParallelism, Option<String>)> =
544            StreamingJob::find_by_id(fragment_model.job_id)
545                .select_only()
546                .columns([
547                    streaming_job::Column::Parallelism,
548                    streaming_job::Column::AdaptiveParallelismStrategy,
549                ])
550                .into_tuple::<(StreamingParallelism, Option<String>)>()
551                .one(&inner.db)
552                .await?;
553
554        let upstream_entries: Vec<(FragmentId, DispatcherType)> = FragmentRelation::find()
555            .select_only()
556            .columns([
557                fragment_relation::Column::SourceFragmentId,
558                fragment_relation::Column::DispatcherType,
559            ])
560            .filter(fragment_relation::Column::TargetFragmentId.eq(fragment_id))
561            .into_tuple()
562            .all(&inner.db)
563            .await?;
564
565        let upstreams: Vec<_> = upstream_entries
566            .into_iter()
567            .map(|(source_id, _)| source_id)
568            .collect();
569
570        let root_fragment_map = find_fragment_no_shuffle_dags_detailed(&inner.db, &[fragment_id])
571            .await
572            .map(Self::collect_root_fragment_mapping)?;
573        let root_fragments = root_fragment_map
574            .get(&fragment_id)
575            .cloned()
576            .unwrap_or_default();
577
578        let info = self.env.shared_actor_infos().read_guard();
579        let SharedFragmentInfo { actors, .. } = info
580            .get_fragment(fragment_model.fragment_id as _)
581            .unwrap_or_else(|| {
582                panic!(
583                    "Failed to retrieve fragment description: fragment {} (job_id {}) not found in shared actor info",
584                    fragment_model.fragment_id,
585                    fragment_model.job_id
586                )
587            });
588
589        let parallelism_policy = Self::format_fragment_parallelism_policy(
590            fragment_model.distribution_type,
591            fragment_model.parallelism.as_ref(),
592            job_parallelism.as_ref().map(|(parallelism, _)| parallelism),
593            job_parallelism
594                .as_ref()
595                .and_then(|(_, strategy)| strategy.as_deref()),
596            &root_fragments,
597        );
598
599        let fragment = FragmentDesc {
600            fragment_id: fragment_model.fragment_id,
601            job_id: fragment_model.job_id,
602            fragment_type_mask: fragment_model.fragment_type_mask,
603            distribution_type: fragment_model.distribution_type,
604            state_table_ids: fragment_model.state_table_ids.clone(),
605            parallelism: actors.len() as _,
606            vnode_count: fragment_model.vnode_count,
607            stream_node: fragment_model.stream_node.clone(),
608            parallelism_policy,
609        };
610
611        Ok(Some((fragment, upstreams)))
612    }
613
614    pub async fn list_fragment_database_ids(
615        &self,
616        select_fragment_ids: Option<Vec<FragmentId>>,
617    ) -> MetaResult<Vec<(FragmentId, DatabaseId)>> {
618        let inner = self.inner.read().await;
619        let select = FragmentModel::find()
620            .select_only()
621            .column(fragment::Column::FragmentId)
622            .column(object::Column::DatabaseId)
623            .join(JoinType::InnerJoin, fragment::Relation::Object.def());
624        let select = if let Some(select_fragment_ids) = select_fragment_ids {
625            select.filter(fragment::Column::FragmentId.is_in(select_fragment_ids))
626        } else {
627            select
628        };
629        Ok(select.into_tuple().all(&inner.db).await?)
630    }
631
632    pub async fn get_job_fragments_by_id(
633        &self,
634        job_id: JobId,
635    ) -> MetaResult<(
636        StreamJobFragments,
637        HashMap<FragmentId, Vec<StreamActor>>,
638        HashMap<ActorId, PbActorStatus>,
639    )> {
640        let inner = self.inner.read().await;
641
642        // Load fragments matching the job from the database
643        let fragments: Vec<_> = FragmentModel::find()
644            .filter(fragment::Column::JobId.eq(job_id))
645            .all(&inner.db)
646            .await?;
647
648        let job_info = StreamingJob::find_by_id(job_id)
649            .one(&inner.db)
650            .await?
651            .ok_or_else(|| anyhow::anyhow!("job {} not found in database", job_id))?;
652
653        let fragment_actors =
654            self.collect_fragment_actor_pairs(fragments, job_info.stream_context())?;
655
656        let job_definition = resolve_streaming_job_definition(&inner.db, &HashSet::from([job_id]))
657            .await?
658            .remove(&job_id);
659
660        Self::compose_table_fragments(
661            job_id,
662            job_info.job_status.into(),
663            job_info.stream_context(),
664            fragment_actors,
665            job_info.max_parallelism as _,
666            job_definition,
667        )
668    }
669
670    pub async fn get_fragment_actor_dispatchers(
671        &self,
672        fragment_ids: Vec<FragmentId>,
673    ) -> MetaResult<FragmentActorDispatchers> {
674        let inner = self.inner.read().await;
675
676        self.get_fragment_actor_dispatchers_txn(&inner.db, fragment_ids)
677            .await
678    }
679
680    pub async fn get_fragment_actor_dispatchers_txn(
681        &self,
682        c: &impl ConnectionTrait,
683        fragment_ids: Vec<FragmentId>,
684    ) -> MetaResult<FragmentActorDispatchers> {
685        let fragment_relations = FragmentRelation::find()
686            .filter(fragment_relation::Column::SourceFragmentId.is_in(fragment_ids))
687            .all(c)
688            .await?;
689
690        type FragmentActorInfo = (
691            DistributionType,
692            Arc<HashMap<crate::model::ActorId, Option<Bitmap>>>,
693        );
694
695        let shared_info = self.env.shared_actor_infos();
696        let mut fragment_actor_cache: HashMap<FragmentId, FragmentActorInfo> = HashMap::new();
697        let get_fragment_actors = |fragment_id: FragmentId| async move {
698            let result: MetaResult<FragmentActorInfo> = try {
699                let read_guard = shared_info.read_guard();
700
701                let fragment = read_guard.get_fragment(fragment_id as _).unwrap();
702
703                (
704                    fragment.distribution_type,
705                    Arc::new(
706                        fragment
707                            .actors
708                            .iter()
709                            .map(|(actor_id, actor_info)| {
710                                (
711                                    *actor_id,
712                                    actor_info
713                                        .vnode_bitmap
714                                        .as_ref()
715                                        .map(|bitmap| Bitmap::from(bitmap.to_protobuf())),
716                                )
717                            })
718                            .collect(),
719                    ),
720                )
721            };
722            result
723        };
724
725        let mut actor_dispatchers_map: HashMap<_, HashMap<_, Vec<_>>> = HashMap::new();
726        for fragment_relation::Model {
727            source_fragment_id,
728            target_fragment_id,
729            dispatcher_type,
730            dist_key_indices,
731            output_indices,
732            output_type_mapping,
733        } in fragment_relations
734        {
735            let (source_fragment_distribution, source_fragment_actors) = {
736                let (distribution, actors) = {
737                    match fragment_actor_cache.entry(source_fragment_id) {
738                        Entry::Occupied(entry) => entry.into_mut(),
739                        Entry::Vacant(entry) => {
740                            entry.insert(get_fragment_actors(source_fragment_id).await?)
741                        }
742                    }
743                };
744                (*distribution, actors.clone())
745            };
746            let (target_fragment_distribution, target_fragment_actors) = {
747                let (distribution, actors) = {
748                    match fragment_actor_cache.entry(target_fragment_id) {
749                        Entry::Occupied(entry) => entry.into_mut(),
750                        Entry::Vacant(entry) => {
751                            entry.insert(get_fragment_actors(target_fragment_id).await?)
752                        }
753                    }
754                };
755                (*distribution, actors.clone())
756            };
757            let output_mapping = PbDispatchOutputMapping {
758                indices: output_indices.into_u32_array(),
759                types: output_type_mapping.unwrap_or_default().to_protobuf(),
760            };
761            let (dispatchers, _) = compose_dispatchers(
762                source_fragment_distribution,
763                &source_fragment_actors,
764                target_fragment_id as _,
765                target_fragment_distribution,
766                &target_fragment_actors,
767                dispatcher_type,
768                dist_key_indices.into_u32_array(),
769                output_mapping,
770            );
771            let actor_dispatchers_map = actor_dispatchers_map
772                .entry(source_fragment_id as _)
773                .or_default();
774            for (actor_id, dispatchers) in dispatchers {
775                actor_dispatchers_map
776                    .entry(actor_id as _)
777                    .or_default()
778                    .push(dispatchers);
779            }
780        }
781        Ok(actor_dispatchers_map)
782    }
783
784    pub async fn get_fragment_downstream_relations(
785        &self,
786        fragment_ids: Vec<FragmentId>,
787    ) -> MetaResult<FragmentDownstreamRelation> {
788        let inner = self.inner.read().await;
789        self.get_fragment_downstream_relations_in_txn(&inner.db, fragment_ids)
790            .await
791    }
792
793    pub async fn get_fragment_downstream_relations_in_txn<C>(
794        &self,
795        txn: &C,
796        fragment_ids: Vec<FragmentId>,
797    ) -> MetaResult<FragmentDownstreamRelation>
798    where
799        C: ConnectionTrait + StreamTrait + Send,
800    {
801        let mut stream = FragmentRelation::find()
802            .filter(fragment_relation::Column::SourceFragmentId.is_in(fragment_ids))
803            .stream(txn)
804            .await?;
805        let mut relations = FragmentDownstreamRelation::new();
806        while let Some(relation) = stream.try_next().await? {
807            relations
808                .entry(relation.source_fragment_id as _)
809                .or_default()
810                .push(DownstreamFragmentRelation {
811                    downstream_fragment_id: relation.target_fragment_id as _,
812                    dispatcher_type: relation.dispatcher_type,
813                    dist_key_indices: relation.dist_key_indices.into_u32_array(),
814                    output_mapping: PbDispatchOutputMapping {
815                        indices: relation.output_indices.into_u32_array(),
816                        types: relation
817                            .output_type_mapping
818                            .unwrap_or_default()
819                            .to_protobuf(),
820                    },
821                });
822        }
823        Ok(relations)
824    }
825
826    pub async fn get_job_fragment_backfill_scan_type(
827        &self,
828        job_id: JobId,
829    ) -> MetaResult<HashMap<crate::model::FragmentId, PbStreamScanType>> {
830        let inner = self.inner.read().await;
831        self.get_job_fragment_backfill_scan_type_in_txn(&inner.db, job_id)
832            .await
833    }
834
835    pub async fn get_job_fragment_backfill_scan_type_in_txn<C>(
836        &self,
837        txn: &C,
838        job_id: JobId,
839    ) -> MetaResult<HashMap<crate::model::FragmentId, PbStreamScanType>>
840    where
841        C: ConnectionTrait + Send,
842    {
843        let fragments: Vec<_> = FragmentModel::find()
844            .filter(fragment::Column::JobId.eq(job_id))
845            .all(txn)
846            .await?;
847
848        let mut result = HashMap::new();
849
850        for fragment::Model {
851            fragment_id,
852            stream_node,
853            ..
854        } in fragments
855        {
856            let stream_node = stream_node.to_protobuf();
857            visit_stream_node_body(&stream_node, |body| {
858                if let NodeBody::StreamScan(node) = body {
859                    match node.stream_scan_type() {
860                        StreamScanType::Unspecified => {}
861                        scan_type => {
862                            result.insert(fragment_id as crate::model::FragmentId, scan_type);
863                        }
864                    }
865                }
866            });
867        }
868
869        Ok(result)
870    }
871
872    pub async fn count_streaming_jobs(&self) -> MetaResult<usize> {
873        let inner = self.inner.read().await;
874        let count = StreamingJob::find().count(&inner.db).await?;
875        Ok(usize::try_from(count).context("streaming job count overflow")?)
876    }
877
878    pub async fn list_streaming_job_infos(&self) -> MetaResult<Vec<StreamingJobInfo>> {
879        let inner = self.inner.read().await;
880        let job_states = StreamingJob::find()
881            .select_only()
882            .column(streaming_job::Column::JobId)
883            .join(JoinType::InnerJoin, streaming_job::Relation::Object.def())
884            .join(JoinType::InnerJoin, object::Relation::Database2.def())
885            .column(object::Column::ObjType)
886            .join(JoinType::LeftJoin, table::Relation::Object1.def().rev())
887            .join(JoinType::LeftJoin, source::Relation::Object.def().rev())
888            .join(JoinType::LeftJoin, sink::Relation::Object.def().rev())
889            .column_as(
890                Expr::if_null(
891                    Expr::col((table::Entity, table::Column::Name)),
892                    Expr::if_null(
893                        Expr::col((source::Entity, source::Column::Name)),
894                        Expr::if_null(
895                            Expr::col((sink::Entity, sink::Column::Name)),
896                            Expr::val("<unknown>"),
897                        ),
898                    ),
899                ),
900                "name",
901            )
902            .columns([
903                streaming_job::Column::JobStatus,
904                streaming_job::Column::Parallelism,
905                streaming_job::Column::AdaptiveParallelismStrategy,
906                streaming_job::Column::BackfillParallelism,
907                streaming_job::Column::BackfillAdaptiveParallelismStrategy,
908                streaming_job::Column::MaxParallelism,
909            ])
910            .column_as(
911                Expr::if_null(
912                    Expr::col((
913                        streaming_job::Entity,
914                        streaming_job::Column::SpecificResourceGroup,
915                    )),
916                    Expr::col((database::Entity, database::Column::ResourceGroup)),
917                ),
918                "resource_group",
919            )
920            .column_as(
921                Expr::if_null(
922                    Expr::col((streaming_job::Entity, streaming_job::Column::ConfigOverride)),
923                    Expr::val(""),
924                ),
925                "config_override",
926            )
927            .column(object::Column::DatabaseId)
928            .column(object::Column::SchemaId)
929            .into_model()
930            .all(&inner.db)
931            .await?;
932        Ok(job_states)
933    }
934
935    pub async fn get_max_parallelism_by_id(&self, job_id: JobId) -> MetaResult<usize> {
936        let inner = self.inner.read().await;
937        let max_parallelism: i32 = StreamingJob::find_by_id(job_id)
938            .select_only()
939            .column(streaming_job::Column::MaxParallelism)
940            .into_tuple()
941            .one(&inner.db)
942            .await?
943            .ok_or_else(|| anyhow::anyhow!("job {} not found in database", job_id))?;
944        Ok(max_parallelism as usize)
945    }
946
947    /// Try to get internal table ids of each streaming job, used by metrics collection.
948    pub async fn get_job_internal_table_ids(&self) -> Option<Vec<(JobId, Vec<TableId>)>> {
949        if let Ok(inner) = self.inner.try_read()
950            && let Ok(job_state_tables) = FragmentModel::find()
951                .select_only()
952                .columns([fragment::Column::JobId, fragment::Column::StateTableIds])
953                .into_tuple::<(JobId, I32Array)>()
954                .all(&inner.db)
955                .await
956        {
957            let mut job_internal_table_ids = HashMap::new();
958            for (job_id, state_table_ids) in job_state_tables {
959                job_internal_table_ids
960                    .entry(job_id)
961                    .or_insert_with(Vec::new)
962                    .extend(
963                        state_table_ids
964                            .into_inner()
965                            .into_iter()
966                            .map(|table_id| TableId::new(table_id as _)),
967                    );
968            }
969            return Some(job_internal_table_ids.into_iter().collect());
970        }
971        None
972    }
973
974    pub async fn has_any_running_jobs(&self) -> MetaResult<bool> {
975        let inner = self.inner.read().await;
976        let count = FragmentModel::find().count(&inner.db).await?;
977        Ok(count > 0)
978    }
979
980    pub fn worker_actor_count(&self) -> MetaResult<HashMap<WorkerId, usize>> {
981        let read_guard = self.env.shared_actor_infos().read_guard();
982        let actor_cnt: HashMap<WorkerId, _> = read_guard
983            .iter_over_fragments()
984            .flat_map(|(_, fragment)| {
985                fragment
986                    .actors
987                    .iter()
988                    .map(|(actor_id, actor)| (actor.worker_id, *actor_id))
989            })
990            .into_group_map()
991            .into_iter()
992            .map(|(k, v)| (k, v.len()))
993            .collect();
994
995        Ok(actor_cnt)
996    }
997
998    fn collect_fragment_actor_map(
999        &self,
1000        fragment_ids: &[FragmentId],
1001        stream_context: StreamContext,
1002    ) -> MetaResult<HashMap<FragmentId, Vec<ActorInfo>>> {
1003        let guard = self.env.shared_actor_infos().read_guard();
1004        let pb_expr_context = stream_context.to_expr_context();
1005        let expr_context: ExprContext = (&pb_expr_context).into();
1006
1007        let mut actor_map = HashMap::with_capacity(fragment_ids.len());
1008        for fragment_id in fragment_ids {
1009            let fragment_info = guard.get_fragment(*fragment_id as _).ok_or_else(|| {
1010                anyhow!("fragment {} not found in shared actor info", fragment_id)
1011            })?;
1012
1013            let actors = fragment_info
1014                .actors
1015                .iter()
1016                .map(|(actor_id, actor_info)| ActorInfo {
1017                    actor_id: *actor_id as _,
1018                    fragment_id: *fragment_id,
1019                    splits: ConnectorSplits::from(&PbConnectorSplits {
1020                        splits: actor_info.splits.iter().map(ConnectorSplit::from).collect(),
1021                    }),
1022                    worker_id: actor_info.worker_id as _,
1023                    vnode_bitmap: actor_info
1024                        .vnode_bitmap
1025                        .as_ref()
1026                        .map(|bitmap| VnodeBitmap::from(&bitmap.to_protobuf())),
1027                    expr_context: expr_context.clone(),
1028                    config_override: stream_context.config_override.clone(),
1029                })
1030                .collect();
1031
1032            actor_map.insert(*fragment_id, actors);
1033        }
1034
1035        Ok(actor_map)
1036    }
1037
1038    fn collect_fragment_actor_pairs(
1039        &self,
1040        fragments: Vec<fragment::Model>,
1041        stream_context: StreamContext,
1042    ) -> MetaResult<Vec<(fragment::Model, Vec<ActorInfo>)>> {
1043        let fragment_ids: Vec<_> = fragments.iter().map(|f| f.fragment_id).collect();
1044        let mut actor_map = self.collect_fragment_actor_map(&fragment_ids, stream_context)?;
1045        fragments
1046            .into_iter()
1047            .map(|fragment| {
1048                let actors = actor_map.remove(&fragment.fragment_id).ok_or_else(|| {
1049                    anyhow!(
1050                        "fragment {} missing in shared actor info map",
1051                        fragment.fragment_id
1052                    )
1053                })?;
1054                Ok((fragment, actors))
1055            })
1056            .collect()
1057    }
1058
1059    // TODO: This function is too heavy, we should avoid using it and implement others on demand.
1060    pub async fn table_fragments(
1061        &self,
1062    ) -> MetaResult<
1063        BTreeMap<
1064            JobId,
1065            (
1066                StreamJobFragments,
1067                HashMap<FragmentId, Vec<StreamActor>>,
1068                HashMap<crate::model::ActorId, PbActorStatus>,
1069            ),
1070        >,
1071    > {
1072        let inner = self.inner.read().await;
1073        let jobs = StreamingJob::find().all(&inner.db).await?;
1074
1075        let mut job_definition = resolve_streaming_job_definition(
1076            &inner.db,
1077            &HashSet::from_iter(jobs.iter().map(|job| job.job_id)),
1078        )
1079        .await?;
1080
1081        let mut table_fragments = BTreeMap::new();
1082        for job in jobs {
1083            let fragments = FragmentModel::find()
1084                .filter(fragment::Column::JobId.eq(job.job_id))
1085                .all(&inner.db)
1086                .await?;
1087
1088            let fragment_actors =
1089                self.collect_fragment_actor_pairs(fragments, job.stream_context())?;
1090
1091            table_fragments.insert(
1092                job.job_id,
1093                Self::compose_table_fragments(
1094                    job.job_id,
1095                    job.job_status.into(),
1096                    job.stream_context(),
1097                    fragment_actors,
1098                    job.max_parallelism as _,
1099                    job_definition.remove(&job.job_id),
1100                )?,
1101            );
1102        }
1103
1104        Ok(table_fragments)
1105    }
1106
1107    pub async fn upstream_fragments(
1108        &self,
1109        fragment_ids: impl Iterator<Item = crate::model::FragmentId>,
1110    ) -> MetaResult<HashMap<crate::model::FragmentId, HashSet<crate::model::FragmentId>>> {
1111        let inner = self.inner.read().await;
1112        self.upstream_fragments_in_txn(&inner.db, fragment_ids)
1113            .await
1114    }
1115
1116    pub async fn upstream_fragments_in_txn<C>(
1117        &self,
1118        txn: &C,
1119        fragment_ids: impl Iterator<Item = crate::model::FragmentId>,
1120    ) -> MetaResult<HashMap<crate::model::FragmentId, HashSet<crate::model::FragmentId>>>
1121    where
1122        C: ConnectionTrait + StreamTrait + Send,
1123    {
1124        let mut stream = FragmentRelation::find()
1125            .select_only()
1126            .columns([
1127                fragment_relation::Column::SourceFragmentId,
1128                fragment_relation::Column::TargetFragmentId,
1129            ])
1130            .filter(
1131                fragment_relation::Column::TargetFragmentId
1132                    .is_in(fragment_ids.map(|id| id as FragmentId)),
1133            )
1134            .into_tuple::<(FragmentId, FragmentId)>()
1135            .stream(txn)
1136            .await?;
1137        let mut upstream_fragments: HashMap<_, HashSet<_>> = HashMap::new();
1138        while let Some((upstream_fragment_id, downstream_fragment_id)) = stream.try_next().await? {
1139            upstream_fragments
1140                .entry(downstream_fragment_id as crate::model::FragmentId)
1141                .or_default()
1142                .insert(upstream_fragment_id as crate::model::FragmentId);
1143        }
1144        Ok(upstream_fragments)
1145    }
1146
1147    pub fn list_actor_locations(&self) -> MetaResult<Vec<PartialActorLocation>> {
1148        let info = self.env.shared_actor_infos().read_guard();
1149
1150        let actor_locations = info
1151            .iter_over_fragments()
1152            .flat_map(|(fragment_id, fragment)| {
1153                fragment
1154                    .actors
1155                    .iter()
1156                    .map(|(actor_id, actor)| PartialActorLocation {
1157                        actor_id: *actor_id as _,
1158                        fragment_id: *fragment_id as _,
1159                        worker_id: actor.worker_id,
1160                    })
1161            })
1162            .collect_vec();
1163
1164        Ok(actor_locations)
1165    }
1166
1167    pub async fn list_actor_info(
1168        &self,
1169    ) -> MetaResult<Vec<(ActorId, FragmentId, ObjectId, SchemaId, ObjectType)>> {
1170        let inner = self.inner.read().await;
1171
1172        let fragment_objects: Vec<(FragmentId, ObjectId, SchemaId, ObjectType)> =
1173            FragmentModel::find()
1174                .select_only()
1175                .join(JoinType::LeftJoin, fragment::Relation::Object.def())
1176                .column(fragment::Column::FragmentId)
1177                .column_as(object::Column::Oid, "job_id")
1178                .column_as(object::Column::SchemaId, "schema_id")
1179                .column_as(object::Column::ObjType, "type")
1180                .into_tuple()
1181                .all(&inner.db)
1182                .await?;
1183
1184        let actor_infos = {
1185            let info = self.env.shared_actor_infos().read_guard();
1186
1187            let mut result = Vec::new();
1188
1189            for (fragment_id, object_id, schema_id, object_type) in fragment_objects {
1190                let Some(fragment) = info.get_fragment(fragment_id as _) else {
1191                    return Err(MetaError::unavailable(format!(
1192                        "shared actor info missing for fragment {fragment_id} while listing actors"
1193                    )));
1194                };
1195
1196                for actor_id in fragment.actors.keys() {
1197                    result.push((
1198                        *actor_id as _,
1199                        fragment.fragment_id as _,
1200                        object_id,
1201                        schema_id,
1202                        object_type,
1203                    ));
1204                }
1205            }
1206
1207            result
1208        };
1209
1210        Ok(actor_infos)
1211    }
1212
1213    pub fn get_worker_slot_mappings(&self) -> Vec<PbFragmentWorkerSlotMapping> {
1214        let guard = self.env.shared_actor_info.read_guard();
1215        guard
1216            .iter_over_fragments()
1217            .map(|(_, fragment)| rebuild_fragment_mapping(fragment))
1218            .collect_vec()
1219    }
1220
1221    pub async fn list_fragment_descs_with_node(
1222        &self,
1223        is_creating: bool,
1224    ) -> MetaResult<Vec<(FragmentDistribution, Vec<FragmentId>)>> {
1225        let inner = self.inner.read().await;
1226        let txn = inner.db.begin().await?;
1227
1228        let fragments_query = Self::build_fragment_query(is_creating);
1229        let fragments: Vec<fragment::Model> = fragments_query.all(&txn).await?;
1230
1231        let rows = fragments
1232            .into_iter()
1233            .map(|fragment| FragmentDescRow {
1234                fragment_id: fragment.fragment_id,
1235                job_id: fragment.job_id,
1236                fragment_type_mask: fragment.fragment_type_mask,
1237                distribution_type: fragment.distribution_type,
1238                state_table_ids: fragment.state_table_ids,
1239                vnode_count: fragment.vnode_count,
1240                parallelism_override: fragment.parallelism,
1241                stream_node: Some(fragment.stream_node),
1242            })
1243            .collect_vec();
1244
1245        self.build_fragment_distributions(&txn, rows).await
1246    }
1247
1248    pub async fn list_fragment_descs_without_node(
1249        &self,
1250        is_creating: bool,
1251    ) -> MetaResult<Vec<(FragmentDistribution, Vec<FragmentId>)>> {
1252        let inner = self.inner.read().await;
1253        let txn = inner.db.begin().await?;
1254
1255        let fragments_query = Self::build_fragment_query(is_creating);
1256        #[expect(clippy::type_complexity)]
1257        let fragments: Vec<(
1258            FragmentId,
1259            JobId,
1260            i32,
1261            DistributionType,
1262            TableIdArray,
1263            i32,
1264            Option<StreamingParallelism>,
1265        )> = fragments_query
1266            .select_only()
1267            .columns([
1268                fragment::Column::FragmentId,
1269                fragment::Column::JobId,
1270                fragment::Column::FragmentTypeMask,
1271                fragment::Column::DistributionType,
1272                fragment::Column::StateTableIds,
1273                fragment::Column::VnodeCount,
1274                fragment::Column::Parallelism,
1275            ])
1276            .into_tuple()
1277            .all(&txn)
1278            .await?;
1279
1280        let rows = fragments
1281            .into_iter()
1282            .map(
1283                |(
1284                    fragment_id,
1285                    job_id,
1286                    fragment_type_mask,
1287                    distribution_type,
1288                    state_table_ids,
1289                    vnode_count,
1290                    parallelism_override,
1291                )| FragmentDescRow {
1292                    fragment_id,
1293                    job_id,
1294                    fragment_type_mask,
1295                    distribution_type,
1296                    state_table_ids,
1297                    vnode_count,
1298                    parallelism_override,
1299                    stream_node: None,
1300                },
1301            )
1302            .collect_vec();
1303
1304        self.build_fragment_distributions(&txn, rows).await
1305    }
1306
1307    fn build_fragment_query(is_creating: bool) -> sea_orm::Select<fragment::Entity> {
1308        if is_creating {
1309            FragmentModel::find()
1310                .join(JoinType::LeftJoin, fragment::Relation::Object.def())
1311                .join(JoinType::LeftJoin, object::Relation::StreamingJob.def())
1312                .filter(
1313                    streaming_job::Column::JobStatus
1314                        .eq(JobStatus::Initial)
1315                        .or(streaming_job::Column::JobStatus.eq(JobStatus::Creating)),
1316                )
1317        } else {
1318            FragmentModel::find()
1319        }
1320    }
1321
1322    async fn build_fragment_distributions(
1323        &self,
1324        txn: &DatabaseTransaction,
1325        rows: Vec<FragmentDescRow>,
1326    ) -> MetaResult<Vec<(FragmentDistribution, Vec<FragmentId>)>> {
1327        let fragment_ids = rows.iter().map(|row| row.fragment_id).collect_vec();
1328        let job_ids = rows.iter().map(|row| row.job_id).unique().collect_vec();
1329
1330        let job_parallelisms: HashMap<JobId, (StreamingParallelism, Option<String>)> =
1331            if fragment_ids.is_empty() {
1332                HashMap::new()
1333            } else {
1334                StreamingJob::find()
1335                    .select_only()
1336                    .columns([
1337                        streaming_job::Column::JobId,
1338                        streaming_job::Column::Parallelism,
1339                        streaming_job::Column::AdaptiveParallelismStrategy,
1340                    ])
1341                    .filter(streaming_job::Column::JobId.is_in(job_ids))
1342                    .into_tuple::<(JobId, StreamingParallelism, Option<String>)>()
1343                    .all(txn)
1344                    .await?
1345                    .into_iter()
1346                    .map(|(job_id, parallelism, strategy)| (job_id, (parallelism, strategy)))
1347                    .collect()
1348            };
1349
1350        let upstream_entries: Vec<(FragmentId, FragmentId, DispatcherType)> =
1351            if fragment_ids.is_empty() {
1352                Vec::new()
1353            } else {
1354                FragmentRelation::find()
1355                    .select_only()
1356                    .columns([
1357                        fragment_relation::Column::TargetFragmentId,
1358                        fragment_relation::Column::SourceFragmentId,
1359                        fragment_relation::Column::DispatcherType,
1360                    ])
1361                    .filter(fragment_relation::Column::TargetFragmentId.is_in(fragment_ids.clone()))
1362                    .into_tuple()
1363                    .all(txn)
1364                    .await?
1365            };
1366
1367        let mut all_upstreams: HashMap<FragmentId, Vec<FragmentId>> = HashMap::new();
1368        for (target_id, source_id, _) in upstream_entries {
1369            all_upstreams.entry(target_id).or_default().push(source_id);
1370        }
1371
1372        let root_fragment_map = if fragment_ids.is_empty() {
1373            HashMap::new()
1374        } else {
1375            let ensembles = find_fragment_no_shuffle_dags_detailed(txn, &fragment_ids).await?;
1376            Self::collect_root_fragment_mapping(ensembles)
1377        };
1378
1379        let guard = self.env.shared_actor_info.read_guard();
1380        let mut result = Vec::with_capacity(rows.len());
1381
1382        for row in rows {
1383            let parallelism = guard
1384                .get_fragment(row.fragment_id as _)
1385                .map(|fragment| fragment.actors.len())
1386                .unwrap_or_default();
1387
1388            let root_fragments = root_fragment_map
1389                .get(&row.fragment_id)
1390                .cloned()
1391                .unwrap_or_default();
1392
1393            let upstreams = all_upstreams.remove(&row.fragment_id).unwrap_or_default();
1394
1395            let parallelism_policy = Self::format_fragment_parallelism_policy(
1396                row.distribution_type,
1397                row.parallelism_override.as_ref(),
1398                job_parallelisms
1399                    .get(&row.job_id)
1400                    .map(|(parallelism, _)| parallelism),
1401                job_parallelisms
1402                    .get(&row.job_id)
1403                    .and_then(|(_, strategy)| strategy.as_deref()),
1404                &root_fragments,
1405            );
1406
1407            let fragment = FragmentDistribution {
1408                fragment_id: row.fragment_id,
1409                table_id: row.job_id,
1410                distribution_type: PbFragmentDistributionType::from(row.distribution_type) as _,
1411                state_table_ids: row.state_table_ids.0,
1412                upstream_fragment_ids: upstreams.clone(),
1413                fragment_type_mask: row.fragment_type_mask as _,
1414                parallelism: parallelism as _,
1415                vnode_count: row.vnode_count as _,
1416                node: row.stream_node.map(|node| node.to_protobuf()),
1417                parallelism_policy,
1418            };
1419
1420            result.push((fragment, upstreams));
1421        }
1422
1423        Ok(result)
1424    }
1425
1426    pub async fn list_sink_log_store_tables(&self) -> MetaResult<Vec<(SinkId, TableId)>> {
1427        let inner = self.inner.read().await;
1428        let txn = inner.db.begin().await?;
1429
1430        let fragments: Vec<(JobId, StreamNode)> = FragmentModel::find()
1431            .select_only()
1432            .columns([fragment::Column::JobId, fragment::Column::StreamNode])
1433            .filter(FragmentTypeMask::intersects(FragmentTypeFlag::Sink))
1434            .into_tuple()
1435            .all(&txn)
1436            .await?;
1437
1438        let mut mapping: HashMap<SinkId, TableId> = HashMap::new();
1439
1440        for (job_id, stream_node) in fragments {
1441            let sink_id = SinkId::new(job_id.as_raw_id());
1442            let stream_node = stream_node.to_protobuf();
1443            let mut internal_table_id: Option<TableId> = None;
1444
1445            visit_stream_node_body(&stream_node, |body| {
1446                if let NodeBody::Sink(node) = body
1447                    && node.log_store_type == SinkLogStoreType::KvLogStore as i32
1448                    && let Some(table) = &node.table
1449                {
1450                    internal_table_id = Some(TableId::new(table.id.as_raw_id()));
1451                }
1452            });
1453
1454            if let Some(table_id) = internal_table_id
1455                && let Some(existing) = mapping.insert(sink_id, table_id)
1456                && existing != table_id
1457            {
1458                tracing::warn!(
1459                    "sink {sink_id:?} has multiple log store tables: {existing:?} vs {table_id:?}"
1460                );
1461            }
1462        }
1463
1464        Ok(mapping.into_iter().collect())
1465    }
1466
1467    /// Build a fragment-to-root lookup for all reported root fragment ensembles.
1468    fn collect_root_fragment_mapping(
1469        ensembles: Vec<NoShuffleEnsemble>,
1470    ) -> HashMap<FragmentId, Vec<FragmentId>> {
1471        let mut mapping = HashMap::new();
1472
1473        for ensemble in ensembles {
1474            let mut roots: Vec<_> = ensemble.entry_fragments().collect();
1475            roots.sort_unstable();
1476            roots.dedup();
1477
1478            if roots.is_empty() {
1479                continue;
1480            }
1481
1482            let root_set: HashSet<_> = roots.iter().copied().collect();
1483
1484            for fragment_id in ensemble.component_fragments() {
1485                if root_set.contains(&fragment_id) {
1486                    mapping.insert(fragment_id, Vec::new());
1487                } else {
1488                    mapping.insert(fragment_id, roots.clone());
1489                }
1490            }
1491        }
1492
1493        mapping
1494    }
1495
1496    fn format_fragment_parallelism_policy(
1497        distribution_type: DistributionType,
1498        fragment_parallelism: Option<&StreamingParallelism>,
1499        job_parallelism: Option<&StreamingParallelism>,
1500        job_adaptive_parallelism_strategy: Option<&str>,
1501        root_fragments: &[FragmentId],
1502    ) -> String {
1503        if distribution_type == DistributionType::Single {
1504            return "single".to_owned();
1505        }
1506
1507        if let Some(parallelism) = fragment_parallelism {
1508            return format!(
1509                "override({})",
1510                Self::format_streaming_parallelism(parallelism, job_adaptive_parallelism_strategy)
1511            );
1512        }
1513
1514        if !root_fragments.is_empty() {
1515            let mut upstreams = root_fragments.to_vec();
1516            upstreams.sort_unstable();
1517            upstreams.dedup();
1518
1519            return format!("upstream_fragment({upstreams:?})");
1520        }
1521
1522        let inherited = job_parallelism
1523            .map(|parallelism| {
1524                Self::format_streaming_parallelism(parallelism, job_adaptive_parallelism_strategy)
1525            })
1526            .unwrap_or_else(|| "unknown".to_owned());
1527        format!("inherit({inherited})")
1528    }
1529
1530    fn format_streaming_parallelism(
1531        parallelism: &StreamingParallelism,
1532        adaptive_parallelism_strategy: Option<&str>,
1533    ) -> String {
1534        match parallelism {
1535            StreamingParallelism::Adaptive => adaptive_parallelism_strategy
1536                .and_then(Self::format_adaptive_parallelism_strategy)
1537                .unwrap_or_else(|| "adaptive".to_owned()),
1538            StreamingParallelism::Fixed(n) => n.to_string(),
1539            StreamingParallelism::Custom => adaptive_parallelism_strategy
1540                .and_then(Self::format_adaptive_parallelism_strategy)
1541                .unwrap_or_else(|| "custom".to_owned()),
1542        }
1543    }
1544
1545    fn format_adaptive_parallelism_strategy(strategy: &str) -> Option<String> {
1546        parse_strategy(strategy)
1547            .ok()
1548            .map(|strategy| match strategy {
1549                AdaptiveParallelismStrategy::Auto | AdaptiveParallelismStrategy::Full => {
1550                    "adaptive".to_owned()
1551                }
1552                AdaptiveParallelismStrategy::Bounded(n) => format!("bounded({n})"),
1553                AdaptiveParallelismStrategy::Ratio(r) => format!("ratio({r})"),
1554            })
1555    }
1556
1557    pub async fn list_sink_actor_mapping(
1558        &self,
1559    ) -> MetaResult<HashMap<SinkId, (String, Vec<ActorId>)>> {
1560        let inner = self.inner.read().await;
1561        let sink_id_names: Vec<(SinkId, String)> = Sink::find()
1562            .select_only()
1563            .columns([sink::Column::SinkId, sink::Column::Name])
1564            .into_tuple()
1565            .all(&inner.db)
1566            .await?;
1567        let (sink_ids, _): (Vec<_>, Vec<_>) = sink_id_names.iter().cloned().unzip();
1568
1569        let sink_name_mapping: HashMap<SinkId, String> = sink_id_names.into_iter().collect();
1570
1571        let actor_with_type: Vec<(ActorId, SinkId)> = {
1572            let info = self.env.shared_actor_infos().read_guard();
1573
1574            info.iter_over_fragments()
1575                .filter(|(_, fragment)| {
1576                    sink_ids.contains(&fragment.job_id.as_sink_id())
1577                        && fragment.fragment_type_mask.contains(FragmentTypeFlag::Sink)
1578                })
1579                .flat_map(|(_, fragment)| {
1580                    fragment
1581                        .actors
1582                        .keys()
1583                        .map(move |actor_id| (*actor_id as _, fragment.job_id.as_sink_id()))
1584                })
1585                .collect()
1586        };
1587
1588        let mut sink_actor_mapping = HashMap::new();
1589        for (actor_id, sink_id) in actor_with_type {
1590            sink_actor_mapping
1591                .entry(sink_id)
1592                .or_insert_with(|| (sink_name_mapping.get(&sink_id).unwrap().clone(), vec![]))
1593                .1
1594                .push(actor_id);
1595        }
1596
1597        Ok(sink_actor_mapping)
1598    }
1599
1600    pub async fn list_fragment_state_tables(&self) -> MetaResult<Vec<PartialFragmentStateTables>> {
1601        let inner = self.inner.read().await;
1602        let fragment_state_tables: Vec<PartialFragmentStateTables> = FragmentModel::find()
1603            .select_only()
1604            .columns([
1605                fragment::Column::FragmentId,
1606                fragment::Column::JobId,
1607                fragment::Column::StateTableIds,
1608            ])
1609            .into_partial_model()
1610            .all(&inner.db)
1611            .await?;
1612        Ok(fragment_state_tables)
1613    }
1614
1615    /// Used in [`crate::barrier::GlobalBarrierManager`], load all running actor that need to be sent or
1616    /// collected
1617    pub async fn load_all_actors_dynamic(
1618        &self,
1619        database_id: Option<DatabaseId>,
1620        worker_nodes: &ActiveStreamingWorkerNodes,
1621    ) -> MetaResult<FragmentRenderMap> {
1622        let loaded = self.load_fragment_context(database_id).await?;
1623
1624        if loaded.is_empty() {
1625            return Ok(HashMap::new());
1626        }
1627
1628        let RenderedGraph { fragments, .. } = render_actor_assignments(
1629            self.env.actor_id_generator(),
1630            worker_nodes.current(),
1631            &loaded,
1632        )?;
1633
1634        tracing::trace!(?fragments, "reload all actors");
1635
1636        Ok(fragments)
1637    }
1638
1639    /// Async load stage: collects all metadata required for rendering actor assignments.
1640    pub async fn load_fragment_context(
1641        &self,
1642        database_id: Option<DatabaseId>,
1643    ) -> MetaResult<LoadedFragmentContext> {
1644        let inner = self.inner.read().await;
1645        let txn = inner.db.begin().await?;
1646
1647        self.load_fragment_context_in_txn(&txn, database_id).await
1648    }
1649
1650    pub async fn load_fragment_context_in_txn<C>(
1651        &self,
1652        txn: &C,
1653        database_id: Option<DatabaseId>,
1654    ) -> MetaResult<LoadedFragmentContext>
1655    where
1656        C: ConnectionTrait,
1657    {
1658        let mut query = StreamingJob::find()
1659            .select_only()
1660            .column(streaming_job::Column::JobId);
1661
1662        if let Some(database_id) = database_id {
1663            query = query
1664                .join(JoinType::InnerJoin, streaming_job::Relation::Object.def())
1665                .filter(object::Column::DatabaseId.eq(database_id));
1666        }
1667
1668        let jobs: Vec<JobId> = query.into_tuple().all(txn).await?;
1669
1670        let jobs: HashSet<JobId> = jobs.into_iter().collect();
1671
1672        if jobs.is_empty() {
1673            return Ok(LoadedFragmentContext::default());
1674        }
1675
1676        load_fragment_context_for_jobs(txn, jobs).await
1677    }
1678
1679    #[await_tree::instrument]
1680    pub async fn fill_snapshot_backfill_epoch(
1681        &self,
1682        fragment_ids: impl Iterator<Item = FragmentId>,
1683        snapshot_backfill_info: Option<&SnapshotBackfillInfo>,
1684        cross_db_snapshot_backfill_info: &SnapshotBackfillInfo,
1685    ) -> MetaResult<()> {
1686        let inner = self.inner.write().await;
1687        let txn = inner.db.begin().await?;
1688        for fragment_id in fragment_ids {
1689            let fragment = FragmentModel::find_by_id(fragment_id)
1690                .one(&txn)
1691                .await?
1692                .context(format!("fragment {} not found", fragment_id))?;
1693            let mut node = fragment.stream_node.to_protobuf();
1694            if crate::stream::fill_snapshot_backfill_epoch(
1695                &mut node,
1696                snapshot_backfill_info,
1697                cross_db_snapshot_backfill_info,
1698            )? {
1699                let node = StreamNode::from(&node);
1700                FragmentModel::update(fragment::ActiveModel {
1701                    fragment_id: Set(fragment_id),
1702                    stream_node: Set(node),
1703                    ..Default::default()
1704                })
1705                .exec(&txn)
1706                .await?;
1707            }
1708        }
1709        txn.commit().await?;
1710        Ok(())
1711    }
1712
1713    /// Get the actor ids of the fragment with `fragment_id` with `Running` status.
1714    pub fn get_running_actors_of_fragment(
1715        &self,
1716        fragment_id: FragmentId,
1717    ) -> MetaResult<HashSet<model::ActorId>> {
1718        let info = self.env.shared_actor_infos().read_guard();
1719
1720        let actors = info
1721            .get_fragment(fragment_id as _)
1722            .map(|SharedFragmentInfo { actors, .. }| actors.keys().copied().collect())
1723            .unwrap_or_default();
1724
1725        Ok(actors)
1726    }
1727
1728    /// Get the actor ids, and each actor's upstream source actor ids of the fragment with `fragment_id` with `Running` status.
1729    /// (`backfill_actor_id`, `upstream_source_actor_id`)
1730    pub async fn get_running_actors_for_source_backfill(
1731        &self,
1732        source_backfill_fragment_id: FragmentId,
1733        source_fragment_id: FragmentId,
1734    ) -> MetaResult<Vec<(ActorId, ActorId)>> {
1735        let inner = self.inner.read().await;
1736        let txn = inner.db.begin().await?;
1737
1738        let fragment_relation: DispatcherType = FragmentRelation::find()
1739            .select_only()
1740            .column(fragment_relation::Column::DispatcherType)
1741            .filter(fragment_relation::Column::SourceFragmentId.eq(source_fragment_id))
1742            .filter(fragment_relation::Column::TargetFragmentId.eq(source_backfill_fragment_id))
1743            .into_tuple()
1744            .one(&txn)
1745            .await?
1746            .ok_or_else(|| {
1747                anyhow!(
1748                    "no fragment connection from source fragment {} to source backfill fragment {}",
1749                    source_fragment_id,
1750                    source_backfill_fragment_id
1751                )
1752            })?;
1753
1754        if fragment_relation != DispatcherType::NoShuffle {
1755            return Err(anyhow!("expected NoShuffle but got {:?}", fragment_relation).into());
1756        }
1757
1758        let load_fragment_distribution_type = |txn, fragment_id: FragmentId| async move {
1759            let result: MetaResult<DistributionType> = try {
1760                FragmentModel::find_by_id(fragment_id)
1761                    .select_only()
1762                    .column(fragment::Column::DistributionType)
1763                    .into_tuple()
1764                    .one(txn)
1765                    .await
1766                    .map_err(MetaError::from)?
1767                    .ok_or_else(|| {
1768                        MetaError::from(anyhow!("failed to find fragment: {}", fragment_id))
1769                    })?
1770            };
1771            result
1772        };
1773
1774        let source_backfill_distribution_type =
1775            load_fragment_distribution_type(&txn, source_backfill_fragment_id).await?;
1776        let source_distribution_type =
1777            load_fragment_distribution_type(&txn, source_fragment_id).await?;
1778
1779        let load_fragment_actor_distribution =
1780            |actor_info: &SharedActorInfos,
1781             fragment_id: FragmentId|
1782             -> HashMap<crate::model::ActorId, Option<Bitmap>> {
1783                let guard = actor_info.read_guard();
1784
1785                guard
1786                    .get_fragment(fragment_id as _)
1787                    .map(|fragment| {
1788                        fragment
1789                            .actors
1790                            .iter()
1791                            .map(|(actor_id, actor)| {
1792                                (
1793                                    *actor_id as _,
1794                                    actor
1795                                        .vnode_bitmap
1796                                        .as_ref()
1797                                        .map(|bitmap| Bitmap::from(bitmap.to_protobuf())),
1798                                )
1799                            })
1800                            .collect()
1801                    })
1802                    .unwrap_or_default()
1803            };
1804
1805        let source_backfill_actors: HashMap<crate::model::ActorId, Option<Bitmap>> =
1806            load_fragment_actor_distribution(
1807                self.env.shared_actor_infos(),
1808                source_backfill_fragment_id,
1809            );
1810
1811        let source_actors =
1812            load_fragment_actor_distribution(self.env.shared_actor_infos(), source_fragment_id);
1813
1814        Ok(resolve_no_shuffle_actor_mapping(
1815            source_distribution_type,
1816            source_actors.iter().map(|(&id, bitmap)| (id, bitmap)),
1817            source_backfill_distribution_type,
1818            source_backfill_actors
1819                .iter()
1820                .map(|(&id, bitmap)| (id, bitmap)),
1821        )
1822        .into_iter()
1823        .map(|(source_actor, source_backfill_actor)| {
1824            (source_backfill_actor as _, source_actor as _)
1825        })
1826        .collect())
1827    }
1828
1829    /// Get and filter the "**root**" fragments of the specified jobs.
1830    /// The root fragment is the bottom-most fragment of its fragment graph, and can be a `MView` or a `Source`.
1831    ///
1832    /// Root fragment connects to downstream jobs.
1833    ///
1834    /// ## What can be the root fragment
1835    /// - For sink, it should have one `Sink` fragment.
1836    /// - For MV, it should have one `MView` fragment.
1837    /// - For table, it should have one `MView` fragment and one or two `Source` fragments. `MView` should be the root.
1838    /// - For source, it should have one `Source` fragment.
1839    ///
1840    /// In other words, it's the `MView` or `Sink` fragment if it exists, otherwise it's the `Source` fragment.
1841    pub async fn get_root_fragments(
1842        &self,
1843        job_ids: Vec<JobId>,
1844    ) -> MetaResult<HashMap<JobId, Fragment>> {
1845        let inner = self.inner.read().await;
1846
1847        let all_fragments = FragmentModel::find()
1848            .filter(fragment::Column::JobId.is_in(job_ids))
1849            .all(&inner.db)
1850            .await?;
1851        // job_id -> fragment
1852        let mut root_fragments = HashMap::<JobId, Fragment>::new();
1853        for fragment in all_fragments {
1854            let mask = FragmentTypeMask::from(fragment.fragment_type_mask);
1855            if mask.contains_any([FragmentTypeFlag::Mview, FragmentTypeFlag::Sink]) {
1856                _ = root_fragments.insert(fragment.job_id, fragment.into());
1857            } else if mask.contains(FragmentTypeFlag::Source) {
1858                // look for Source fragment only if there's no MView fragment
1859                // (notice try_insert here vs insert above)
1860                _ = root_fragments.try_insert(fragment.job_id, fragment.into());
1861            }
1862        }
1863
1864        Ok(root_fragments)
1865    }
1866
1867    pub async fn get_root_fragment(&self, job_id: JobId) -> MetaResult<Fragment> {
1868        let mut root_fragments = self.get_root_fragments(vec![job_id]).await?;
1869        let root_fragment = root_fragments
1870            .remove(&job_id)
1871            .context(format!("root fragment for job {} not found", job_id))?;
1872
1873        Ok(root_fragment)
1874    }
1875
1876    /// Get the downstream fragments connected to the specified job.
1877    pub async fn get_downstream_fragments(
1878        &self,
1879        job_id: JobId,
1880    ) -> MetaResult<Vec<(stream_plan::DispatcherType, Fragment)>> {
1881        let root_fragment = self.get_root_fragment(job_id).await?;
1882
1883        let inner = self.inner.read().await;
1884        let txn = inner.db.begin().await?;
1885        let downstream_fragment_relations: Vec<fragment_relation::Model> = FragmentRelation::find()
1886            .filter(
1887                fragment_relation::Column::SourceFragmentId
1888                    .eq(root_fragment.fragment_id as FragmentId),
1889            )
1890            .all(&txn)
1891            .await?;
1892
1893        let downstream_fragment_ids = downstream_fragment_relations
1894            .iter()
1895            .map(|model| model.target_fragment_id as FragmentId)
1896            .collect::<HashSet<_>>();
1897
1898        let downstream_fragments: Vec<fragment::Model> = FragmentModel::find()
1899            .filter(fragment::Column::FragmentId.is_in(downstream_fragment_ids))
1900            .all(&txn)
1901            .await?;
1902
1903        let mut downstream_fragments_map: HashMap<_, _> = downstream_fragments
1904            .into_iter()
1905            .map(|fragment| (fragment.fragment_id, fragment))
1906            .collect();
1907
1908        let mut downstream_fragments = vec![];
1909
1910        let fragment_map: HashMap<_, _> = downstream_fragment_relations
1911            .iter()
1912            .map(|model| (model.target_fragment_id, model.dispatcher_type))
1913            .collect();
1914
1915        for (fragment_id, dispatcher_type) in fragment_map {
1916            let dispatch_type = PbDispatcherType::from(dispatcher_type);
1917
1918            let fragment = downstream_fragments_map
1919                .remove(&fragment_id)
1920                .context(format!(
1921                    "downstream fragment node for id {} not found",
1922                    fragment_id
1923                ))?
1924                .into();
1925
1926            downstream_fragments.push((dispatch_type, fragment));
1927        }
1928        Ok(downstream_fragments)
1929    }
1930
1931    pub async fn load_source_fragment_ids(
1932        &self,
1933    ) -> MetaResult<HashMap<SourceId, BTreeSet<FragmentId>>> {
1934        let inner = self.inner.read().await;
1935        let fragments: Vec<(FragmentId, StreamNode)> = FragmentModel::find()
1936            .select_only()
1937            .columns([fragment::Column::FragmentId, fragment::Column::StreamNode])
1938            .filter(FragmentTypeMask::intersects(FragmentTypeFlag::Source))
1939            .into_tuple()
1940            .all(&inner.db)
1941            .await?;
1942
1943        let mut source_fragment_ids = HashMap::new();
1944        for (fragment_id, stream_node) in fragments {
1945            if let Some(source_id) = stream_node.to_protobuf().find_stream_source() {
1946                source_fragment_ids
1947                    .entry(source_id)
1948                    .or_insert_with(BTreeSet::new)
1949                    .insert(fragment_id);
1950            }
1951        }
1952        Ok(source_fragment_ids)
1953    }
1954
1955    pub async fn load_backfill_fragment_ids(
1956        &self,
1957    ) -> MetaResult<HashMap<SourceId, BTreeSet<(FragmentId, FragmentId)>>> {
1958        let inner = self.inner.read().await;
1959        let fragments: Vec<(FragmentId, StreamNode)> = FragmentModel::find()
1960            .select_only()
1961            .columns([fragment::Column::FragmentId, fragment::Column::StreamNode])
1962            .filter(FragmentTypeMask::intersects(FragmentTypeFlag::SourceScan))
1963            .into_tuple()
1964            .all(&inner.db)
1965            .await?;
1966
1967        let mut source_fragment_ids = HashMap::new();
1968        for (fragment_id, stream_node) in fragments {
1969            if let Some((source_id, upstream_source_fragment_id)) =
1970                stream_node.to_protobuf().find_source_backfill()
1971            {
1972                source_fragment_ids
1973                    .entry(source_id)
1974                    .or_insert_with(BTreeSet::new)
1975                    .insert((fragment_id, upstream_source_fragment_id));
1976            }
1977        }
1978        Ok(source_fragment_ids)
1979    }
1980
1981    pub async fn get_all_upstream_sink_infos(
1982        &self,
1983        target_table: &PbTable,
1984        target_fragment_id: FragmentId,
1985    ) -> MetaResult<Vec<UpstreamSinkInfo>> {
1986        let inner = self.inner.read().await;
1987        let txn = inner.db.begin().await?;
1988
1989        self.get_all_upstream_sink_infos_in_txn(&txn, target_table, target_fragment_id)
1990            .await
1991    }
1992
1993    pub async fn get_all_upstream_sink_infos_in_txn<C>(
1994        &self,
1995        txn: &C,
1996        target_table: &PbTable,
1997        target_fragment_id: FragmentId,
1998    ) -> MetaResult<Vec<UpstreamSinkInfo>>
1999    where
2000        C: ConnectionTrait,
2001    {
2002        let incoming_sinks = Sink::find()
2003            .filter(sink::Column::TargetTable.eq(target_table.id))
2004            .all(txn)
2005            .await?;
2006
2007        let sink_ids = incoming_sinks.iter().map(|s| s.sink_id).collect_vec();
2008        let sink_fragment_ids = get_sink_fragment_by_ids(txn, sink_ids).await?;
2009
2010        let mut upstream_sink_infos = Vec::with_capacity(incoming_sinks.len());
2011        for sink in &incoming_sinks {
2012            let sink_fragment_id =
2013                sink_fragment_ids
2014                    .get(&sink.sink_id)
2015                    .cloned()
2016                    .ok_or(anyhow::anyhow!(
2017                        "sink fragment not found for sink id {}",
2018                        sink.sink_id
2019                    ))?;
2020            let upstream_info = build_upstream_sink_info(
2021                sink.sink_id,
2022                sink.original_target_columns
2023                    .as_ref()
2024                    .map(|cols| cols.to_protobuf())
2025                    .unwrap_or_default(),
2026                sink_fragment_id,
2027                target_table,
2028                target_fragment_id,
2029            )?;
2030            upstream_sink_infos.push(upstream_info);
2031        }
2032
2033        Ok(upstream_sink_infos)
2034    }
2035
2036    pub async fn get_mview_fragment_by_id(&self, job_id: JobId) -> MetaResult<FragmentId> {
2037        let inner = self.inner.read().await;
2038        let txn = inner.db.begin().await?;
2039
2040        let mview_fragment: Vec<FragmentId> = FragmentModel::find()
2041            .select_only()
2042            .column(fragment::Column::FragmentId)
2043            .filter(
2044                fragment::Column::JobId
2045                    .eq(job_id)
2046                    .and(FragmentTypeMask::intersects(FragmentTypeFlag::Mview)),
2047            )
2048            .into_tuple()
2049            .all(&txn)
2050            .await?;
2051
2052        if mview_fragment.len() != 1 {
2053            return Err(anyhow::anyhow!(
2054                "expected exactly one mview fragment for job {}, found {}",
2055                job_id,
2056                mview_fragment.len()
2057            )
2058            .into());
2059        }
2060
2061        Ok(mview_fragment.into_iter().next().unwrap())
2062    }
2063
2064    pub async fn has_table_been_migrated(&self, table_id: TableId) -> MetaResult<bool> {
2065        let inner = self.inner.read().await;
2066        let txn = inner.db.begin().await?;
2067        has_table_been_migrated(&txn, table_id).await
2068    }
2069
2070    pub async fn update_fragment_splits<C>(
2071        &self,
2072        txn: &C,
2073        fragment_splits: &HashMap<FragmentId, Vec<SplitImpl>>,
2074    ) -> MetaResult<()>
2075    where
2076        C: ConnectionTrait,
2077    {
2078        if fragment_splits.is_empty() {
2079            return Ok(());
2080        }
2081
2082        let existing_fragment_ids: HashSet<FragmentId> = FragmentModel::find()
2083            .select_only()
2084            .column(fragment::Column::FragmentId)
2085            .filter(fragment::Column::FragmentId.is_in(fragment_splits.keys().copied()))
2086            .into_tuple()
2087            .all(txn)
2088            .await?
2089            .into_iter()
2090            .collect();
2091
2092        // Filter out stale fragment ids to avoid FK violations when split updates race with drop.
2093        let (models, skipped_fragment_ids): (Vec<_>, Vec<_>) = fragment_splits
2094            .iter()
2095            .partition_map(|(fragment_id, splits)| {
2096                if existing_fragment_ids.contains(fragment_id) {
2097                    Either::Left(fragment_splits::ActiveModel {
2098                        fragment_id: Set(*fragment_id as _),
2099                        splits: Set(Some(ConnectorSplits::from(&PbConnectorSplits {
2100                            splits: splits.iter().map(Into::into).collect_vec(),
2101                        }))),
2102                    })
2103                } else {
2104                    Either::Right(*fragment_id)
2105                }
2106            });
2107
2108        if !skipped_fragment_ids.is_empty() {
2109            tracing::warn!(
2110                skipped_fragment_ids = ?skipped_fragment_ids,
2111                total_fragment_ids = fragment_splits.len(),
2112                "skipping stale fragment split updates for missing fragments"
2113            );
2114        }
2115
2116        if models.is_empty() {
2117            return Ok(());
2118        }
2119
2120        FragmentSplits::insert_many(models)
2121            .on_conflict(
2122                OnConflict::column(fragment_splits::Column::FragmentId)
2123                    .update_column(fragment_splits::Column::Splits)
2124                    .to_owned(),
2125            )
2126            .exec(txn)
2127            .await?;
2128
2129        Ok(())
2130    }
2131}
2132
2133#[cfg(test)]
2134mod tests {
2135    use std::collections::{BTreeMap, HashMap, HashSet};
2136
2137    use itertools::Itertools;
2138    use risingwave_common::catalog::{FragmentTypeFlag, FragmentTypeMask};
2139    use risingwave_common::hash::{ActorMapping, VirtualNode, VnodeCount};
2140    use risingwave_common::id::JobId;
2141    use risingwave_common::util::iter_util::ZipEqDebug;
2142    use risingwave_common::util::stream_graph_visitor::visit_stream_node_body;
2143    use risingwave_meta_model::fragment::DistributionType;
2144    use risingwave_meta_model::*;
2145    use risingwave_pb::meta::table_fragments::fragment::PbFragmentDistributionType;
2146    use risingwave_pb::plan_common::PbExprContext;
2147    use risingwave_pb::source::{PbConnectorSplit, PbConnectorSplits};
2148    use risingwave_pb::stream_plan::stream_node::PbNodeBody;
2149    use risingwave_pb::stream_plan::{MergeNode, PbStreamNode, PbUnionNode};
2150
2151    use super::ActorInfo;
2152    use crate::MetaResult;
2153    use crate::controller::catalog::CatalogController;
2154    use crate::model::{Fragment, StreamActor};
2155
2156    type ActorUpstreams = BTreeMap<crate::model::FragmentId, HashSet<crate::model::ActorId>>;
2157
2158    type FragmentActorUpstreams = HashMap<crate::model::ActorId, ActorUpstreams>;
2159
2160    const TEST_FRAGMENT_ID: FragmentId = FragmentId::new(1);
2161
2162    const TEST_UPSTREAM_FRAGMENT_ID: FragmentId = FragmentId::new(2);
2163
2164    const TEST_JOB_ID: JobId = JobId::new(1);
2165
2166    const TEST_STATE_TABLE_ID: TableId = TableId::new(1000);
2167
2168    fn generate_upstream_actor_ids_for_actor(actor_id: ActorId) -> ActorUpstreams {
2169        let mut upstream_actor_ids = BTreeMap::new();
2170        upstream_actor_ids.insert(
2171            TEST_UPSTREAM_FRAGMENT_ID,
2172            HashSet::from_iter([(actor_id + 100)]),
2173        );
2174        upstream_actor_ids.insert(
2175            (TEST_UPSTREAM_FRAGMENT_ID + 1) as _,
2176            HashSet::from_iter([(actor_id + 200)]),
2177        );
2178        upstream_actor_ids
2179    }
2180
2181    fn generate_merger_stream_node(actor_upstream_actor_ids: &ActorUpstreams) -> PbStreamNode {
2182        let mut input = vec![];
2183        for &upstream_fragment_id in actor_upstream_actor_ids.keys() {
2184            input.push(PbStreamNode {
2185                node_body: Some(PbNodeBody::Merge(Box::new(MergeNode {
2186                    upstream_fragment_id,
2187                    ..Default::default()
2188                }))),
2189                ..Default::default()
2190            });
2191        }
2192
2193        PbStreamNode {
2194            input,
2195            node_body: Some(PbNodeBody::Union(PbUnionNode {})),
2196            ..Default::default()
2197        }
2198    }
2199
2200    #[tokio::test]
2201    async fn test_extract_fragment() -> MetaResult<()> {
2202        let actor_count = 3u32;
2203        let upstream_actor_ids: FragmentActorUpstreams = (0..actor_count)
2204            .map(|actor_id| {
2205                (
2206                    actor_id.into(),
2207                    generate_upstream_actor_ids_for_actor(actor_id.into()),
2208                )
2209            })
2210            .collect();
2211
2212        let stream_node = generate_merger_stream_node(upstream_actor_ids.values().next().unwrap());
2213
2214        let pb_fragment = Fragment {
2215            fragment_id: TEST_FRAGMENT_ID as _,
2216            fragment_type_mask: FragmentTypeMask::from(FragmentTypeFlag::Source as u32),
2217            distribution_type: PbFragmentDistributionType::Hash as _,
2218            state_table_ids: vec![TEST_STATE_TABLE_ID as _],
2219            maybe_vnode_count: VnodeCount::for_test().to_protobuf(),
2220            nodes: stream_node,
2221        };
2222
2223        let fragment =
2224            CatalogController::prepare_fragment_model_for_new_job(TEST_JOB_ID, &pb_fragment)?;
2225
2226        check_fragment(fragment, pb_fragment);
2227
2228        Ok(())
2229    }
2230
2231    #[tokio::test]
2232    async fn test_compose_fragment() -> MetaResult<()> {
2233        let actor_count = 3u32;
2234
2235        let upstream_actor_ids: FragmentActorUpstreams = (0..actor_count)
2236            .map(|actor_id| {
2237                (
2238                    actor_id.into(),
2239                    generate_upstream_actor_ids_for_actor(actor_id.into()),
2240                )
2241            })
2242            .collect();
2243
2244        let mut actor_bitmaps = ActorMapping::new_uniform(
2245            (0..actor_count).map(|i| i.into()),
2246            VirtualNode::COUNT_FOR_TEST,
2247        )
2248        .to_bitmaps();
2249
2250        let actors = (0..actor_count)
2251            .map(|actor_id| {
2252                let actor_splits = ConnectorSplits::from(&PbConnectorSplits {
2253                    splits: vec![PbConnectorSplit {
2254                        split_type: "dummy".to_owned(),
2255                        ..Default::default()
2256                    }],
2257                });
2258
2259                ActorInfo {
2260                    actor_id: actor_id.into(),
2261                    fragment_id: TEST_FRAGMENT_ID,
2262                    splits: actor_splits,
2263                    worker_id: 0.into(),
2264                    vnode_bitmap: actor_bitmaps
2265                        .remove(&actor_id)
2266                        .map(|bitmap| bitmap.to_protobuf())
2267                        .as_ref()
2268                        .map(VnodeBitmap::from),
2269                    expr_context: ExprContext::from(&PbExprContext {
2270                        time_zone: String::from("America/New_York"),
2271                        strict_mode: false,
2272                    }),
2273                    config_override: "a.b.c = true".into(),
2274                }
2275            })
2276            .collect_vec();
2277
2278        let stream_node = {
2279            let template_actor = actors.first().cloned().unwrap();
2280
2281            let template_upstream_actor_ids =
2282                upstream_actor_ids.get(&template_actor.actor_id).unwrap();
2283
2284            generate_merger_stream_node(template_upstream_actor_ids)
2285        };
2286
2287        #[expect(deprecated)]
2288        let fragment = fragment::Model {
2289            fragment_id: TEST_FRAGMENT_ID,
2290            job_id: TEST_JOB_ID,
2291            fragment_type_mask: 0,
2292            distribution_type: DistributionType::Hash,
2293            stream_node: StreamNode::from(&stream_node),
2294            state_table_ids: TableIdArray(vec![TEST_STATE_TABLE_ID]),
2295            upstream_fragment_id: Default::default(),
2296            vnode_count: VirtualNode::COUNT_FOR_TEST as _,
2297            parallelism: None,
2298        };
2299
2300        let (pb_fragment, pb_actors, pb_actor_status, pb_actor_splits) =
2301            CatalogController::compose_fragment(fragment.clone(), actors.clone(), None).unwrap();
2302
2303        assert_eq!(pb_actor_status.len(), actor_count as usize);
2304        assert!(
2305            pb_actor_status
2306                .values()
2307                .all(|actor_status| actor_status.location.is_some())
2308        );
2309        assert_eq!(pb_actor_splits.len(), actor_count as usize);
2310
2311        check_fragment(fragment, pb_fragment);
2312        check_actors(
2313            actors,
2314            &upstream_actor_ids,
2315            pb_actors,
2316            pb_actor_splits,
2317            &stream_node,
2318        );
2319
2320        Ok(())
2321    }
2322
2323    fn check_actors(
2324        actors: Vec<ActorInfo>,
2325        actor_upstreams: &FragmentActorUpstreams,
2326        pb_actors: Vec<StreamActor>,
2327        pb_actor_splits: HashMap<ActorId, PbConnectorSplits>,
2328        stream_node: &PbStreamNode,
2329    ) {
2330        for (
2331            ActorInfo {
2332                actor_id,
2333                fragment_id,
2334                splits,
2335                worker_id: _,
2336                vnode_bitmap,
2337                expr_context,
2338                ..
2339            },
2340            StreamActor {
2341                actor_id: pb_actor_id,
2342                fragment_id: pb_fragment_id,
2343                vnode_bitmap: pb_vnode_bitmap,
2344                mview_definition,
2345                expr_context: pb_expr_context,
2346                ..
2347            },
2348        ) in actors.into_iter().zip_eq_debug(pb_actors.into_iter())
2349        {
2350            assert_eq!(actor_id, pb_actor_id as ActorId);
2351            assert_eq!(fragment_id, pb_fragment_id as FragmentId);
2352
2353            assert_eq!(
2354                vnode_bitmap.map(|bitmap| bitmap.to_protobuf().into()),
2355                pb_vnode_bitmap,
2356            );
2357
2358            assert_eq!(mview_definition, "");
2359
2360            visit_stream_node_body(stream_node, |body| {
2361                if let PbNodeBody::Merge(m) = body {
2362                    assert!(
2363                        actor_upstreams
2364                            .get(&actor_id)
2365                            .unwrap()
2366                            .contains_key(&m.upstream_fragment_id)
2367                    );
2368                }
2369            });
2370
2371            assert_eq!(
2372                splits,
2373                pb_actor_splits
2374                    .get(&pb_actor_id)
2375                    .map(ConnectorSplits::from)
2376                    .unwrap_or_default()
2377            );
2378
2379            assert_eq!(Some(expr_context.to_protobuf()), pb_expr_context);
2380        }
2381    }
2382
2383    fn check_fragment(fragment: fragment::Model, pb_fragment: Fragment) {
2384        let Fragment {
2385            fragment_id,
2386            fragment_type_mask,
2387            distribution_type: pb_distribution_type,
2388            state_table_ids: pb_state_table_ids,
2389            maybe_vnode_count: _,
2390            nodes,
2391        } = pb_fragment;
2392
2393        assert_eq!(fragment_id, TEST_FRAGMENT_ID);
2394        assert_eq!(fragment_type_mask, fragment.fragment_type_mask.into());
2395        assert_eq!(
2396            pb_distribution_type,
2397            PbFragmentDistributionType::from(fragment.distribution_type)
2398        );
2399
2400        assert_eq!(pb_state_table_ids, fragment.state_table_ids.0);
2401        assert_eq!(fragment.stream_node.to_protobuf(), nodes);
2402    }
2403
2404    #[test]
2405    fn test_parallelism_policy_with_root_fragments() {
2406        #[expect(deprecated)]
2407        let fragment = fragment::Model {
2408            fragment_id: 3.into(),
2409            job_id: TEST_JOB_ID,
2410            fragment_type_mask: 0,
2411            distribution_type: DistributionType::Hash,
2412            stream_node: StreamNode::from(&PbStreamNode::default()),
2413            state_table_ids: TableIdArray::default(),
2414            upstream_fragment_id: Default::default(),
2415            vnode_count: 0,
2416            parallelism: None,
2417        };
2418
2419        let job_parallelism = StreamingParallelism::Fixed(4);
2420
2421        let policy = super::CatalogController::format_fragment_parallelism_policy(
2422            fragment.distribution_type,
2423            fragment.parallelism.as_ref(),
2424            Some(&job_parallelism),
2425            None,
2426            &[],
2427        );
2428
2429        assert_eq!(policy, "inherit(4)");
2430    }
2431
2432    #[test]
2433    fn test_parallelism_policy_with_adaptive_strategy() {
2434        #[expect(deprecated)]
2435        let fragment = fragment::Model {
2436            fragment_id: 4.into(),
2437            job_id: TEST_JOB_ID,
2438            fragment_type_mask: 0,
2439            distribution_type: DistributionType::Hash,
2440            stream_node: StreamNode::from(&PbStreamNode::default()),
2441            state_table_ids: TableIdArray::default(),
2442            upstream_fragment_id: Default::default(),
2443            vnode_count: 0,
2444            parallelism: None,
2445        };
2446
2447        let job_parallelism = StreamingParallelism::Adaptive;
2448
2449        let policy = super::CatalogController::format_fragment_parallelism_policy(
2450            fragment.distribution_type,
2451            fragment.parallelism.as_ref(),
2452            Some(&job_parallelism),
2453            Some("RATIO(0.5)"),
2454            &[],
2455        );
2456
2457        assert_eq!(policy, "inherit(ratio(0.5))");
2458    }
2459
2460    #[test]
2461    fn test_parallelism_policy_with_custom_strategy() {
2462        #[expect(deprecated)]
2463        let fragment = fragment::Model {
2464            fragment_id: 6.into(),
2465            job_id: TEST_JOB_ID,
2466            fragment_type_mask: 0,
2467            distribution_type: DistributionType::Hash,
2468            stream_node: StreamNode::from(&PbStreamNode::default()),
2469            state_table_ids: TableIdArray::default(),
2470            upstream_fragment_id: Default::default(),
2471            vnode_count: 0,
2472            parallelism: None,
2473        };
2474
2475        let job_parallelism = StreamingParallelism::Custom;
2476
2477        let policy = super::CatalogController::format_fragment_parallelism_policy(
2478            fragment.distribution_type,
2479            fragment.parallelism.as_ref(),
2480            Some(&job_parallelism),
2481            Some("BOUNDED(8)"),
2482            &[],
2483        );
2484
2485        assert_eq!(policy, "inherit(bounded(8))");
2486    }
2487
2488    #[test]
2489    fn test_parallelism_policy_with_invalid_adaptive_strategy_falls_back() {
2490        #[expect(deprecated)]
2491        let fragment = fragment::Model {
2492            fragment_id: 7.into(),
2493            job_id: TEST_JOB_ID,
2494            fragment_type_mask: 0,
2495            distribution_type: DistributionType::Hash,
2496            stream_node: StreamNode::from(&PbStreamNode::default()),
2497            state_table_ids: TableIdArray::default(),
2498            upstream_fragment_id: Default::default(),
2499            vnode_count: 0,
2500            parallelism: None,
2501        };
2502
2503        let job_parallelism = StreamingParallelism::Adaptive;
2504
2505        let policy = super::CatalogController::format_fragment_parallelism_policy(
2506            fragment.distribution_type,
2507            fragment.parallelism.as_ref(),
2508            Some(&job_parallelism),
2509            Some("NOT_A_STRATEGY"),
2510            &[],
2511        );
2512
2513        assert_eq!(policy, "inherit(adaptive)");
2514    }
2515
2516    #[test]
2517    fn test_parallelism_policy_with_upstream_roots() {
2518        #[expect(deprecated)]
2519        let fragment = fragment::Model {
2520            fragment_id: 5.into(),
2521            job_id: TEST_JOB_ID,
2522            fragment_type_mask: 0,
2523            distribution_type: DistributionType::Hash,
2524            stream_node: StreamNode::from(&PbStreamNode::default()),
2525            state_table_ids: TableIdArray::default(),
2526            upstream_fragment_id: Default::default(),
2527            vnode_count: 0,
2528            parallelism: None,
2529        };
2530
2531        let policy = super::CatalogController::format_fragment_parallelism_policy(
2532            fragment.distribution_type,
2533            fragment.parallelism.as_ref(),
2534            None,
2535            None,
2536            &[3.into(), 1.into(), 2.into(), 1.into()],
2537        );
2538
2539        assert_eq!(policy, "upstream_fragment([1, 2, 3])");
2540    }
2541}