Skip to main content

risingwave_meta/controller/catalog/
test.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[cfg(test)]
16mod tests {
17    use std::collections::BTreeMap;
18
19    use risingwave_common::catalog::{FragmentTypeFlag, FragmentTypeMask};
20    use risingwave_common::hash::{VirtualNode, VnodeCount};
21    use risingwave_meta_model::FragmentId;
22    use risingwave_meta_model::fragment::DistributionType;
23    use risingwave_meta_model::table::HandleConflictBehavior;
24    use risingwave_pb::catalog::subscription::SubscriptionState;
25    use risingwave_pb::catalog::{PbSinkType, PbTable, StreamSourceInfo};
26    use risingwave_pb::common::{HostAddress, WorkerNode, WorkerType, worker_node};
27    use risingwave_pb::meta::SubscribeType;
28    use risingwave_pb::meta::table_fragments::fragment::PbFragmentDistributionType;
29    use risingwave_pb::plan_common::ExternalTableDesc;
30    use risingwave_pb::stream_plan::stream_node::PbNodeBody;
31    use risingwave_pb::stream_plan::{PbStreamNode, StreamScanNode, StreamScanType};
32    use tokio::sync::{mpsc, oneshot};
33
34    use crate::barrier::Command;
35    use crate::controller::catalog::*;
36    use crate::manager::{LocalNotification, MetaOpts, WorkerKey};
37    use crate::model::{Fragment, FragmentDownstreamRelation};
38    use crate::serving::ServingVnodeMapping;
39
40    const TEST_DATABASE_ID: DatabaseId = DatabaseId::new(1);
41    const TEST_SCHEMA_ID: SchemaId = SchemaId::new(2);
42    const TEST_OWNER_ID: UserId = UserId::new(1);
43
44    async fn insert_test_table(
45        txn: &DatabaseTransaction,
46        table_id: TableId,
47        name: &str,
48        table_type: TableType,
49        belongs_to_job_id: Option<JobId>,
50        definition: &str,
51    ) -> MetaResult<()> {
52        table::ActiveModel {
53            table_id: Set(table_id),
54            name: Set(name.to_owned()),
55            optional_associated_source_id: Set(None),
56            table_type: Set(table_type),
57            belongs_to_job_id: Set(belongs_to_job_id),
58            columns: Set(vec![].into()),
59            pk: Set(vec![].into()),
60            distribution_key: Set(Vec::<i32>::new().into()),
61            stream_key: Set(Vec::<i32>::new().into()),
62            append_only: Set(false),
63            fragment_id: Set(None),
64            vnode_col_index: Set(None),
65            row_id_index: Set(None),
66            value_indices: Set(Vec::<i32>::new().into()),
67            definition: Set(definition.to_owned()),
68            handle_pk_conflict_behavior: Set(HandleConflictBehavior::NoCheck),
69            version_column_indices: Set(None),
70            read_prefix_len_hint: Set(0),
71            watermark_indices: Set(Vec::<i32>::new().into()),
72            dist_key_in_pk: Set(Vec::<i32>::new().into()),
73            dml_fragment_id: Set(None),
74            cardinality: Set(None),
75            cleaned_by_watermark: Set(false),
76            description: Set(None),
77            version: Set(None),
78            retention_seconds: Set(None),
79            cdc_table_id: Set(None),
80            vnode_count: Set(1),
81            webhook_info: Set(None),
82            engine: Set(None),
83            clean_watermark_index_in_pk: Set(None),
84            clean_watermark_indices: Set(None),
85            refreshable: Set(false),
86            vector_index_info: Set(None),
87            cdc_table_type: Set(None),
88        }
89        .insert(txn)
90        .await?;
91        Ok(())
92    }
93
94    async fn insert_test_fragment(
95        txn: &DatabaseTransaction,
96        fragment_id: FragmentId,
97        job_id: JobId,
98        state_table_ids: TableIdArray,
99    ) -> MetaResult<()> {
100        fragment::ActiveModel {
101            fragment_id: Set(fragment_id),
102            job_id: Set(job_id),
103            fragment_type_mask: Set(0),
104            distribution_type: Set(fragment::DistributionType::Hash),
105            stream_node: Set(StreamNode::from(&PbStreamNode::default())),
106            state_table_ids: Set(state_table_ids),
107            upstream_fragment_id: Set(I32Array::default()),
108            vnode_count: Set(1),
109            parallelism: Set(None),
110        }
111        .insert(txn)
112        .await?;
113        Ok(())
114    }
115
116    async fn insert_test_streaming_job(
117        txn: &DatabaseTransaction,
118        name: &str,
119        has_result_table: bool,
120        policy: Option<CacheRefillPolicy>,
121    ) -> MetaResult<(JobId, Option<TableId>, TableId)> {
122        let object_type = if has_result_table {
123            ObjectType::Table
124        } else {
125            ObjectType::Sink
126        };
127        let job_id = CatalogController::create_object(
128            txn,
129            object_type,
130            TEST_OWNER_ID,
131            Some(TEST_SCHEMA_ID.as_object_id()),
132        )
133        .await?
134        .oid
135        .as_job_id();
136        let result_table_id = has_result_table.then_some(job_id.as_mv_table_id());
137        if let Some(table_id) = result_table_id {
138            insert_test_table(txn, table_id, name, TableType::MaterializedView, None, "").await?;
139        }
140
141        let internal_table_id = CatalogController::create_object(
142            txn,
143            ObjectType::Table,
144            TEST_OWNER_ID,
145            Some(job_id.as_object_id()),
146        )
147        .await?
148        .oid
149        .as_table_id();
150        insert_test_table(
151            txn,
152            internal_table_id,
153            &format!("__internal_{name}"),
154            TableType::Internal,
155            Some(job_id),
156            "",
157        )
158        .await?;
159
160        insert_test_streaming_job_model(txn, job_id, policy).await?;
161
162        Ok((job_id, result_table_id, internal_table_id))
163    }
164
165    async fn insert_test_streaming_job_model(
166        txn: &DatabaseTransaction,
167        job_id: JobId,
168        policy: Option<CacheRefillPolicy>,
169    ) -> MetaResult<()> {
170        streaming_job::ActiveModel {
171            job_id: Set(job_id),
172            job_status: Set(JobStatus::Created),
173            create_type: Set(CreateType::Foreground),
174            timezone: Set(None),
175            config_override: Set(policy.map(|policy| {
176                format!(
177                    "[streaming.developer]\ncache_refill_policy = \"{}\"\n",
178                    policy
179                )
180            })),
181            adaptive_parallelism_strategy: Set(None),
182            parallelism: Set(StreamingParallelism::Adaptive),
183            backfill_parallelism: Set(None),
184            backfill_adaptive_parallelism_strategy: Set(None),
185            backfill_orders: Set(None),
186            max_parallelism: Set(1),
187            specific_resource_group: Set(None),
188            is_serverless_backfill: Set(false),
189            refresh_interval_sec: Set(None),
190        }
191        .insert(txn)
192        .await?;
193
194        Ok(())
195    }
196
197    #[tokio::test]
198    async fn test_iceberg_update_fragment_throttle_is_not_persisted() -> MetaResult<()> {
199        use risingwave_pb::common::ThrottleType;
200        use risingwave_pb::stream_plan::{
201            SourceNode, StreamFsFetch, StreamFsFetchNode, StreamSource,
202        };
203
204        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
205        let inner = mgr.inner.write().await;
206        let txn = inner.db.begin().await?;
207        let (job_id, _, _) = insert_test_streaming_job(&txn, "iceberg_updates", true, None).await?;
208        let fragment_id = FragmentId::new(100);
209        insert_test_fragment(&txn, fragment_id, job_id, TableIdArray::default()).await?;
210        txn.commit().await?;
211        drop(inner);
212
213        let properties = std::collections::BTreeMap::from([
214            ("connector".to_owned(), "iceberg".to_owned()),
215            ("streaming_updates".to_owned(), "true".to_owned()),
216        ]);
217        let legacy_source = PbStreamNode {
218            node_body: Some(PbNodeBody::Source(Box::new(SourceNode {
219                source_inner: Some(StreamSource::default()),
220            }))),
221            ..Default::default()
222        };
223        for body in [
224            PbNodeBody::Source(Box::new(SourceNode {
225                source_inner: Some(StreamSource {
226                    with_properties: properties.clone(),
227                    ..Default::default()
228                }),
229            })),
230            PbNodeBody::StreamFsFetch(Box::new(StreamFsFetchNode {
231                node_inner: Some(StreamFsFetch {
232                    with_properties: properties.clone(),
233                    ..Default::default()
234                }),
235            })),
236        ] {
237            // Ordinary nodes before and after the update node must not mask rejection.
238            let original = PbStreamNode {
239                node_body: Some(PbNodeBody::Union(Default::default())),
240                input: vec![
241                    legacy_source.clone(),
242                    PbStreamNode {
243                        node_body: Some(body),
244                        ..Default::default()
245                    },
246                    legacy_source.clone(),
247                ],
248                ..Default::default()
249            };
250            fragment::ActiveModel {
251                fragment_id: Set(fragment_id),
252                stream_node: Set(StreamNode::from(&original)),
253                ..Default::default()
254            }
255            .update(&mgr.inner.read().await.db)
256            .await?;
257            for rate_limit in [None, Some(0), Some(100)] {
258                let error = mgr
259                    .update_fragment_rate_limit_by_fragment_id(
260                        fragment_id,
261                        ThrottleType::Source,
262                        rate_limit,
263                    )
264                    .await
265                    .expect_err("update sources cannot be throttled");
266                assert!(error.to_string().contains("streaming_updates"));
267                let persisted = risingwave_meta_model::prelude::Fragment::find_by_id(fragment_id)
268                    .one(&mgr.inner.read().await.db)
269                    .await?
270                    .unwrap();
271                assert_eq!(persisted.stream_node.to_protobuf(), original);
272            }
273        }
274        fragment::ActiveModel {
275            fragment_id: Set(fragment_id),
276            stream_node: Set(StreamNode::from(&legacy_source)),
277            ..Default::default()
278        }
279        .update(&mgr.inner.read().await.db)
280        .await?;
281        let updated = mgr
282            .update_fragment_rate_limit_by_fragment_id(fragment_id, ThrottleType::Source, Some(100))
283            .await?;
284        let Some(PbNodeBody::Source(source)) = updated.node_body else {
285            unreachable!()
286        };
287        assert_eq!(source.source_inner.unwrap().rate_limit, Some(100));
288
289        // The source-ID API must also roll back its catalog update on rejection.
290        mgr.create_source(
291            PbSource {
292                schema_id: TEST_SCHEMA_ID,
293                database_id: TEST_DATABASE_ID,
294                name: "iceberg_update_source".to_owned(),
295                owner: TEST_OWNER_ID as _,
296                with_properties: properties,
297                info: Some(StreamSourceInfo::default()),
298                ..Default::default()
299            },
300            None,
301        )
302        .await?;
303        let source = Source::find()
304            .filter(source::Column::Name.eq("iceberg_update_source"))
305            .one(&mgr.inner.read().await.db)
306            .await?
307            .unwrap();
308        let error = mgr
309            .update_source_rate_limit_by_source_id(source.source_id, Some(100))
310            .await
311            .expect_err("source-ID throttling must also fail");
312        assert!(error.to_string().contains("streaming_updates"));
313        let persisted = Source::find_by_id(source.source_id)
314            .one(&mgr.inner.read().await.db)
315            .await?
316            .unwrap();
317        assert_eq!(persisted, source);
318        Ok(())
319    }
320
321    #[tokio::test]
322    async fn test_cancel_creating_job_includes_belonging_streaming_jobs() -> MetaResult<()> {
323        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
324        let mut inner = mgr.inner.write().await;
325        let txn = inner.db.begin().await?;
326
327        let table_job_id = CatalogController::create_object(
328            &txn,
329            ObjectType::Table,
330            TEST_OWNER_ID,
331            Some(TEST_SCHEMA_ID.as_object_id()),
332        )
333        .await?
334        .oid
335        .as_job_id();
336        insert_test_table(
337            &txn,
338            table_job_id.as_mv_table_id(),
339            "cancel_table",
340            TableType::Table,
341            None,
342            "",
343        )
344        .await?;
345        let sink_job_id = CatalogController::create_object(
346            &txn,
347            ObjectType::Sink,
348            TEST_OWNER_ID,
349            Some(table_job_id.as_object_id()),
350        )
351        .await?
352        .oid
353        .as_job_id();
354        Sink::insert(sink::ActiveModel::from(PbSink {
355            id: sink_job_id.as_sink_id(),
356            schema_id: TEST_SCHEMA_ID,
357            database_id: TEST_DATABASE_ID,
358            name: "cancel_sink".to_owned(),
359            owner: TEST_OWNER_ID as _,
360            sink_type: PbSinkType::AppendOnly as i32,
361            ..Default::default()
362        }))
363        .exec(&txn)
364        .await?;
365        for job_id in [table_job_id, sink_job_id] {
366            insert_test_streaming_job_model(&txn, job_id, None).await?;
367            StreamingJob::update(streaming_job::ActiveModel {
368                job_id: Set(job_id),
369                job_status: Set(JobStatus::Creating),
370                ..Default::default()
371            })
372            .exec(&txn)
373            .await?;
374        }
375
376        let table_state_id = TableId::new(1000);
377        let sink_state_id = TableId::new(1001);
378        insert_test_fragment(
379            &txn,
380            FragmentId::new(100),
381            table_job_id,
382            TableIdArray(vec![table_state_id]),
383        )
384        .await?;
385        insert_test_fragment(
386            &txn,
387            FragmentId::new(101),
388            sink_job_id,
389            TableIdArray(vec![sink_state_id]),
390        )
391        .await?;
392        let (table_finish_tx, table_finish_rx) = oneshot::channel();
393        inner.register_finish_notifier(TEST_DATABASE_ID, table_job_id, table_finish_tx);
394        let (sink_finish_tx, sink_finish_rx) = oneshot::channel();
395        inner.register_finish_notifier(TEST_DATABASE_ID, sink_job_id, sink_finish_tx);
396        txn.commit().await?;
397        drop(inner);
398
399        let abort_result = mgr
400            .try_abort_creating_streaming_job(table_job_id, true)
401            .await?;
402        assert!(abort_result.aborted);
403        assert_eq!(
404            abort_result.aborted_sink_ids,
405            vec![sink_job_id.as_sink_id()]
406        );
407        let cancel_info = abort_result
408            .cancel_info
409            .expect("cancelled table job should have cleanup information");
410        assert_eq!(
411            cancel_info
412                .streaming_job_ids
413                .iter()
414                .copied()
415                .collect::<HashSet<_>>(),
416            HashSet::from([table_job_id, sink_job_id])
417        );
418        assert_eq!(
419            cancel_info
420                .state_table_ids
421                .iter()
422                .copied()
423                .collect::<HashSet<_>>(),
424            HashSet::from([table_state_id, sink_state_id])
425        );
426        let Command::DropStreamingJobs {
427            streaming_job_ids,
428            unregistered_state_table_ids,
429            ..
430        } = cancel_info.command
431        else {
432            unreachable!()
433        };
434        assert_eq!(
435            streaming_job_ids,
436            HashSet::from([table_job_id, sink_job_id])
437        );
438        assert_eq!(
439            unregistered_state_table_ids,
440            HashSet::from([table_state_id, sink_state_id])
441        );
442
443        for finish_rx in [table_finish_rx, sink_finish_rx] {
444            let err = finish_rx
445                .await
446                .expect("aborted job should notify its finish waiter")
447                .expect_err("aborted job should not finish successfully");
448            assert!(err.contains("cancelled"));
449        }
450        let db = &mgr.inner.read().await.db;
451        assert!(Object::find_by_id(table_job_id).one(db).await?.is_none());
452        assert!(Object::find_by_id(sink_job_id).one(db).await?.is_none());
453
454        Ok(())
455    }
456
457    #[tokio::test]
458    async fn test_create_multiple_sinks_into_same_table_and_drop_table() -> MetaResult<()> {
459        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
460        let inner = mgr.inner.write().await;
461        let txn = inner.db.begin().await?;
462        let (_, Some(target_table_id), _) =
463            insert_test_streaming_job(&txn, "mvt", true, None).await?
464        else {
465            unreachable!()
466        };
467        let (mv1_id, Some(_), _) = insert_test_streaming_job(&txn, "mv1", true, None).await? else {
468            unreachable!()
469        };
470        let (mv2_id, Some(_), _) = insert_test_streaming_job(&txn, "mv2", true, None).await? else {
471            unreachable!()
472        };
473        txn.commit().await?;
474        drop(inner);
475
476        let mut sink_ids = Vec::new();
477        let test_sink_tuples = [("s1", mv1_id), ("s2", mv2_id)];
478
479        fn assert_incoming_sink_drop_error<T>(error: &MetaError, test_sink_tuples: &[(&str, T)]) {
480            let message = error.to_string();
481
482            assert!(
483                message.contains("sink") && message.contains("depends on it"),
484                "expected an incoming-sink dependency error, got: {message}"
485            );
486
487            assert!(
488                test_sink_tuples
489                    .iter()
490                    .all(|(sink_name, _)| message.contains(*sink_name)),
491                "expected the error to mention all incoming sinks, got: {message}"
492            );
493        }
494
495        for (name, source) in test_sink_tuples {
496            let mut job = crate::manager::StreamingJob::Sink(
497                PbSink {
498                    name: name.to_owned(),
499                    database_id: TEST_DATABASE_ID,
500                    schema_id: TEST_SCHEMA_ID,
501                    owner: TEST_OWNER_ID as _,
502                    target_table: Some(target_table_id),
503                    sink_type: PbSinkType::AppendOnly as i32,
504                    ..Default::default()
505                },
506                None,
507            );
508            // Use create_job_catalog to trigger construct_sink_cycle_check_query for regression
509            // testing purpose to ensure no circular issue causing infinite recursion when
510            // cte_referencing
511            tokio::time::timeout(
512                std::time::Duration::from_secs(3),
513                mgr.create_job_catalog(
514                    &mut job,
515                    &crate::model::StreamContext::default(),
516                    &None,
517                    1,
518                    HashSet::from([source.as_object_id()]),
519                    risingwave_pb::ddl_service::streaming_job_resource_type::ResourceType::Regular(
520                        true,
521                    ),
522                    &None,
523                    None,
524                    None,
525                    None,
526                    None,
527                ),
528            )
529            .await
530            .expect("creating a second sink into the same table should not hang")?;
531            sink_ids.push(job.id().as_object_id());
532        }
533        let owned_sink_name = "owned_sink_without_iceberg_prefix";
534        let mut owned_sink = crate::manager::StreamingJob::Sink(
535            PbSink {
536                name: owned_sink_name.to_owned(),
537                database_id: TEST_DATABASE_ID,
538                schema_id: TEST_SCHEMA_ID,
539                owner: TEST_OWNER_ID as _,
540                target_table: Some(target_table_id),
541                sink_type: PbSinkType::AppendOnly as i32,
542                ..Default::default()
543            },
544            Some(target_table_id),
545        );
546        mgr.create_job_catalog(
547            &mut owned_sink,
548            &crate::model::StreamContext::default(),
549            &None,
550            1,
551            HashSet::from([mv1_id.as_object_id()]),
552            risingwave_pb::ddl_service::streaming_job_resource_type::ResourceType::Regular(true),
553            &None,
554            None,
555            None,
556            None,
557            None,
558        )
559        .await?;
560        let owned_sink_id = owned_sink.id().as_object_id();
561        sink_ids.push(owned_sink_id);
562
563        // Ensure the test sinks were created
564        assert_eq!(sink_ids.len(), test_sink_tuples.len() + 1);
565
566        let inner = mgr.inner.read().await;
567        for sink_id in &sink_ids {
568            streaming_job::ActiveModel {
569                job_id: Set(sink_id.as_job_id()),
570                job_status: Set(JobStatus::Created),
571                ..Default::default()
572            }
573            .update(&inner.db)
574            .await?;
575        }
576        // Ensure no object_dependency created for (target_table, sink) which could cause circular
577        // issue
578        let object_dependency_count = ObjectDependency::find()
579            .filter(object_dependency::Column::Oid.eq(target_table_id.as_object_id()))
580            .filter(object_dependency::Column::UsedBy.is_in(sink_ids.clone()))
581            .count(&inner.db)
582            .await?;
583        assert_eq!(object_dependency_count, 0);
584        assert_eq!(
585            Object::find_by_id(owned_sink_id)
586                .one(&inner.db)
587                .await?
588                .unwrap()
589                .belong_to_oid,
590            Some(target_table_id.as_object_id())
591        );
592        drop(inner);
593
594        let error = mgr
595            .drop_object(ObjectType::Table, target_table_id, DropMode::Restrict)
596            .await
597            .expect_err("RESTRICT drop should fail for a table with incoming sinks");
598        assert_incoming_sink_drop_error(&error, &test_sink_tuples);
599        assert!(
600            !error.to_string().contains(owned_sink_name),
601            "an owned incoming sink should not prevent a RESTRICT drop"
602        );
603        mgr.drop_object(ObjectType::Table, target_table_id, DropMode::Cascade)
604            .await
605            .expect("CASCADE drop should succeed");
606
607        let inner = mgr.inner.read().await;
608        let db = &inner.db;
609        // Check that the cascade drop successfully dropped
610        assert!(Object::find_by_id(target_table_id).one(db).await?.is_none());
611        assert_eq!(
612            Object::find()
613                .filter(object::Column::Oid.is_in(sink_ids))
614                .count(db)
615                .await?,
616            0
617        );
618        // Sanity checks that sources were not dropped
619        assert!(Object::find_by_id(mv1_id).one(db).await?.is_some());
620        assert!(Object::find_by_id(mv2_id).one(db).await?.is_some());
621
622        Ok(())
623    }
624
625    #[tokio::test]
626    async fn test_replace_upstream_object_rejects_creating_incoming_sink() -> MetaResult<()> {
627        fn assert_replace_concurrency_error(error: &MetaError) {
628            let message = error.to_string();
629            // Ensures the replacement failed because a referring streaming job is still creating.
630            assert!(
631                message.contains("referenced by some creating jobs"),
632                "expected a replace concurrency error, got: {message}"
633            );
634        }
635
636        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
637        let inner = mgr.inner.write().await;
638        let txn = inner.db.begin().await?;
639        let (target_mv_id, Some(target_mv_table_id), _) =
640            insert_test_streaming_job(&txn, "target_mv", true, None).await?
641        else {
642            unreachable!()
643        };
644        let (source_mv_id, Some(_), _) =
645            insert_test_streaming_job(&txn, "source_mv", true, None).await?
646        else {
647            unreachable!()
648        };
649        txn.commit().await?;
650        drop(inner);
651
652        let mut sink = crate::manager::StreamingJob::Sink(
653            PbSink {
654                name: "creating_sink".to_owned(),
655                database_id: TEST_DATABASE_ID,
656                schema_id: TEST_SCHEMA_ID,
657                owner: TEST_OWNER_ID as _,
658                target_table: Some(target_mv_table_id),
659                sink_type: PbSinkType::AppendOnly as i32,
660                ..Default::default()
661            },
662            None,
663        );
664        let creating_sink = mgr
665            .create_job_catalog(
666                &mut sink,
667                &crate::model::StreamContext::default(),
668                &None,
669                1,
670                HashSet::from([source_mv_id.as_object_id()]),
671                risingwave_pb::ddl_service::streaming_job_resource_type::ResourceType::Regular(
672                    true,
673                ),
674                &None,
675                None,
676                None,
677                None,
678                None,
679            )
680            .await?;
681        // Ensures the incoming sink is still creating, which should block replacement.
682        assert_ne!(creating_sink.job_status, JobStatus::Created);
683
684        let replacement = crate::manager::StreamingJob::MaterializedView(PbTable {
685            id: target_mv_table_id,
686            name: "target_mv".to_owned(),
687            database_id: TEST_DATABASE_ID,
688            schema_id: TEST_SCHEMA_ID,
689            owner: TEST_OWNER_ID as _,
690            ..Default::default()
691        });
692        // Ensures the replacement targets the upstream MV that the creating sink depends on.
693        assert_eq!(replacement.id(), target_mv_id);
694
695        // Ensures replacement rejects the upstream MV while its referring sink is creating.
696        let error = mgr
697            .create_job_catalog_for_replace(&replacement, None, None, None)
698            .await
699            .expect_err("replacement should reject a creating incoming sink");
700        // Ensures the rejection error reports the expected concurrency reason.
701        assert_replace_concurrency_error(&error);
702
703        Ok(())
704    }
705
706    #[tokio::test]
707    async fn test_replace_upstream_object_with_created_incoming_sink() -> MetaResult<()> {
708        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
709        let inner = mgr.inner.write().await;
710        let txn = inner.db.begin().await?;
711        let (_, Some(target_table_id), _) =
712            insert_test_streaming_job(&txn, "target_table", true, None).await?
713        else {
714            unreachable!()
715        };
716        let (source_mv_id, Some(source_mv_table_id), _) =
717            insert_test_streaming_job(&txn, "source_mv", true, None).await?
718        else {
719            unreachable!()
720        };
721        txn.commit().await?;
722        drop(inner);
723
724        let mut sink = crate::manager::StreamingJob::Sink(
725            PbSink {
726                name: "created_sink".to_owned(),
727                database_id: TEST_DATABASE_ID,
728                schema_id: TEST_SCHEMA_ID,
729                owner: TEST_OWNER_ID as _,
730                target_table: Some(target_table_id),
731                sink_type: PbSinkType::AppendOnly as i32,
732                ..Default::default()
733            },
734            None,
735        );
736        let creating_sink = mgr
737            .create_job_catalog(
738                &mut sink,
739                &crate::model::StreamContext::default(),
740                &None,
741                1,
742                HashSet::from([source_mv_id.as_object_id()]),
743                risingwave_pb::ddl_service::streaming_job_resource_type::ResourceType::Regular(
744                    true,
745                ),
746                &None,
747                None,
748                None,
749                None,
750                None,
751            )
752            .await?;
753        // Ensures the incoming sink starts as a creating job before the test marks it created.
754        assert_ne!(creating_sink.job_status, JobStatus::Created);
755
756        let sink_id = sink.id();
757        let inner = mgr.inner.read().await;
758        streaming_job::ActiveModel {
759            job_id: Set(sink_id),
760            job_status: Set(JobStatus::Created),
761            ..Default::default()
762        }
763        .update(&inner.db)
764        .await?;
765        let sink_model = risingwave_meta_model::prelude::StreamingJob::find_by_id(sink_id)
766            .one(&inner.db)
767            .await?
768            .expect("sink should exist");
769        // Ensures the persisted sink row is the sink created by this test.
770        assert_eq!(sink_model.job_id, sink_id);
771        // Ensures a fully created incoming sink does not block upstream MV replacement.
772        assert_eq!(sink_model.job_status, JobStatus::Created);
773        drop(inner);
774
775        let replacement = crate::manager::StreamingJob::MaterializedView(PbTable {
776            id: source_mv_table_id,
777            name: "source_mv".to_owned(),
778            database_id: TEST_DATABASE_ID,
779            schema_id: TEST_SCHEMA_ID,
780            owner: TEST_OWNER_ID as _,
781            ..Default::default()
782        });
783        // Ensures the replacement targets the upstream MV that the created sink depends on.
784        assert_eq!(replacement.id(), source_mv_id);
785
786        let tmp_model = mgr
787            .create_job_catalog_for_replace(&replacement, None, None, None)
788            .await?;
789
790        // Ensures replacement creates a distinct temporary job instead of reusing the original MV id.
791        assert_ne!(tmp_model.job_id, source_mv_id);
792        // Ensures the temporary replacement job is created but not finished yet.
793        assert_eq!(tmp_model.job_status, JobStatus::Initial);
794
795        let inner = mgr.inner.read().await;
796        let db = &inner.db;
797        // Ensures the created sink still depends on the upstream MV being replaced.
798        assert_eq!(
799            ObjectDependency::find()
800                .filter(object_dependency::Column::Oid.eq(source_mv_id.as_object_id()))
801                .filter(object_dependency::Column::UsedBy.eq(sink_id.as_object_id()))
802                .count(db)
803                .await?,
804            1
805        );
806        // Ensures replacement records the temporary job as a dependent of the original MV.
807        assert_eq!(
808            ObjectDependency::find()
809                .filter(object_dependency::Column::Oid.eq(source_mv_id.as_object_id()))
810                .filter(object_dependency::Column::UsedBy.eq(tmp_model.job_id.as_object_id()))
811                .count(db)
812                .await?,
813            1
814        );
815
816        Ok(())
817    }
818
819    #[tokio::test]
820    async fn test_table_refill_catalog_snapshot_classifies_table_identity() -> MetaResult<()> {
821        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
822        let inner = mgr.inner.write().await;
823        let txn = inner.db.begin().await?;
824
825        let (mv_job, Some(mv_result), mv_internal) =
826            insert_test_streaming_job(&txn, "mv_both", true, Some(CacheRefillPolicy::Both)).await?
827        else {
828            unreachable!()
829        };
830        let (default_job, Some(_default_result), default_internal) =
831            insert_test_streaming_job(&txn, "mv_default", true, None).await?
832        else {
833            unreachable!()
834        };
835        let (sink_job, None, sink_internal) = insert_test_streaming_job(
836            &txn,
837            "sink_streaming",
838            false,
839            Some(CacheRefillPolicy::Streaming),
840        )
841        .await?
842        else {
843            unreachable!()
844        };
845
846        let result_fragment = FragmentId::new(100);
847        let internal_fragment = FragmentId::new(101);
848        let sink_fragment = FragmentId::new(102);
849        for (fragment_id, job_id, table_ids) in [
850            (result_fragment, mv_job, vec![mv_result, mv_internal]),
851            (internal_fragment, default_job, vec![default_internal]),
852            (sink_fragment, sink_job, vec![sink_internal]),
853        ] {
854            insert_test_fragment(&txn, fragment_id, job_id, TableIdArray(table_ids)).await?;
855        }
856        txn.commit().await?;
857        drop(inner);
858
859        let serving_infos = mgr.fragment_serving_infos().await?;
860        assert_eq!(serving_infos.len(), 3);
861        assert_eq!(
862            serving_infos[&result_fragment].result_table_id,
863            Some(mv_result)
864        );
865        assert_eq!(serving_infos[&internal_fragment].result_table_id, None);
866        assert_eq!(serving_infos[&sink_fragment].result_table_id, None);
867
868        let policies = mgr.table_cache_refill_policies_snapshot().await?;
869        assert_eq!(
870            policies
871                .table_policies
872                .into_iter()
873                .map(|policy| (policy.table_id, policy.policy))
874                .collect::<HashMap<_, _>>(),
875            HashMap::from([(
876                mv_result.as_raw_id(),
877                CacheRefillPolicy::Both.to_protobuf() as i32,
878            )])
879        );
880        assert_eq!(
881            policies
882                .internal_table_policies
883                .into_iter()
884                .map(|policy| (policy.table_id, policy.policy))
885                .collect::<HashMap<_, _>>(),
886            HashMap::from([
887                (
888                    mv_internal.as_raw_id(),
889                    CacheRefillPolicy::Both.to_protobuf() as i32,
890                ),
891                (
892                    sink_internal.as_raw_id(),
893                    CacheRefillPolicy::Streaming.to_protobuf() as i32,
894                ),
895            ])
896        );
897
898        Ok(())
899    }
900
901    #[tokio::test]
902    async fn test_foreground_creating_catalog_lifecycle() -> MetaResult<()> {
903        let env = MetaSrvEnv::for_test().await;
904        let (tx, mut notification_rx) = mpsc::unbounded_channel();
905        env.notification_manager().insert_sender(
906            SubscribeType::Frontend,
907            WorkerKey(HostAddress {
908                host: "localhost".to_owned(),
909                port: 1234,
910            }),
911            tx,
912        );
913        let mgr = CatalogController::new(env).await?;
914        let inner = mgr.inner.write().await;
915        let txn = inner.db.begin().await?;
916
917        // A foreground table and its internal table are both visible while creating.
918        let (job_id, Some(table_id), internal_table_id) =
919            insert_test_streaming_job(&txn, "creating_table", true, None).await?
920        else {
921            unreachable!()
922        };
923        let associated_source_id = CatalogController::create_object(
924            &txn,
925            ObjectType::Source,
926            TEST_OWNER_ID,
927            Some(TEST_SCHEMA_ID.as_object_id()),
928        )
929        .await?
930        .oid
931        .as_source_id();
932        Source::insert(source::ActiveModel::from(PbSource {
933            id: associated_source_id,
934            schema_id: TEST_SCHEMA_ID,
935            database_id: TEST_DATABASE_ID,
936            name: "creating_table_source".to_owned(),
937            owner: TEST_OWNER_ID as _,
938            optional_associated_table_id: Some(
939                risingwave_pb::catalog::source::OptionalAssociatedTableId::AssociatedTableId(
940                    table_id,
941                ),
942            ),
943            ..Default::default()
944        }))
945        .exec(&txn)
946        .await?;
947        table::ActiveModel {
948            table_id: Set(table_id),
949            table_type: Set(TableType::Table),
950            optional_associated_source_id: Set(Some(associated_source_id)),
951            ..Default::default()
952        }
953        .update(&txn)
954        .await?;
955        streaming_job::ActiveModel {
956            job_id: Set(job_id),
957            job_status: Set(JobStatus::Initial),
958            ..Default::default()
959        }
960        .update(&txn)
961        .await?;
962
963        // A foreground index and its index table are both visible while creating.
964        let (_primary_job_id, Some(primary_table_id), _) =
965            insert_test_streaming_job(&txn, "primary_table", true, None).await?
966        else {
967            unreachable!()
968        };
969        let index_job_id = CatalogController::create_object(
970            &txn,
971            ObjectType::Index,
972            TEST_OWNER_ID,
973            Some(TEST_SCHEMA_ID.as_object_id()),
974        )
975        .await?
976        .oid
977        .as_job_id();
978        let index_table_id = index_job_id.as_mv_table_id();
979        insert_test_table(
980            &txn,
981            index_table_id,
982            "creating_index",
983            TableType::Index,
984            None,
985            "",
986        )
987        .await?;
988        index::ActiveModel {
989            index_id: Set(index_job_id.as_index_id()),
990            name: Set("creating_index".to_owned()),
991            index_table_id: Set(index_table_id),
992            primary_table_id: Set(primary_table_id),
993            index_items: Set(vec![].into()),
994            index_column_properties: Set(None),
995            index_columns_len: Set(0),
996        }
997        .insert(&txn)
998        .await?;
999        insert_test_streaming_job_model(&txn, index_job_id, None).await?;
1000        streaming_job::ActiveModel {
1001            job_id: Set(index_job_id),
1002            job_status: Set(JobStatus::Initial),
1003            ..Default::default()
1004        }
1005        .update(&txn)
1006        .await?;
1007
1008        // A creating shared source is included in restart snapshots as well.
1009        let source_job_id = CatalogController::create_object(
1010            &txn,
1011            ObjectType::Source,
1012            TEST_OWNER_ID,
1013            Some(TEST_SCHEMA_ID.as_object_id()),
1014        )
1015        .await?
1016        .oid
1017        .as_job_id();
1018        Source::insert(source::ActiveModel::from(PbSource {
1019            id: source_job_id.as_shared_source_id(),
1020            schema_id: TEST_SCHEMA_ID,
1021            database_id: TEST_DATABASE_ID,
1022            name: "creating_shared_source".to_owned(),
1023            owner: TEST_OWNER_ID as _,
1024            info: Some(StreamSourceInfo {
1025                cdc_source_job: true,
1026                ..Default::default()
1027            }),
1028            ..Default::default()
1029        }))
1030        .exec(&txn)
1031        .await?;
1032        insert_test_streaming_job_model(&txn, source_job_id, None).await?;
1033        streaming_job::ActiveModel {
1034            job_id: Set(source_job_id),
1035            job_status: Set(JobStatus::Initial),
1036            ..Default::default()
1037        }
1038        .update(&txn)
1039        .await?;
1040
1041        let sink_job_id = CatalogController::create_object(
1042            &txn,
1043            ObjectType::Sink,
1044            TEST_OWNER_ID,
1045            Some(TEST_SCHEMA_ID.as_object_id()),
1046        )
1047        .await?
1048        .oid
1049        .as_job_id();
1050        Sink::insert(sink::ActiveModel::from(PbSink {
1051            id: sink_job_id.as_sink_id(),
1052            schema_id: TEST_SCHEMA_ID,
1053            database_id: TEST_DATABASE_ID,
1054            name: "creating_sink".to_owned(),
1055            owner: TEST_OWNER_ID as _,
1056            sink_type: PbSinkType::AppendOnly as i32,
1057            ..Default::default()
1058        }))
1059        .exec(&txn)
1060        .await?;
1061        insert_test_streaming_job_model(&txn, sink_job_id, None).await?;
1062        streaming_job::ActiveModel {
1063            job_id: Set(sink_job_id),
1064            job_status: Set(JobStatus::Initial),
1065            ..Default::default()
1066        }
1067        .update(&txn)
1068        .await?;
1069
1070        txn.commit().await?;
1071
1072        let (catalog, _) = inner.snapshot().await?;
1073        assert!(!catalog.2.iter().any(|table| table.id == table_id));
1074        assert!(!catalog.2.iter().any(|table| table.id == internal_table_id));
1075        assert!(!catalog.2.iter().any(|table| table.id == index_table_id));
1076        assert!(
1077            !catalog
1078                .3
1079                .iter()
1080                .any(|source| source.id == associated_source_id)
1081        );
1082        assert!(
1083            !catalog
1084                .3
1085                .iter()
1086                .any(|source| source.id == source_job_id.as_shared_source_id())
1087        );
1088        assert!(
1089            !catalog
1090                .6
1091                .iter()
1092                .any(|index| index.id == index_job_id.as_index_id())
1093        );
1094        assert!(
1095            !catalog
1096                .4
1097                .iter()
1098                .any(|sink| sink.id == sink_job_id.as_sink_id())
1099        );
1100
1101        drop(inner);
1102
1103        let downstreams = FragmentDownstreamRelation::new();
1104        let mut add_notifications = vec![];
1105        for creating_job_id in [job_id, index_job_id, source_job_id, sink_job_id] {
1106            mgr.post_collect_job_fragments(creating_job_id, &downstreams, None, None, None, true)
1107                .await?;
1108            let notification = notification_rx
1109                .recv()
1110                .await
1111                .expect("frontend should receive a creating notification")
1112                .into_notification()
1113                .expect("creating notification should be valid");
1114            assert_eq!(notification.operation(), NotificationOperation::Add);
1115            let object_group = match notification.info {
1116                Some(NotificationInfo::ObjectGroup(object_group)) => object_group,
1117                other => panic!("unexpected notification: {other:?}"),
1118            };
1119            add_notifications.push(object_group);
1120        }
1121
1122        assert!(add_notifications[0].objects.iter().any(|object| matches!(
1123            &object.object_info,
1124            Some(PbObjectInfo::Table(table)) if table.id == table_id
1125        )));
1126        assert!(add_notifications[0].objects.iter().any(|object| matches!(
1127            &object.object_info,
1128            Some(PbObjectInfo::Table(table)) if table.id == internal_table_id
1129        )));
1130        assert!(add_notifications[0].objects.iter().any(|object| matches!(
1131            &object.object_info,
1132            Some(PbObjectInfo::Source(source)) if source.id == associated_source_id
1133        )));
1134        assert!(add_notifications[1].objects.iter().any(|object| matches!(
1135            &object.object_info,
1136            Some(PbObjectInfo::Table(table)) if table.id == index_table_id
1137        )));
1138        assert!(add_notifications[1].objects.iter().any(|object| matches!(
1139            &object.object_info,
1140            Some(PbObjectInfo::Index(index)) if index.id == index_job_id.as_index_id()
1141        )));
1142        assert!(add_notifications[2].objects.iter().any(|object| matches!(
1143            &object.object_info,
1144            Some(PbObjectInfo::Source(source)) if source.id == source_job_id.as_shared_source_id()
1145        )));
1146        assert!(add_notifications[3].objects.iter().any(|object| matches!(
1147            &object.object_info,
1148            Some(PbObjectInfo::Sink(sink)) if sink.id == sink_job_id.as_sink_id()
1149        )));
1150
1151        let inner = mgr.inner.write().await;
1152        let (catalog, _) = inner.snapshot().await?;
1153        assert!(catalog.2.iter().any(|table| table.id == table_id));
1154        assert!(catalog.2.iter().any(|table| table.id == internal_table_id));
1155        assert!(catalog.2.iter().any(|table| table.id == index_table_id));
1156        assert!(
1157            catalog
1158                .3
1159                .iter()
1160                .any(|source| source.id == source_job_id.as_shared_source_id())
1161        );
1162        assert!(
1163            catalog
1164                .6
1165                .iter()
1166                .any(|index| index.id == index_job_id.as_index_id())
1167        );
1168        assert!(
1169            catalog
1170                .4
1171                .iter()
1172                .any(|sink| sink.id == sink_job_id.as_sink_id())
1173        );
1174
1175        let txn = inner.db.begin().await?;
1176        let (operation, _, _, _) = mgr.finish_streaming_job_inner(&txn, job_id).await?;
1177        assert_eq!(operation, NotificationOperation::Update);
1178        let (operation, _, _, _) = mgr.finish_streaming_job_inner(&txn, index_job_id).await?;
1179        assert_eq!(operation, NotificationOperation::Update);
1180        let (operation, _, _, _) = mgr.finish_streaming_job_inner(&txn, source_job_id).await?;
1181        assert_eq!(operation, NotificationOperation::Update);
1182        let (operation, _, _, _) = mgr.finish_streaming_job_inner(&txn, sink_job_id).await?;
1183        assert_eq!(operation, NotificationOperation::Update);
1184        txn.commit().await?;
1185
1186        Ok(())
1187    }
1188
1189    #[tokio::test]
1190    async fn test_alter_streaming_job_cache_refill_policy_notifies_hummock() -> MetaResult<()> {
1191        let env = MetaSrvEnv::for_test().await;
1192        let (tx, mut rx) = mpsc::unbounded_channel();
1193        env.notification_manager().insert_sender(
1194            SubscribeType::Hummock,
1195            WorkerKey(HostAddress {
1196                host: "localhost".to_owned(),
1197                port: 1234,
1198            }),
1199            tx,
1200        );
1201        let mgr = CatalogController::new(env).await?;
1202
1203        let inner = mgr.inner.write().await;
1204        let txn = inner.db.begin().await?;
1205        let (_job, Some(result_table_id), internal_table_id) =
1206            insert_test_streaming_job(&txn, "mv_cache_refill", true, None).await?
1207        else {
1208            unreachable!()
1209        };
1210        insert_test_fragment(
1211            &txn,
1212            FragmentId::new(200),
1213            result_table_id.as_job_id(),
1214            TableIdArray(vec![result_table_id, internal_table_id]),
1215        )
1216        .await?;
1217        txn.commit().await?;
1218        drop(inner);
1219
1220        mgr.alter_streaming_job_config(
1221            result_table_id.as_job_id(),
1222            HashMap::from([(
1223                STREAMING_CACHE_REFILL_POLICY_CONFIG_PATH.to_owned(),
1224                "\"both\"".to_owned(),
1225            )]),
1226            vec![],
1227        )
1228        .await?;
1229
1230        let response = rx
1231            .recv()
1232            .await
1233            .expect("should receive hummock notification")
1234            .into_notification()
1235            .expect("notification should be ok");
1236        assert_eq!(response.operation(), NotificationOperation::Update);
1237        let info = response.info;
1238        let Some(NotificationInfo::TableRefillRuntimeConfig(config)) = info else {
1239            panic!("unexpected notification: {:?}", info);
1240        };
1241        assert!(config.serving_table_vnode_mappings.is_none());
1242        let policies = config
1243            .table_cache_refill_policies
1244            .expect("policy snapshot should be present");
1245        assert_eq!(
1246            policies
1247                .table_policies
1248                .into_iter()
1249                .map(|policy| (policy.table_id, policy.policy))
1250                .collect::<HashMap<_, _>>(),
1251            HashMap::from([(
1252                result_table_id.as_raw_id(),
1253                CacheRefillPolicy::Both.to_protobuf() as i32,
1254            )])
1255        );
1256        assert_eq!(
1257            policies
1258                .internal_table_policies
1259                .into_iter()
1260                .map(|policy| (policy.table_id, policy.policy))
1261                .collect::<HashMap<_, _>>(),
1262            HashMap::from([(
1263                internal_table_id.as_raw_id(),
1264                CacheRefillPolicy::Both.to_protobuf() as i32,
1265            )])
1266        );
1267
1268        Ok(())
1269    }
1270
1271    #[tokio::test]
1272    async fn test_prepare_streaming_job_cache_refill_policy_notifies_hummock() -> MetaResult<()> {
1273        let env = MetaSrvEnv::for_test().await;
1274        let (tx, mut rx) = mpsc::unbounded_channel();
1275        env.notification_manager().insert_sender(
1276            SubscribeType::Hummock,
1277            WorkerKey(HostAddress {
1278                host: "localhost".to_owned(),
1279                port: 1234,
1280            }),
1281            tx,
1282        );
1283        let (local_notification_tx, mut local_notification_rx) = mpsc::unbounded_channel();
1284        env.notification_manager()
1285            .insert_local_sender(local_notification_tx);
1286        let mgr = CatalogController::new(env).await?;
1287
1288        let inner = mgr.inner.write().await;
1289        let txn = inner.db.begin().await?;
1290        let (job_id, Some(result_table_id), internal_table_id) = insert_test_streaming_job(
1291            &txn,
1292            "mv_initial_cache_refill",
1293            true,
1294            Some(CacheRefillPolicy::Both),
1295        )
1296        .await?
1297        else {
1298            unreachable!()
1299        };
1300        let (unprepared_job_id, Some(unprepared_result_table_id), unprepared_internal_table_id) =
1301            insert_test_streaming_job(
1302                &txn,
1303                "mv_unprepared_cache_refill",
1304                true,
1305                Some(CacheRefillPolicy::Serving),
1306            )
1307            .await?
1308        else {
1309            unreachable!()
1310        };
1311        for job_id in [job_id, unprepared_job_id] {
1312            streaming_job::ActiveModel {
1313                job_id: Set(job_id),
1314                job_status: Set(JobStatus::Initial),
1315                ..Default::default()
1316            }
1317            .update(&txn)
1318            .await?;
1319        }
1320        txn.commit().await?;
1321        drop(inner);
1322
1323        let fragments = [Fragment {
1324            fragment_id: FragmentId::new(300),
1325            fragment_type_mask: FragmentTypeMask::default(),
1326            distribution_type: PbFragmentDistributionType::Hash,
1327            state_table_ids: vec![],
1328            maybe_vnode_count: Some(1),
1329            nodes: PbStreamNode::default(),
1330        }];
1331        mgr.prepare_streaming_job(
1332            job_id,
1333            || fragments.iter(),
1334            &FragmentDownstreamRelation::default(),
1335            true,
1336            None,
1337            None,
1338        )
1339        .await?;
1340
1341        let local_notification = local_notification_rx
1342            .try_recv()
1343            .expect("should receive serving fragment mapping notification");
1344        let LocalNotification::ServingFragmentMappingsUpsert(fragment_ids) = local_notification
1345        else {
1346            panic!(
1347                "unexpected local notification before hummock notification: {:?}",
1348                local_notification
1349            );
1350        };
1351        assert_eq!(fragment_ids, vec![FragmentId::new(300).as_raw_id()]);
1352
1353        let response = rx
1354            .recv()
1355            .await
1356            .expect("should receive hummock notification")
1357            .into_notification()
1358            .expect("notification should be ok");
1359        assert_eq!(response.operation(), NotificationOperation::Update);
1360        let info = response.info;
1361        let Some(NotificationInfo::TableRefillRuntimeConfig(config)) = info else {
1362            panic!("unexpected notification: {:?}", info);
1363        };
1364        assert!(config.serving_table_vnode_mappings.is_none());
1365        let policies = config
1366            .table_cache_refill_policies
1367            .expect("policy snapshot should be present");
1368        let table_policies = policies
1369            .table_policies
1370            .into_iter()
1371            .map(|policy| (policy.table_id, policy.policy))
1372            .collect::<HashMap<_, _>>();
1373        assert_eq!(
1374            table_policies,
1375            HashMap::from([(
1376                result_table_id.as_raw_id(),
1377                CacheRefillPolicy::Both.to_protobuf() as i32,
1378            )])
1379        );
1380        assert!(!table_policies.contains_key(&unprepared_result_table_id.as_raw_id()));
1381        let internal_table_policies = policies
1382            .internal_table_policies
1383            .into_iter()
1384            .map(|policy| (policy.table_id, policy.policy))
1385            .collect::<HashMap<_, _>>();
1386        assert_eq!(
1387            internal_table_policies,
1388            HashMap::from([(
1389                internal_table_id.as_raw_id(),
1390                CacheRefillPolicy::Both.to_protobuf() as i32,
1391            )])
1392        );
1393        assert!(!internal_table_policies.contains_key(&unprepared_internal_table_id.as_raw_id()));
1394
1395        Ok(())
1396    }
1397
1398    async fn insert_dirty_creating_job_with_fragment(
1399        mgr: &CatalogController,
1400        fragment_id: FragmentId,
1401        vnode_count: i32,
1402        fragment_type_mask: FragmentTypeMask,
1403    ) -> MetaResult<(JobId, TableId)> {
1404        let inner = mgr.inner.write().await;
1405        let txn = inner.db.begin().await?;
1406        let job_obj = CatalogController::create_object(
1407            &txn,
1408            ObjectType::Table,
1409            TEST_OWNER_ID,
1410            Some(TEST_SCHEMA_ID.as_object_id()),
1411        )
1412        .await?;
1413        let job_id = job_obj.oid.as_job_id();
1414        let table_id = job_id.as_mv_table_id();
1415        insert_test_table(
1416            &txn,
1417            table_id,
1418            "mv_dirty_serving_mapping",
1419            TableType::MaterializedView,
1420            None,
1421            "CREATE MATERIALIZED VIEW mv_dirty_serving_mapping AS SELECT 1",
1422        )
1423        .await?;
1424        table::ActiveModel {
1425            table_id: Set(table_id),
1426            engine: Set(Some(table::Engine::Hummock)),
1427            ..Default::default()
1428        }
1429        .update(&txn)
1430        .await?;
1431        streaming_job::ActiveModel {
1432            job_id: Set(job_id),
1433            job_status: Set(JobStatus::Creating),
1434            create_type: Set(CreateType::Foreground),
1435            timezone: Set(None),
1436            config_override: Set(None),
1437            adaptive_parallelism_strategy: Set(None),
1438            parallelism: Set(StreamingParallelism::Adaptive),
1439            backfill_parallelism: Set(None),
1440            backfill_adaptive_parallelism_strategy: Set(None),
1441            backfill_orders: Set(None),
1442            max_parallelism: Set(1),
1443            specific_resource_group: Set(None),
1444            is_serverless_backfill: Set(false),
1445            refresh_interval_sec: Set(None),
1446        }
1447        .insert(&txn)
1448        .await?;
1449        fragment::ActiveModel {
1450            fragment_id: Set(fragment_id),
1451            job_id: Set(job_id),
1452            fragment_type_mask: Set(fragment_type_mask.into()),
1453            distribution_type: Set(DistributionType::Hash),
1454            stream_node: Set(StreamNode::default()),
1455            state_table_ids: Set(Vec::<TableId>::new().into()),
1456            upstream_fragment_id: Set(Vec::<i32>::new().into()),
1457            vnode_count: Set(vnode_count),
1458            parallelism: Set(None),
1459        }
1460        .insert(&txn)
1461        .await?;
1462        txn.commit().await?;
1463        drop(inner);
1464
1465        Ok((job_id, table_id))
1466    }
1467
1468    #[tokio::test]
1469    async fn test_dirty_cleanup_reconcile_removes_stale_serving_vnode_mapping() -> MetaResult<()> {
1470        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1471        let fragment_id = FragmentId::new(42);
1472        insert_dirty_creating_job_with_fragment(
1473            &mgr,
1474            fragment_id,
1475            VirtualNode::COUNT_FOR_TEST as i32,
1476            FragmentTypeMask::from(FragmentTypeFlag::Values as u32),
1477        )
1478        .await?;
1479
1480        let worker = WorkerNode {
1481            id: WorkerId::new(1),
1482            r#type: WorkerType::ComputeNode.into(),
1483            host: Some(HostAddress {
1484                host: "localhost".to_owned(),
1485                port: 1,
1486            }),
1487            state: worker_node::State::Running as i32,
1488            property: Some(worker_node::Property {
1489                is_serving: true,
1490                parallelism: 1,
1491                ..Default::default()
1492            }),
1493            ..Default::default()
1494        };
1495        let serving_vnode_mapping = ServingVnodeMapping::default();
1496        let initial_snapshot = mgr.fragment_serving_infos().await?;
1497        serving_vnode_mapping.upsert(&initial_snapshot, std::slice::from_ref(&worker), None);
1498        assert!(serving_vnode_mapping.all().contains_key(&fragment_id));
1499
1500        mgr.clean_dirty_creating_jobs(Some(TEST_DATABASE_ID))
1501            .await?;
1502        let current_snapshot = mgr.fragment_serving_infos().await?;
1503        assert!(!current_snapshot.contains_key(&fragment_id));
1504
1505        serving_vnode_mapping.reconcile(&current_snapshot, &[worker], None);
1506        assert!(!serving_vnode_mapping.all().contains_key(&fragment_id));
1507
1508        Ok(())
1509    }
1510
1511    #[tokio::test]
1512    async fn test_clean_dirty_creating_jobs_keeps_job_without_values_fragment() -> MetaResult<()> {
1513        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1514        let fragment_id = FragmentId::new(43);
1515        let (job_id, table_id) = insert_dirty_creating_job_with_fragment(
1516            &mgr,
1517            fragment_id,
1518            1,
1519            FragmentTypeMask::empty(),
1520        )
1521        .await?;
1522
1523        let cleaned = mgr
1524            .clean_dirty_creating_jobs(Some(TEST_DATABASE_ID))
1525            .await?;
1526        assert!(cleaned.streaming_job_ids.is_empty());
1527
1528        let inner = mgr.inner.read().await;
1529        assert!(Object::find_by_id(job_id).one(&inner.db).await?.is_some());
1530        assert!(
1531            StreamingJob::find_by_id(job_id)
1532                .one(&inner.db)
1533                .await?
1534                .is_some()
1535        );
1536        assert!(Table::find_by_id(table_id).one(&inner.db).await?.is_some());
1537
1538        Ok(())
1539    }
1540
1541    #[tokio::test]
1542    async fn test_clean_dirty_creating_jobs_cleans_foreground_job_in_legacy_mode() -> MetaResult<()>
1543    {
1544        let mut opts = MetaOpts::test(false);
1545        opts.clean_all_foreground_jobs_on_recovery = true;
1546        let mgr = CatalogController::new(MetaSrvEnv::for_test_opts(opts, |_| ()).await).await?;
1547        let (job_id, table_id) = insert_dirty_creating_job_with_fragment(
1548            &mgr,
1549            FragmentId::new(44),
1550            1,
1551            FragmentTypeMask::empty(),
1552        )
1553        .await?;
1554
1555        let cleaned = mgr
1556            .clean_dirty_creating_jobs(Some(TEST_DATABASE_ID))
1557            .await?;
1558        assert_eq!(cleaned.streaming_job_ids, vec![job_id]);
1559
1560        let db = &mgr.inner.read().await.db;
1561        assert!(Object::find_by_id(job_id).one(db).await?.is_none());
1562        assert!(StreamingJob::find_by_id(job_id).one(db).await?.is_none());
1563        assert!(Table::find_by_id(table_id).one(db).await?.is_none());
1564
1565        Ok(())
1566    }
1567
1568    #[tokio::test]
1569    async fn test_database_func() -> MetaResult<()> {
1570        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1571        let pb_database = PbDatabase {
1572            name: "db1".to_owned(),
1573            owner: TEST_OWNER_ID as _,
1574            ..Default::default()
1575        };
1576        mgr.create_database(pb_database).await?;
1577
1578        let database_id: DatabaseId = Database::find()
1579            .select_only()
1580            .column(database::Column::DatabaseId)
1581            .filter(database::Column::Name.eq("db1"))
1582            .into_tuple()
1583            .one(&mgr.inner.read().await.db)
1584            .await?
1585            .unwrap();
1586
1587        mgr.alter_name(ObjectType::Database, database_id, "db2")
1588            .await?;
1589        let database = Database::find_by_id(database_id)
1590            .one(&mgr.inner.read().await.db)
1591            .await?
1592            .unwrap();
1593        assert_eq!(database.name, "db2");
1594
1595        let schema_id: SchemaId = Schema::find()
1596            .inner_join(Object)
1597            .select_only()
1598            .column(schema::Column::SchemaId)
1599            .filter(object::Column::DatabaseId.eq(database_id))
1600            .into_tuple()
1601            .one(&mgr.inner.read().await.db)
1602            .await?
1603            .unwrap();
1604        mgr.create_view(
1605            PbView {
1606                schema_id,
1607                database_id,
1608                name: "cross_db_upstream".to_owned(),
1609                owner: TEST_OWNER_ID as _,
1610                sql: "CREATE VIEW cross_db_upstream AS SELECT 1".to_owned(),
1611                ..Default::default()
1612            },
1613            HashSet::new(),
1614        )
1615        .await?;
1616        let upstream_id: ViewId = View::find()
1617            .inner_join(Object)
1618            .select_only()
1619            .column(view::Column::ViewId)
1620            .filter(
1621                object::Column::DatabaseId
1622                    .eq(database_id)
1623                    .and(view::Column::Name.eq("cross_db_upstream")),
1624            )
1625            .into_tuple()
1626            .one(&mgr.inner.read().await.db)
1627            .await?
1628            .unwrap();
1629
1630        let inner = mgr.inner.write().await;
1631        let txn = inner.db.begin().await?;
1632        let (dependent_job_id, Some(dependent_table_id), _) =
1633            insert_test_streaming_job(&txn, "cross_db_dependent", true, None).await?
1634        else {
1635            unreachable!()
1636        };
1637        ObjectDependency::insert(object_dependency::ActiveModel {
1638            oid: Set(upstream_id.as_object_id()),
1639            used_by: Set(dependent_job_id.as_object_id()),
1640            ..Default::default()
1641        })
1642        .exec(&txn)
1643        .await?;
1644        txn.commit().await?;
1645        drop(inner);
1646
1647        assert!(
1648            mgr.drop_object(ObjectType::Database, database_id, DropMode::Cascade)
1649                .await
1650                .is_err()
1651        );
1652        mgr.drop_object(ObjectType::Table, dependent_table_id, DropMode::Cascade)
1653            .await?;
1654        mgr.drop_object(ObjectType::Database, database_id, DropMode::Cascade)
1655            .await?;
1656
1657        Ok(())
1658    }
1659
1660    #[tokio::test]
1661    async fn test_schema_func() -> MetaResult<()> {
1662        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1663        let pb_schema = PbSchema {
1664            database_id: TEST_DATABASE_ID,
1665            name: "schema1".to_owned(),
1666            owner: TEST_OWNER_ID as _,
1667            ..Default::default()
1668        };
1669        mgr.create_schema(pb_schema.clone()).await?;
1670        assert!(mgr.create_schema(pb_schema).await.is_err());
1671
1672        let schema_id: SchemaId = Schema::find()
1673            .select_only()
1674            .column(schema::Column::SchemaId)
1675            .filter(schema::Column::Name.eq("schema1"))
1676            .into_tuple()
1677            .one(&mgr.inner.read().await.db)
1678            .await?
1679            .unwrap();
1680
1681        mgr.alter_name(ObjectType::Schema, schema_id, "schema2")
1682            .await?;
1683        let schema = Schema::find_by_id(schema_id)
1684            .one(&mgr.inner.read().await.db)
1685            .await?
1686            .unwrap();
1687        assert_eq!(schema.name, "schema2");
1688        mgr.drop_object(ObjectType::Schema, schema_id, DropMode::Restrict)
1689            .await?;
1690
1691        Ok(())
1692    }
1693
1694    #[tokio::test]
1695    async fn test_create_view() -> MetaResult<()> {
1696        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1697        let pb_view = PbView {
1698            schema_id: TEST_SCHEMA_ID,
1699            database_id: TEST_DATABASE_ID,
1700            name: "view".to_owned(),
1701            owner: TEST_OWNER_ID as _,
1702            sql: "CREATE VIEW view AS SELECT 1".to_owned(),
1703            ..Default::default()
1704        };
1705        mgr.create_view(pb_view.clone(), HashSet::new()).await?;
1706        assert!(mgr.create_view(pb_view, HashSet::new()).await.is_err());
1707
1708        let view = View::find().one(&mgr.inner.read().await.db).await?.unwrap();
1709        mgr.drop_object(ObjectType::View, view.view_id, DropMode::Cascade)
1710            .await?;
1711        assert!(
1712            View::find_by_id(view.view_id)
1713                .one(&mgr.inner.read().await.db)
1714                .await?
1715                .is_none()
1716        );
1717
1718        Ok(())
1719    }
1720
1721    #[tokio::test]
1722    async fn test_object_belong_to_cascade() -> MetaResult<()> {
1723        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1724        mgr.create_schema(PbSchema {
1725            database_id: TEST_DATABASE_ID,
1726            name: "belong_to_target".to_owned(),
1727            owner: TEST_OWNER_ID as _,
1728            ..Default::default()
1729        })
1730        .await?;
1731        let target_schema_id: SchemaId = Schema::find()
1732            .select_only()
1733            .column(schema::Column::SchemaId)
1734            .filter(schema::Column::Name.eq("belong_to_target"))
1735            .into_tuple()
1736            .one(&mgr.inner.read().await.db)
1737            .await?
1738            .unwrap();
1739        let txn = mgr.inner.read().await.db.begin().await?;
1740
1741        let mv_obj = CatalogController::create_object(
1742            &txn,
1743            ObjectType::Table,
1744            TEST_OWNER_ID,
1745            Some(TEST_SCHEMA_ID.as_object_id()),
1746        )
1747        .await?;
1748        assert_eq!(mv_obj.belong_to_oid, Some(TEST_SCHEMA_ID.as_object_id()));
1749        assert_eq!(mv_obj.database_id, Some(TEST_DATABASE_ID));
1750        assert_eq!(mv_obj.schema_id, Some(TEST_SCHEMA_ID));
1751        let job_id = mv_obj.oid.as_job_id();
1752        let mv_table_id = job_id.as_mv_table_id();
1753        insert_test_table(
1754            &txn,
1755            mv_table_id,
1756            "mv_belong_to",
1757            TableType::MaterializedView,
1758            None,
1759            "CREATE MATERIALIZED VIEW mv_belong_to AS SELECT 1",
1760        )
1761        .await?;
1762
1763        let internal_obj = CatalogController::create_object(
1764            &txn,
1765            ObjectType::Table,
1766            TEST_OWNER_ID,
1767            Some(job_id.as_object_id()),
1768        )
1769        .await?;
1770        assert_eq!(internal_obj.belong_to_oid, Some(job_id.as_object_id()));
1771        assert_eq!(internal_obj.database_id, Some(TEST_DATABASE_ID));
1772        assert_eq!(internal_obj.schema_id, Some(TEST_SCHEMA_ID));
1773        let internal_table_id = internal_obj.oid.as_table_id();
1774        insert_test_table(
1775            &txn,
1776            internal_table_id,
1777            "__internal_mv_belong_to",
1778            TableType::Internal,
1779            Some(job_id),
1780            "",
1781        )
1782        .await?;
1783        let nested_obj = CatalogController::create_object(
1784            &txn,
1785            ObjectType::Table,
1786            TEST_OWNER_ID,
1787            Some(internal_table_id.as_object_id()),
1788        )
1789        .await?;
1790        txn.commit().await?;
1791
1792        assert!(
1793            mgr.alter_schema(ObjectType::Sink, job_id.as_object_id(), target_schema_id,)
1794                .await
1795                .is_err()
1796        );
1797        mgr.alter_schema(ObjectType::Table, job_id.as_object_id(), target_schema_id)
1798            .await?;
1799
1800        let db = &mgr.inner.read().await.db;
1801        let belonging_object_ids = get_belong_objects(db, job_id.as_object_id())
1802            .await?
1803            .into_iter()
1804            .map(|object| object.oid)
1805            .collect::<HashSet<_>>();
1806        assert_eq!(
1807            belonging_object_ids,
1808            HashSet::from([internal_table_id.as_object_id(), nested_obj.oid])
1809        );
1810        let moved_objects = Object::find()
1811            .filter(object::Column::Oid.is_in([
1812                job_id.as_object_id(),
1813                internal_table_id.as_object_id(),
1814                nested_obj.oid,
1815            ]))
1816            .all(db)
1817            .await?;
1818        assert!(
1819            moved_objects
1820                .iter()
1821                .all(|object| object.schema_id == Some(target_schema_id))
1822        );
1823        assert_eq!(
1824            Object::find_by_id(internal_table_id)
1825                .one(db)
1826                .await?
1827                .unwrap()
1828                .belong_to_oid,
1829            Some(job_id.as_object_id())
1830        );
1831        assert_eq!(
1832            Object::find_by_id(nested_obj.oid)
1833                .one(db)
1834                .await?
1835                .unwrap()
1836                .belong_to_oid,
1837            Some(internal_table_id.as_object_id())
1838        );
1839
1840        Object::delete_by_id(job_id).exec(db).await?;
1841
1842        assert!(Object::find_by_id(job_id).one(db).await?.is_none());
1843        assert!(
1844            Object::find_by_id(internal_table_id)
1845                .one(db)
1846                .await?
1847                .is_none()
1848        );
1849        assert!(Table::find_by_id(mv_table_id).one(db).await?.is_none());
1850        assert!(
1851            Table::find_by_id(internal_table_id)
1852                .one(db)
1853                .await?
1854                .is_none()
1855        );
1856        assert!(Object::find_by_id(nested_obj.oid).one(db).await?.is_none());
1857
1858        Ok(())
1859    }
1860
1861    #[tokio::test]
1862    async fn test_alter_internal_table_schema_rejected() -> MetaResult<()> {
1863        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1864        mgr.create_schema(PbSchema {
1865            database_id: TEST_DATABASE_ID,
1866            name: "internal_table_alter_target".to_owned(),
1867            owner: TEST_OWNER_ID as _,
1868            ..Default::default()
1869        })
1870        .await?;
1871        let target_schema_id: SchemaId = Schema::find()
1872            .select_only()
1873            .column(schema::Column::SchemaId)
1874            .filter(schema::Column::Name.eq("internal_table_alter_target"))
1875            .into_tuple()
1876            .one(&mgr.inner.read().await.db)
1877            .await?
1878            .unwrap();
1879
1880        let txn = mgr.inner.read().await.db.begin().await?;
1881        let parent_obj = CatalogController::create_object(
1882            &txn,
1883            ObjectType::Table,
1884            TEST_OWNER_ID,
1885            Some(TEST_SCHEMA_ID.as_object_id()),
1886        )
1887        .await?;
1888        let parent_job_id = parent_obj.oid.as_job_id();
1889        insert_test_table(
1890            &txn,
1891            parent_job_id.as_mv_table_id(),
1892            "internal_table_parent",
1893            TableType::MaterializedView,
1894            None,
1895            "",
1896        )
1897        .await?;
1898        let internal_obj = CatalogController::create_object(
1899            &txn,
1900            ObjectType::Table,
1901            TEST_OWNER_ID,
1902            Some(parent_job_id.as_object_id()),
1903        )
1904        .await?;
1905        let internal_table_id = internal_obj.oid.as_table_id();
1906        insert_test_table(
1907            &txn,
1908            internal_table_id,
1909            "__internal_table_alter_target",
1910            TableType::Internal,
1911            Some(parent_job_id),
1912            "",
1913        )
1914        .await?;
1915        txn.commit().await?;
1916
1917        for new_schema in [TEST_SCHEMA_ID, target_schema_id] {
1918            assert!(
1919                mgr.alter_schema(
1920                    ObjectType::Table,
1921                    internal_table_id.as_object_id(),
1922                    new_schema,
1923                )
1924                .await
1925                .is_err()
1926            );
1927        }
1928
1929        let internal_obj = Object::find_by_id(internal_table_id)
1930            .one(&mgr.inner.read().await.db)
1931            .await?
1932            .unwrap();
1933        assert_eq!(internal_obj.schema_id, Some(TEST_SCHEMA_ID));
1934        assert_eq!(
1935            internal_obj.belong_to_oid,
1936            Some(parent_job_id.as_object_id())
1937        );
1938
1939        Ok(())
1940    }
1941
1942    #[tokio::test]
1943    async fn test_alter_table_schema_moves_indexes_but_not_subscriptions() -> MetaResult<()> {
1944        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
1945        mgr.create_schema(PbSchema {
1946            database_id: TEST_DATABASE_ID,
1947            name: "alter_table_target".to_owned(),
1948            owner: TEST_OWNER_ID as _,
1949            ..Default::default()
1950        })
1951        .await?;
1952        let target_schema_id: SchemaId = Schema::find()
1953            .select_only()
1954            .column(schema::Column::SchemaId)
1955            .filter(schema::Column::Name.eq("alter_table_target"))
1956            .into_tuple()
1957            .one(&mgr.inner.read().await.db)
1958            .await?
1959            .unwrap();
1960
1961        let txn = mgr.inner.read().await.db.begin().await?;
1962        let table_obj = CatalogController::create_object(
1963            &txn,
1964            ObjectType::Table,
1965            TEST_OWNER_ID,
1966            Some(TEST_SCHEMA_ID.as_object_id()),
1967        )
1968        .await?;
1969        let table_id = table_obj.oid.as_table_id();
1970        insert_test_table(
1971            &txn,
1972            table_id,
1973            "mv_with_index_and_subscription",
1974            TableType::MaterializedView,
1975            None,
1976            "CREATE MATERIALIZED VIEW mv_with_index_and_subscription AS SELECT 1",
1977        )
1978        .await?;
1979
1980        let index_obj = CatalogController::create_object(
1981            &txn,
1982            ObjectType::Index,
1983            TEST_OWNER_ID,
1984            Some(TEST_SCHEMA_ID.as_object_id()),
1985        )
1986        .await?;
1987        let index_id = index_obj.oid.as_index_id();
1988        let index_table_id = index_id.as_object_id().as_table_id();
1989        insert_test_table(
1990            &txn,
1991            index_table_id,
1992            "idx_mv_with_index_and_subscription_table",
1993            TableType::Index,
1994            None,
1995            "",
1996        )
1997        .await?;
1998        index::ActiveModel {
1999            index_id: Set(index_id),
2000            name: Set("idx_mv_with_index_and_subscription".to_owned()),
2001            index_table_id: Set(index_table_id),
2002            primary_table_id: Set(table_id),
2003            index_items: Set(Vec::<risingwave_pb::expr::ExprNode>::new().into()),
2004            index_column_properties: Set(None),
2005            index_columns_len: Set(0),
2006        }
2007        .insert(&txn)
2008        .await?;
2009
2010        let index_internal_obj = CatalogController::create_object(
2011            &txn,
2012            ObjectType::Table,
2013            TEST_OWNER_ID,
2014            Some(index_id.as_object_id()),
2015        )
2016        .await?;
2017        let index_internal_table_id = index_internal_obj.oid.as_table_id();
2018        insert_test_table(
2019            &txn,
2020            index_internal_table_id,
2021            "__internal_idx_mv_with_index_and_subscription",
2022            TableType::Internal,
2023            Some(index_id.as_job_id()),
2024            "",
2025        )
2026        .await?;
2027        txn.commit().await?;
2028
2029        let mut subscription = PbSubscription {
2030            name: "subscription_in_original_schema".to_owned(),
2031            definition: "CREATE SUBSCRIPTION subscription_in_original_schema FROM mv_with_index_and_subscription".to_owned(),
2032            retention_seconds: Some(86400),
2033            database_id: TEST_DATABASE_ID,
2034            schema_id: TEST_SCHEMA_ID,
2035            dependent_table_id: table_id,
2036            owner: TEST_OWNER_ID as _,
2037            subscription_state: SubscriptionState::Created as _,
2038            ..Default::default()
2039        };
2040        mgr.create_subscription_catalog(&mut subscription).await?;
2041
2042        {
2043            let inner = mgr.inner.read().await;
2044            assert_eq!(
2045                Object::find_by_id(index_id)
2046                    .one(&inner.db)
2047                    .await?
2048                    .unwrap()
2049                    .belong_to_oid,
2050                Some(TEST_SCHEMA_ID.as_object_id())
2051            );
2052            assert_eq!(
2053                Object::find_by_id(subscription.id)
2054                    .one(&inner.db)
2055                    .await?
2056                    .unwrap()
2057                    .belong_to_oid,
2058                Some(TEST_SCHEMA_ID.as_object_id())
2059            );
2060        }
2061
2062        mgr.alter_schema(ObjectType::Table, table_id.as_object_id(), target_schema_id)
2063            .await?;
2064
2065        let db = &mgr.inner.read().await.db;
2066        for object_id in [table_id.as_object_id(), index_id.as_object_id()] {
2067            let object = Object::find_by_id(object_id).one(db).await?.unwrap();
2068            assert_eq!(object.schema_id, Some(target_schema_id));
2069            assert_eq!(object.belong_to_oid, Some(target_schema_id.as_object_id()));
2070        }
2071        let index_internal_object = Object::find_by_id(index_internal_table_id)
2072            .one(db)
2073            .await?
2074            .unwrap();
2075        assert_eq!(index_internal_object.schema_id, Some(target_schema_id));
2076        assert_eq!(
2077            index_internal_object.belong_to_oid,
2078            Some(index_id.as_object_id())
2079        );
2080
2081        let subscription_object = Object::find_by_id(subscription.id).one(db).await?.unwrap();
2082        assert_eq!(subscription_object.schema_id, Some(TEST_SCHEMA_ID));
2083        assert_eq!(
2084            subscription_object.belong_to_oid,
2085            Some(TEST_SCHEMA_ID.as_object_id())
2086        );
2087
2088        Ok(())
2089    }
2090
2091    #[tokio::test]
2092    async fn test_create_function() -> MetaResult<()> {
2093        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2094        let test_data_type = risingwave_pb::data::DataType {
2095            type_name: risingwave_pb::data::data_type::TypeName::Int32 as _,
2096            ..Default::default()
2097        };
2098        let arg_types = vec![test_data_type.clone()];
2099        let pb_function = PbFunction {
2100            schema_id: TEST_SCHEMA_ID,
2101            database_id: TEST_DATABASE_ID,
2102            name: "test_function".to_owned(),
2103            owner: TEST_OWNER_ID as _,
2104            arg_types,
2105            return_type: Some(test_data_type.clone()),
2106            language: "python".to_owned(),
2107            always_retry_on_network_error: true,
2108            unsafe_skip_materializing_exprs: true,
2109            is_immutable: true,
2110            kind: Some(risingwave_pb::catalog::function::Kind::Scalar(
2111                Default::default(),
2112            )),
2113            ..Default::default()
2114        };
2115        mgr.create_function(pb_function.clone()).await?;
2116        assert!(mgr.create_function(pb_function).await.is_err());
2117
2118        let function = Function::find()
2119            .inner_join(Object)
2120            .filter(
2121                object::Column::DatabaseId
2122                    .eq(TEST_DATABASE_ID)
2123                    .and(object::Column::SchemaId.eq(TEST_SCHEMA_ID))
2124                    .add(function::Column::Name.eq("test_function")),
2125            )
2126            .one(&mgr.inner.read().await.db)
2127            .await?
2128            .unwrap();
2129        assert_eq!(function.return_type.to_protobuf(), test_data_type);
2130        assert_eq!(function.arg_types.to_protobuf().len(), 1);
2131        assert_eq!(function.language, "python");
2132        assert!(function.always_retry_on_network_error);
2133        assert!(function.unsafe_skip_materializing_exprs);
2134        assert!(function.is_immutable);
2135
2136        mgr.create_schema(PbSchema {
2137            database_id: TEST_DATABASE_ID,
2138            name: "function_target".to_owned(),
2139            owner: TEST_OWNER_ID as _,
2140            ..Default::default()
2141        })
2142        .await?;
2143        let target_schema_id: SchemaId = Schema::find()
2144            .select_only()
2145            .column(schema::Column::SchemaId)
2146            .filter(schema::Column::Name.eq("function_target"))
2147            .into_tuple()
2148            .one(&mgr.inner.read().await.db)
2149            .await?
2150            .unwrap();
2151        mgr.alter_schema(
2152            ObjectType::Function,
2153            function.function_id.as_object_id(),
2154            target_schema_id,
2155        )
2156        .await?;
2157        assert_eq!(
2158            Object::find_by_id(function.function_id)
2159                .one(&mgr.inner.read().await.db)
2160                .await?
2161                .unwrap()
2162                .schema_id,
2163            Some(target_schema_id)
2164        );
2165
2166        mgr.drop_object(
2167            ObjectType::Function,
2168            function.function_id,
2169            DropMode::Restrict,
2170        )
2171        .await?;
2172        assert!(
2173            Object::find_by_id(function.function_id)
2174                .one(&mgr.inner.read().await.db)
2175                .await?
2176                .is_none()
2177        );
2178
2179        Ok(())
2180    }
2181
2182    #[tokio::test]
2183    async fn test_create_cdc_table_source_dependency() -> MetaResult<()> {
2184        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2185        let (shared_source_id, _) = mgr
2186            .create_source(
2187                PbSource {
2188                    schema_id: TEST_SCHEMA_ID,
2189                    database_id: TEST_DATABASE_ID,
2190                    name: "shared_cdc".to_owned(),
2191                    owner: TEST_OWNER_ID,
2192                    info: Some(StreamSourceInfo {
2193                        cdc_source_job: true,
2194                        ..Default::default()
2195                    }),
2196                    ..Default::default()
2197                },
2198                None,
2199            )
2200            .await?;
2201
2202        let (table_source_id, _) = mgr
2203            .create_source(
2204                PbSource {
2205                    schema_id: TEST_SCHEMA_ID,
2206                    database_id: TEST_DATABASE_ID,
2207                    name: "orders_cdc".to_owned(),
2208                    owner: TEST_OWNER_ID,
2209                    info: Some(StreamSourceInfo {
2210                        external_table: Some(ExternalTableDesc {
2211                            source_id: shared_source_id,
2212                            table_name: "mydb.orders".to_owned(),
2213                            connect_properties: BTreeMap::from([(
2214                                "hostname".to_owned(),
2215                                "mysql-host".to_owned(),
2216                            )]),
2217                            ..Default::default()
2218                        }),
2219                        ..Default::default()
2220                    }),
2221                    ..Default::default()
2222                },
2223                None,
2224            )
2225            .await?;
2226
2227        let table_source = Source::find_by_id(table_source_id)
2228            .one(&mgr.inner.read().await.db)
2229            .await?
2230            .unwrap();
2231        let external_table = table_source
2232            .source_info
2233            .unwrap()
2234            .to_protobuf()
2235            .external_table
2236            .unwrap();
2237        assert_eq!(external_table.source_id, shared_source_id);
2238        assert_eq!(external_table.table_id, table_source_id.as_cdc_table_id());
2239        // Connect properties are only used to validate the descriptor, never persisted.
2240        assert!(external_table.connect_properties.is_empty());
2241        assert!(external_table.secret_refs.is_empty());
2242
2243        let dependency_count = ObjectDependency::find()
2244            .filter(object_dependency::Column::Oid.eq(shared_source_id.as_object_id()))
2245            .filter(object_dependency::Column::UsedBy.eq(table_source_id.as_object_id()))
2246            .count(&mgr.inner.read().await.db)
2247            .await?;
2248        assert_eq!(dependency_count, 1);
2249
2250        Ok(())
2251    }
2252
2253    #[tokio::test]
2254    async fn test_alter_relation_rename() -> MetaResult<()> {
2255        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2256        let pb_source = PbSource {
2257            schema_id: TEST_SCHEMA_ID,
2258            database_id: TEST_DATABASE_ID,
2259            name: "s1".to_owned(),
2260            owner: TEST_OWNER_ID as _,
2261            definition: r#"CREATE SOURCE s1 (v1 int) with (
2262  connector = 'kafka',
2263  topic = 'kafka_alter',
2264  properties.bootstrap.server = 'message_queue:29092',
2265  scan.startup.mode = 'earliest'
2266) FORMAT PLAIN ENCODE JSON"#
2267                .to_owned(),
2268            info: Some(StreamSourceInfo {
2269                ..Default::default()
2270            }),
2271            ..Default::default()
2272        };
2273        mgr.create_source(pb_source, None).await?;
2274        let source_id: SourceId = Source::find()
2275            .select_only()
2276            .column(source::Column::SourceId)
2277            .filter(source::Column::Name.eq("s1"))
2278            .into_tuple()
2279            .one(&mgr.inner.read().await.db)
2280            .await?
2281            .unwrap();
2282
2283        let pb_view = PbView {
2284            schema_id: TEST_SCHEMA_ID,
2285            database_id: TEST_DATABASE_ID,
2286            name: "view_1".to_owned(),
2287            owner: TEST_OWNER_ID as _,
2288            sql: "CREATE VIEW view_1 AS SELECT v1 FROM s1".to_owned(),
2289            ..Default::default()
2290        };
2291        mgr.create_view(pb_view, HashSet::from([source_id.as_object_id()]))
2292            .await?;
2293        let view_id: ViewId = View::find()
2294            .select_only()
2295            .column(view::Column::ViewId)
2296            .filter(view::Column::Name.eq("view_1"))
2297            .into_tuple()
2298            .one(&mgr.inner.read().await.db)
2299            .await?
2300            .unwrap();
2301
2302        mgr.alter_name(ObjectType::Source, source_id, "s2").await?;
2303        let source = Source::find_by_id(source_id)
2304            .one(&mgr.inner.read().await.db)
2305            .await?
2306            .unwrap();
2307        assert_eq!(source.name, "s2");
2308        assert_eq!(
2309            source.definition,
2310            "CREATE SOURCE s2 (v1 INT) WITH (\
2311  connector = 'kafka', \
2312  topic = 'kafka_alter', \
2313  properties.bootstrap.server = 'message_queue:29092', \
2314  scan.startup.mode = 'earliest'\
2315) FORMAT PLAIN ENCODE JSON"
2316        );
2317
2318        let view = View::find_by_id(view_id)
2319            .one(&mgr.inner.read().await.db)
2320            .await?
2321            .unwrap();
2322        assert_eq!(
2323            view.definition,
2324            "CREATE VIEW view_1 AS SELECT v1 FROM s2 AS s1"
2325        );
2326
2327        mgr.drop_object(ObjectType::Source, source_id, DropMode::Cascade)
2328            .await?;
2329        assert!(
2330            View::find_by_id(view_id)
2331                .one(&mgr.inner.read().await.db)
2332                .await?
2333                .is_none()
2334        );
2335
2336        Ok(())
2337    }
2338
2339    #[tokio::test]
2340    async fn test_drop_object_rejects_source_without_its_table() -> MetaResult<()> {
2341        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2342        let mut job = crate::manager::StreamingJob::Table(
2343            Some(PbSource {
2344                name: "t".to_owned(),
2345                database_id: TEST_DATABASE_ID,
2346                schema_id: TEST_SCHEMA_ID,
2347                owner: TEST_OWNER_ID as _,
2348                info: Some(StreamSourceInfo::default()),
2349                ..Default::default()
2350            }),
2351            PbTable {
2352                name: "t".to_owned(),
2353                database_id: TEST_DATABASE_ID,
2354                schema_id: TEST_SCHEMA_ID,
2355                owner: TEST_OWNER_ID as _,
2356                table_type: PbTableType::Table as _,
2357                handle_pk_conflict_behavior:
2358                    risingwave_pb::catalog::PbHandleConflictBehavior::NoCheck as _,
2359                fragment_id: FragmentId::placeholder(),
2360                ..Default::default()
2361            },
2362            risingwave_pb::ddl_service::TableJobType::General,
2363        );
2364        mgr.create_job_catalog(
2365            &mut job,
2366            &crate::model::StreamContext::default(),
2367            &None,
2368            1,
2369            HashSet::new(),
2370            risingwave_pb::ddl_service::streaming_job_resource_type::ResourceType::Regular(true),
2371            &None,
2372            None,
2373            None,
2374            None,
2375            None,
2376        )
2377        .await?;
2378        let crate::manager::StreamingJob::Table(Some(source), _, _) = job else {
2379            unreachable!()
2380        };
2381
2382        let err = mgr
2383            .drop_object(ObjectType::Source, source.id, DropMode::Restrict)
2384            .await
2385            .unwrap_err();
2386        assert!(err.to_string().contains("use DROP TABLE"), "{err}");
2387
2388        // The source may be in another schema than its table.
2389        mgr.create_schema(PbSchema {
2390            database_id: TEST_DATABASE_ID,
2391            name: "other_schema".to_owned(),
2392            owner: TEST_OWNER_ID as _,
2393            ..Default::default()
2394        })
2395        .await?;
2396        let other_schema: SchemaId = Schema::find()
2397            .select_only()
2398            .column(schema::Column::SchemaId)
2399            .filter(schema::Column::Name.eq("other_schema"))
2400            .into_tuple()
2401            .one(&mgr.inner.read().await.db)
2402            .await?
2403            .unwrap();
2404        Object::update_many()
2405            .col_expr(object::Column::SchemaId, other_schema.into())
2406            .col_expr(
2407                object::Column::BelongToOid,
2408                other_schema.as_object_id().into(),
2409            )
2410            .filter(object::Column::Oid.eq(source.id.as_object_id()))
2411            .exec(&mgr.inner.read().await.db)
2412            .await?;
2413        let err = mgr
2414            .drop_object(ObjectType::Schema, other_schema, DropMode::Cascade)
2415            .await
2416            .unwrap_err();
2417        assert!(err.to_string().contains("use DROP TABLE"), "{err}");
2418
2419        Ok(())
2420    }
2421
2422    #[tokio::test]
2423    async fn test_cancel_creating_table_deletes_associated_source() -> MetaResult<()> {
2424        let env = MetaSrvEnv::for_test().await;
2425        let (tx, mut notification_rx) = mpsc::unbounded_channel();
2426        env.notification_manager().insert_sender(
2427            SubscribeType::Frontend,
2428            WorkerKey(HostAddress {
2429                host: "localhost".to_owned(),
2430                port: 1234,
2431            }),
2432            tx,
2433        );
2434        let mgr = CatalogController::new(env).await?;
2435
2436        let mut inner = mgr.inner.write().await;
2437        let txn = inner.db.begin().await?;
2438        let obj = CatalogController::create_object(
2439            &txn,
2440            ObjectType::Table,
2441            TEST_OWNER_ID,
2442            Some(TEST_SCHEMA_ID.as_object_id()),
2443        )
2444        .await?;
2445        let job_id = obj.oid.as_job_id();
2446        let source_obj = CatalogController::create_object(
2447            &txn,
2448            ObjectType::Source,
2449            TEST_OWNER_ID,
2450            Some(job_id.as_object_id()),
2451        )
2452        .await?;
2453        Source::insert(source::ActiveModel::from(PbSource {
2454            id: source_obj.oid.as_source_id(),
2455            schema_id: TEST_SCHEMA_ID,
2456            database_id: TEST_DATABASE_ID,
2457            name: "source_abort_initial".to_owned(),
2458            owner: TEST_OWNER_ID as _,
2459            ..Default::default()
2460        }))
2461        .exec(&txn)
2462        .await?;
2463
2464        table::ActiveModel {
2465            table_id: Set(obj.oid.as_table_id()),
2466            name: Set("table_abort_initial".to_owned()),
2467            optional_associated_source_id: Set(Some(source_obj.oid.as_source_id())),
2468            table_type: Set(TableType::Table),
2469            belongs_to_job_id: Set(None),
2470            columns: Set(vec![].into()),
2471            pk: Set(vec![].into()),
2472            distribution_key: Set(Vec::<i32>::new().into()),
2473            stream_key: Set(Vec::<i32>::new().into()),
2474            append_only: Set(false),
2475            fragment_id: Set(None),
2476            vnode_col_index: Set(None),
2477            row_id_index: Set(None),
2478            value_indices: Set(Vec::<i32>::new().into()),
2479            definition: Set("CREATE TABLE table_abort_initial (v1 INT)".to_owned()),
2480            handle_pk_conflict_behavior: Set(HandleConflictBehavior::NoCheck),
2481            version_column_indices: Set(None),
2482            read_prefix_len_hint: Set(0),
2483            watermark_indices: Set(Vec::<i32>::new().into()),
2484            dist_key_in_pk: Set(Vec::<i32>::new().into()),
2485            dml_fragment_id: Set(None),
2486            cardinality: Set(None),
2487            cleaned_by_watermark: Set(false),
2488            description: Set(None),
2489            version: Set(None),
2490            retention_seconds: Set(None),
2491            cdc_table_id: Set(None),
2492            vnode_count: Set(1),
2493            webhook_info: Set(None),
2494            engine: Set(None),
2495            clean_watermark_index_in_pk: Set(None),
2496            clean_watermark_indices: Set(None),
2497            refreshable: Set(false),
2498            vector_index_info: Set(None),
2499            cdc_table_type: Set(None),
2500        }
2501        .insert(&txn)
2502        .await?;
2503
2504        let internal_obj = CatalogController::create_object(
2505            &txn,
2506            ObjectType::Table,
2507            TEST_OWNER_ID,
2508            Some(job_id.as_object_id()),
2509        )
2510        .await?;
2511        let internal_table_id = internal_obj.oid.as_table_id();
2512        insert_test_table(
2513            &txn,
2514            internal_table_id,
2515            "__internal_mv_abort_initial",
2516            TableType::Internal,
2517            Some(job_id),
2518            "",
2519        )
2520        .await?;
2521
2522        streaming_job::ActiveModel {
2523            job_id: Set(job_id),
2524            job_status: Set(JobStatus::Creating),
2525            create_type: Set(CreateType::Foreground),
2526            timezone: Set(None),
2527            config_override: Set(None),
2528            adaptive_parallelism_strategy: Set(None),
2529            parallelism: Set(StreamingParallelism::Adaptive),
2530            backfill_parallelism: Set(None),
2531            backfill_adaptive_parallelism_strategy: Set(None),
2532            backfill_orders: Set(None),
2533            max_parallelism: Set(1),
2534            specific_resource_group: Set(None),
2535            is_serverless_backfill: Set(false),
2536            refresh_interval_sec: Set(None),
2537        }
2538        .insert(&txn)
2539        .await?;
2540
2541        let (tx, rx) = oneshot::channel();
2542        inner.register_finish_notifier(TEST_DATABASE_ID, job_id, tx);
2543        txn.commit().await?;
2544        drop(inner);
2545
2546        let abort_result = mgr.try_abort_creating_streaming_job(job_id, true).await?;
2547        assert!(abort_result.aborted);
2548        assert_eq!(abort_result.database_id, Some(TEST_DATABASE_ID));
2549
2550        let err = rx
2551            .await
2552            .expect("finish notifier should be notified")
2553            .expect_err("creating job cancellation should fail the create wait");
2554        assert!(err.contains("cancelled"));
2555
2556        let db = &mgr.inner.read().await.db;
2557        assert!(Object::find_by_id(job_id).one(db).await?.is_none());
2558        assert!(StreamingJob::find_by_id(job_id).one(db).await?.is_none());
2559        assert!(
2560            Table::find_by_id(job_id.as_mv_table_id())
2561                .one(db)
2562                .await?
2563                .is_none()
2564        );
2565        assert!(
2566            Object::find_by_id(internal_table_id)
2567                .one(db)
2568                .await?
2569                .is_none()
2570        );
2571        assert!(
2572            Table::find_by_id(internal_table_id)
2573                .one(db)
2574                .await?
2575                .is_none()
2576        );
2577        assert!(
2578            mgr.inner
2579                .read()
2580                .await
2581                .dropped_tables
2582                .contains_key(&internal_table_id)
2583        );
2584        assert!(
2585            Source::find_by_id(source_obj.oid.as_source_id())
2586                .one(db)
2587                .await?
2588                .is_none()
2589        );
2590
2591        let notification = notification_rx
2592            .recv()
2593            .await
2594            .expect("frontend should receive an abort notification")
2595            .into_notification()
2596            .expect("abort notification should be valid");
2597        assert_eq!(notification.operation(), NotificationOperation::Delete);
2598        let object_group = match notification.info {
2599            Some(NotificationInfo::ObjectGroup(object_group)) => object_group,
2600            other => panic!("unexpected notification: {other:?}"),
2601        };
2602        assert!(object_group.objects.iter().any(|object| matches!(
2603            &object.object_info,
2604            Some(PbObjectInfo::Table(table)) if table.id == job_id.as_mv_table_id()
2605        )));
2606        assert!(object_group.objects.iter().any(|object| matches!(
2607            &object.object_info,
2608            Some(PbObjectInfo::Source(source)) if source.id == source_obj.oid.as_source_id()
2609        )));
2610
2611        Ok(())
2612    }
2613
2614    #[tokio::test]
2615    async fn test_failed_foreground_creating_job_is_preserved() -> MetaResult<()> {
2616        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2617        let (job_id, table_id) = insert_dirty_creating_job_with_fragment(
2618            &mgr,
2619            FragmentId::new(45),
2620            1,
2621            FragmentTypeMask::empty(),
2622        )
2623        .await?;
2624        let subscriptions = mgr
2625            .create_cross_db_subscriptions(job_id, [table_id])
2626            .await?;
2627
2628        let abort_result = mgr.try_abort_creating_streaming_job(job_id, false).await?;
2629        assert!(!abort_result.aborted);
2630        assert_eq!(abort_result.database_id, Some(TEST_DATABASE_ID));
2631        assert!(abort_result.cross_db_subscriptions.is_empty());
2632
2633        let db = &mgr.inner.read().await.db;
2634        assert!(Object::find_by_id(job_id).one(db).await?.is_some());
2635        assert!(StreamingJob::find_by_id(job_id).one(db).await?.is_some());
2636        assert!(Table::find_by_id(table_id).one(db).await?.is_some());
2637        assert!(
2638            Subscription::find_by_id(subscriptions[0].subscription_id)
2639                .one(db)
2640                .await?
2641                .is_some()
2642        );
2643
2644        Ok(())
2645    }
2646
2647    #[tokio::test]
2648    async fn test_failed_created_job_is_preserved() -> MetaResult<()> {
2649        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2650        let (job_id, table_id) = insert_dirty_creating_job_with_fragment(
2651            &mgr,
2652            FragmentId::new(46),
2653            1,
2654            FragmentTypeMask::empty(),
2655        )
2656        .await?;
2657
2658        {
2659            let inner = mgr.inner.read().await;
2660            streaming_job::ActiveModel {
2661                job_id: Set(job_id),
2662                job_status: Set(JobStatus::Created),
2663                ..Default::default()
2664            }
2665            .update(&inner.db)
2666            .await?;
2667        }
2668
2669        let abort_result = mgr.try_abort_creating_streaming_job(job_id, false).await?;
2670        assert!(!abort_result.aborted);
2671        assert_eq!(abort_result.database_id, Some(TEST_DATABASE_ID));
2672        let db = &mgr.inner.read().await.db;
2673        assert!(Object::find_by_id(job_id).one(db).await?.is_some());
2674        assert!(StreamingJob::find_by_id(job_id).one(db).await?.is_some());
2675        assert!(Table::find_by_id(table_id).one(db).await?.is_some());
2676
2677        Ok(())
2678    }
2679
2680    #[tokio::test]
2681    async fn test_clean_dirty_creating_jobs_records_dropped_tables_for_per_db_recovery()
2682    -> MetaResult<()> {
2683        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2684
2685        let inner = mgr.inner.write().await;
2686        let txn = inner.db.begin().await?;
2687        let mv_obj = CatalogController::create_object(
2688            &txn,
2689            ObjectType::Table,
2690            TEST_OWNER_ID,
2691            Some(TEST_SCHEMA_ID.as_object_id()),
2692        )
2693        .await?;
2694        let job_id = mv_obj.oid.as_job_id();
2695        let mv_table_id = job_id.as_mv_table_id();
2696        insert_test_table(
2697            &txn,
2698            mv_table_id,
2699            "mv_dirty",
2700            TableType::MaterializedView,
2701            None,
2702            "CREATE MATERIALIZED VIEW mv_dirty AS SELECT 1",
2703        )
2704        .await?;
2705
2706        let internal_obj = CatalogController::create_object(
2707            &txn,
2708            ObjectType::Table,
2709            TEST_OWNER_ID,
2710            Some(job_id.as_object_id()),
2711        )
2712        .await?;
2713        let internal_table_id = internal_obj.oid.as_table_id();
2714        insert_test_table(
2715            &txn,
2716            internal_table_id,
2717            "__internal_mv_dirty",
2718            TableType::Internal,
2719            Some(job_id),
2720            "",
2721        )
2722        .await?;
2723
2724        streaming_job::ActiveModel {
2725            job_id: Set(job_id),
2726            job_status: Set(JobStatus::Initial),
2727            create_type: Set(CreateType::Foreground),
2728            timezone: Set(None),
2729            config_override: Set(None),
2730            adaptive_parallelism_strategy: Set(None),
2731            parallelism: Set(StreamingParallelism::Adaptive),
2732            backfill_parallelism: Set(None),
2733            backfill_adaptive_parallelism_strategy: Set(None),
2734            backfill_orders: Set(None),
2735            max_parallelism: Set(1),
2736            specific_resource_group: Set(None),
2737            is_serverless_backfill: Set(false),
2738            refresh_interval_sec: Set(None),
2739        }
2740        .insert(&txn)
2741        .await?;
2742        txn.commit().await?;
2743        drop(inner);
2744
2745        let cleaned = mgr
2746            .clean_dirty_creating_jobs(Some(TEST_DATABASE_ID))
2747            .await?;
2748        assert_eq!(cleaned.streaming_job_ids, vec![job_id]);
2749        assert!(cleaned.source_ids.is_empty());
2750        let mut dropped_table_ids = cleaned.dropped_table_ids;
2751        dropped_table_ids.sort_unstable();
2752        assert_eq!(dropped_table_ids, vec![mv_table_id, internal_table_id]);
2753
2754        let inner = mgr.inner.read().await;
2755        assert!(inner.dropped_tables.contains_key(&mv_table_id));
2756        assert!(inner.dropped_tables.contains_key(&internal_table_id));
2757        assert!(Object::find_by_id(job_id).one(&inner.db).await?.is_none());
2758        assert!(
2759            Object::find_by_id(internal_table_id)
2760                .one(&inner.db)
2761                .await?
2762                .is_none()
2763        );
2764        assert!(
2765            StreamingJob::find_by_id(job_id)
2766                .one(&inner.db)
2767                .await?
2768                .is_none()
2769        );
2770        assert!(
2771            Table::find_by_id(mv_table_id)
2772                .one(&inner.db)
2773                .await?
2774                .is_none()
2775        );
2776        assert!(
2777            Table::find_by_id(internal_table_id)
2778                .one(&inner.db)
2779                .await?
2780                .is_none()
2781        );
2782
2783        Ok(())
2784    }
2785
2786    #[tokio::test]
2787    async fn test_clean_dirty_creating_jobs_notifies_serving_mapping_fragment_delete()
2788    -> MetaResult<()> {
2789        let env = MetaSrvEnv::for_test().await;
2790        let (local_notification_tx, mut local_notification_rx) = mpsc::unbounded_channel();
2791        env.notification_manager()
2792            .insert_local_sender(local_notification_tx);
2793        let mgr = CatalogController::new(env).await?;
2794        let fragment_id = FragmentId::new(3);
2795        let (job_id, mv_table_id) = insert_dirty_creating_job_with_fragment(
2796            &mgr,
2797            fragment_id,
2798            1,
2799            FragmentTypeMask::from(FragmentTypeFlag::Values as u32),
2800        )
2801        .await?;
2802
2803        assert!(
2804            mgr.fragment_serving_infos()
2805                .await?
2806                .contains_key(&fragment_id)
2807        );
2808
2809        let cleaned = mgr
2810            .clean_dirty_creating_jobs(Some(TEST_DATABASE_ID))
2811            .await?;
2812        assert_eq!(cleaned.streaming_job_ids, vec![job_id]);
2813
2814        let inner = mgr.inner.read().await;
2815        assert!(Object::find_by_id(job_id).one(&inner.db).await?.is_none());
2816        assert!(
2817            StreamingJob::find_by_id(job_id)
2818                .one(&inner.db)
2819                .await?
2820                .is_none()
2821        );
2822        assert!(
2823            Table::find_by_id(mv_table_id)
2824                .one(&inner.db)
2825                .await?
2826                .is_none()
2827        );
2828        drop(inner);
2829        assert!(
2830            !mgr.fragment_serving_infos()
2831                .await?
2832                .contains_key(&fragment_id)
2833        );
2834
2835        let notification = local_notification_rx.try_recv().expect(
2836            "dirty-job cleanup must notify the serving mapping worker about deleted fragments",
2837        );
2838        match notification {
2839            LocalNotification::ServingFragmentMappingsDelete(fragment_ids) => {
2840                assert_eq!(fragment_ids, vec![fragment_id]);
2841            }
2842            notification => panic!("unexpected local notification: {notification:?}"),
2843        }
2844
2845        Ok(())
2846    }
2847
2848    #[tokio::test]
2849    async fn test_abort_creating_subscription_commits_delete() -> MetaResult<()> {
2850        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2851        let pb_view = PbView {
2852            schema_id: TEST_SCHEMA_ID,
2853            database_id: TEST_DATABASE_ID,
2854            name: "subscription_dep_view".to_owned(),
2855            owner: TEST_OWNER_ID as _,
2856            sql: "CREATE VIEW subscription_dep_view AS SELECT 1".to_owned(),
2857            ..Default::default()
2858        };
2859        mgr.create_view(pb_view, HashSet::new()).await?;
2860
2861        let view_id: ViewId = View::find()
2862            .select_only()
2863            .column(view::Column::ViewId)
2864            .filter(view::Column::Name.eq("subscription_dep_view"))
2865            .into_tuple()
2866            .one(&mgr.inner.read().await.db)
2867            .await?
2868            .unwrap();
2869
2870        let mut pb_subscription = PbSubscription {
2871            name: "subscription_to_abort".to_owned(),
2872            definition: "CREATE SUBSCRIPTION subscription_to_abort FROM subscription_dep_view"
2873                .to_owned(),
2874            retention_seconds: Some(86400),
2875            database_id: TEST_DATABASE_ID,
2876            schema_id: TEST_SCHEMA_ID,
2877            dependent_table_id: view_id.as_object_id().as_table_id(),
2878            owner: TEST_OWNER_ID as _,
2879            subscription_state: SubscriptionState::Init as _,
2880            ..Default::default()
2881        };
2882        mgr.create_subscription_catalog(&mut pb_subscription)
2883            .await?;
2884
2885        mgr.try_abort_creating_subscription(pb_subscription.id)
2886            .await?;
2887
2888        assert!(
2889            Subscription::find_by_id(pb_subscription.id)
2890                .one(&mgr.inner.read().await.db)
2891                .await?
2892                .is_none()
2893        );
2894
2895        Ok(())
2896    }
2897
2898    #[tokio::test]
2899    async fn test_drop_table_cascade_drops_dependent_subscription() -> MetaResult<()> {
2900        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2901
2902        let inner = mgr.inner.write().await;
2903        let txn = inner.db.begin().await?;
2904        let table_obj = CatalogController::create_object(
2905            &txn,
2906            ObjectType::Table,
2907            TEST_OWNER_ID,
2908            Some(TEST_SCHEMA_ID.as_object_id()),
2909        )
2910        .await?;
2911        let table_id = table_obj.oid.as_table_id();
2912        insert_test_table(
2913            &txn,
2914            table_id,
2915            "subscription_dep_table",
2916            TableType::Table,
2917            None,
2918            "CREATE TABLE subscription_dep_table (v1 INT)",
2919        )
2920        .await?;
2921        txn.commit().await?;
2922        drop(inner);
2923
2924        let mut pb_subscription = PbSubscription {
2925            name: "subscription_to_drop_with_table".to_owned(),
2926            definition:
2927                "CREATE SUBSCRIPTION subscription_to_drop_with_table FROM subscription_dep_table"
2928                    .to_owned(),
2929            retention_seconds: Some(86400),
2930            database_id: TEST_DATABASE_ID,
2931            schema_id: TEST_SCHEMA_ID,
2932            dependent_table_id: table_id,
2933            owner: TEST_OWNER_ID as _,
2934            subscription_state: SubscriptionState::Created as _,
2935            ..Default::default()
2936        };
2937        mgr.create_subscription_catalog(&mut pb_subscription)
2938            .await?;
2939
2940        mgr.drop_object(ObjectType::Table, table_id, DropMode::Cascade)
2941            .await?;
2942
2943        let db = &mgr.inner.read().await.db;
2944        assert!(Table::find_by_id(table_id).one(db).await?.is_none());
2945        assert!(
2946            Object::find_by_id(table_id.as_object_id())
2947                .one(db)
2948                .await?
2949                .is_none()
2950        );
2951        assert!(
2952            Subscription::find_by_id(pb_subscription.id)
2953                .one(db)
2954                .await?
2955                .is_none()
2956        );
2957        assert!(
2958            Object::find_by_id(pb_subscription.id.as_object_id())
2959                .one(db)
2960                .await?
2961                .is_none()
2962        );
2963
2964        Ok(())
2965    }
2966
2967    #[tokio::test]
2968    async fn test_get_table_change_log_truncate_info() -> MetaResult<()> {
2969        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
2970        let pb_view = PbView {
2971            schema_id: TEST_SCHEMA_ID,
2972            database_id: TEST_DATABASE_ID,
2973            name: "change_log_upstream".to_owned(),
2974            owner: TEST_OWNER_ID as _,
2975            sql: "CREATE VIEW change_log_upstream AS SELECT 1".to_owned(),
2976            ..Default::default()
2977        };
2978        mgr.create_view(pb_view, HashSet::new()).await?;
2979        let upstream_table_id: TableId = View::find()
2980            .select_only()
2981            .column(view::Column::ViewId)
2982            .filter(view::Column::Name.eq("change_log_upstream"))
2983            .into_tuple::<ViewId>()
2984            .one(&mgr.inner.read().await.db)
2985            .await?
2986            .unwrap()
2987            .as_object_id()
2988            .as_table_id();
2989        let mut subscription = PbSubscription {
2990            name: "change_log_subscription".to_owned(),
2991            definition: "CREATE SUBSCRIPTION change_log_subscription FROM change_log_upstream"
2992                .to_owned(),
2993            retention_seconds: Some(123),
2994            database_id: TEST_DATABASE_ID,
2995            schema_id: TEST_SCHEMA_ID,
2996            dependent_table_id: upstream_table_id,
2997            owner: TEST_OWNER_ID as _,
2998            subscription_state: SubscriptionState::Created as _,
2999            ..Default::default()
3000        };
3001        mgr.create_subscription_catalog(&mut subscription).await?;
3002
3003        let inner = mgr.inner.write().await;
3004        let txn = inner.db.begin().await?;
3005        let (job_id, _, state_table_id) =
3006            insert_test_streaming_job(&txn, "snapshot_job", true, None).await?;
3007        let cross_db_progress_table_id = TableId::new(9998);
3008        let mut job = streaming_job::Entity::find_by_id(job_id)
3009            .one(&txn)
3010            .await?
3011            .unwrap()
3012            .into_active_model();
3013        job.job_status = Set(JobStatus::Creating);
3014        job.update(&txn).await?;
3015        fragment::ActiveModel {
3016            fragment_id: Set(FragmentId::new(100)),
3017            job_id: Set(job_id),
3018            fragment_type_mask: Set(FragmentTypeFlag::SnapshotBackfillStreamScan as i32),
3019            distribution_type: Set(fragment::DistributionType::Hash),
3020            stream_node: Set(StreamNode::from(&PbStreamNode {
3021                node_body: Some(PbNodeBody::StreamScan(Box::new(StreamScanNode {
3022                    table_id: upstream_table_id,
3023                    stream_scan_type: StreamScanType::SnapshotBackfill as i32,
3024                    snapshot_backfill_epoch: None,
3025                    ..Default::default()
3026                }))),
3027                ..Default::default()
3028            })),
3029            state_table_ids: Set(vec![state_table_id].into()),
3030            upstream_fragment_id: Set(I32Array::default()),
3031            vnode_count: Set(1),
3032            parallelism: Set(None),
3033        }
3034        .insert(&txn)
3035        .await?;
3036        fragment::ActiveModel {
3037            fragment_id: Set(FragmentId::new(104)),
3038            job_id: Set(job_id),
3039            fragment_type_mask: Set(FragmentTypeFlag::CrossDbSnapshotBackfillStreamScan as i32),
3040            distribution_type: Set(fragment::DistributionType::Hash),
3041            stream_node: Set(StreamNode::from(&PbStreamNode {
3042                node_body: Some(PbNodeBody::StreamScan(Box::new(StreamScanNode {
3043                    table_id: upstream_table_id,
3044                    stream_scan_type: StreamScanType::CrossDbSnapshotBackfill as i32,
3045                    state_table: Some(PbTable {
3046                        id: cross_db_progress_table_id,
3047                        ..Default::default()
3048                    }),
3049                    ..Default::default()
3050                }))),
3051                ..Default::default()
3052            })),
3053            state_table_ids: Set(vec![cross_db_progress_table_id].into()),
3054            upstream_fragment_id: Set(I32Array::default()),
3055            vnode_count: Set(1),
3056            parallelism: Set(None),
3057        }
3058        .insert(&txn)
3059        .await?;
3060        fragment::ActiveModel {
3061            fragment_id: Set(FragmentId::new(103)),
3062            job_id: Set(job_id),
3063            fragment_type_mask: Set(0),
3064            distribution_type: Set(fragment::DistributionType::Hash),
3065            stream_node: Set(StreamNode::from(&PbStreamNode::default())),
3066            state_table_ids: Set(vec![TableId::new(9999)].into()),
3067            upstream_fragment_id: Set(I32Array::default()),
3068            vnode_count: Set(1),
3069            parallelism: Set(None),
3070        }
3071        .insert(&txn)
3072        .await?;
3073
3074        let (iceberg_job_id, _, progress_table_id) =
3075            insert_test_streaming_job(&txn, "iceberg_v3_sink", false, None).await?;
3076        fragment::ActiveModel {
3077            fragment_id: Set(FragmentId::new(101)),
3078            job_id: Set(iceberg_job_id),
3079            fragment_type_mask: Set(FragmentTypeFlag::IcebergWithPkIndexWriter as i32),
3080            distribution_type: Set(fragment::DistributionType::Hash),
3081            stream_node: Set(StreamNode::from(&PbStreamNode {
3082                node_body: Some(PbNodeBody::IcebergWithPkIndexWriter(Default::default())),
3083                ..Default::default()
3084            })),
3085            state_table_ids: Set(Default::default()),
3086            upstream_fragment_id: Set(I32Array::default()),
3087            vnode_count: Set(1),
3088            parallelism: Set(None),
3089        }
3090        .insert(&txn)
3091        .await?;
3092        fragment::ActiveModel {
3093            fragment_id: Set(FragmentId::new(102)),
3094            job_id: Set(iceberg_job_id),
3095            fragment_type_mask: Set(FragmentTypeFlag::SnapshotBackfillStreamScan as i32),
3096            distribution_type: Set(fragment::DistributionType::Hash),
3097            stream_node: Set(StreamNode::from(&PbStreamNode {
3098                node_body: Some(PbNodeBody::StreamScan(Box::new(StreamScanNode {
3099                    table_id: upstream_table_id,
3100                    stream_scan_type: StreamScanType::SnapshotBackfill as i32,
3101                    state_table: Some(PbTable {
3102                        id: progress_table_id,
3103                        ..Default::default()
3104                    }),
3105                    ..Default::default()
3106                }))),
3107                ..Default::default()
3108            })),
3109            state_table_ids: Set(vec![progress_table_id].into()),
3110            upstream_fragment_id: Set(I32Array::default()),
3111            vnode_count: Set(1),
3112            parallelism: Set(None),
3113        }
3114        .insert(&txn)
3115        .await?;
3116        txn.commit().await?;
3117        drop(inner);
3118
3119        let truncate_info = mgr.get_table_change_log_truncate_info().await?;
3120        assert_eq!(
3121            truncate_info.subscription_retention_seconds,
3122            HashMap::from([(upstream_table_id, 123)])
3123        );
3124        assert_eq!(truncate_info.committed_epoch_truncate_jobs.len(), 1);
3125        let committed_epoch_truncate_job = &truncate_info.committed_epoch_truncate_jobs[0];
3126        assert_eq!(committed_epoch_truncate_job.job_id, job_id);
3127        assert_eq!(
3128            committed_epoch_truncate_job.state_table_ids,
3129            HashSet::from([state_table_id])
3130        );
3131        assert_eq!(
3132            committed_epoch_truncate_job.upstream_table_snapshot_epochs,
3133            HashMap::from([(upstream_table_id, None)])
3134        );
3135        assert_eq!(truncate_info.progress_table_subscribers.len(), 2);
3136        let progress_subscriber = truncate_info
3137            .progress_table_subscribers
3138            .iter()
3139            .find(|subscriber| subscriber.subscriber_job_id == iceberg_job_id)
3140            .unwrap();
3141        assert_eq!(progress_subscriber.subscriber_job_id, iceberg_job_id);
3142        assert_eq!(progress_subscriber.upstream_table_id, upstream_table_id);
3143        assert_eq!(progress_subscriber.progress_table_id, progress_table_id);
3144        let cross_db_progress_subscriber = truncate_info
3145            .progress_table_subscribers
3146            .iter()
3147            .find(|subscriber| subscriber.subscriber_job_id == job_id)
3148            .unwrap();
3149        assert_eq!(
3150            cross_db_progress_subscriber.upstream_table_id,
3151            upstream_table_id
3152        );
3153        assert_eq!(
3154            cross_db_progress_subscriber.progress_table_id,
3155            cross_db_progress_table_id
3156        );
3157
3158        Ok(())
3159    }
3160
3161    #[tokio::test]
3162    async fn test_cross_db_subscription_lifecycle_and_recovery_lookup() -> MetaResult<()> {
3163        let mgr = CatalogController::new(MetaSrvEnv::for_test().await).await?;
3164        let (_, upstream_database) = mgr
3165            .create_database(PbDatabase {
3166                name: "cross_db_upstream_database".to_owned(),
3167                owner: TEST_OWNER_ID,
3168                ..Default::default()
3169            })
3170            .await?;
3171        let upstream_schema_id: SchemaId = Schema::find()
3172            .inner_join(Object)
3173            .select_only()
3174            .column(schema::Column::SchemaId)
3175            .filter(object::Column::DatabaseId.eq(upstream_database.database_id))
3176            .into_tuple()
3177            .one(&mgr.inner.read().await.db)
3178            .await?
3179            .unwrap();
3180
3181        let inner = mgr.inner.write().await;
3182        let txn = inner.db.begin().await?;
3183        let upstream_job_id = CatalogController::create_object(
3184            &txn,
3185            ObjectType::Table,
3186            TEST_OWNER_ID,
3187            Some(upstream_schema_id.as_object_id()),
3188        )
3189        .await?
3190        .oid
3191        .as_job_id();
3192        insert_test_table(
3193            &txn,
3194            upstream_job_id.as_mv_table_id(),
3195            "cross_db_upstream_mv",
3196            TableType::MaterializedView,
3197            None,
3198            "",
3199        )
3200        .await?;
3201        insert_test_streaming_job_model(&txn, upstream_job_id, None).await?;
3202        let (downstream_job_id, Some(downstream_table_id), progress_table_id) =
3203            insert_test_streaming_job(&txn, "cross_db_downstream_mv", true, None).await?
3204        else {
3205            unreachable!()
3206        };
3207        let (aborted_downstream_job_id, _, _) =
3208            insert_test_streaming_job(&txn, "cross_db_aborted_downstream_mv", true, None).await?;
3209        streaming_job::ActiveModel {
3210            job_id: Set(aborted_downstream_job_id),
3211            job_status: Set(JobStatus::Initial),
3212            ..Default::default()
3213        }
3214        .update(&txn)
3215        .await?;
3216        fragment::ActiveModel {
3217            fragment_id: Set(FragmentId::new(101)),
3218            job_id: Set(downstream_job_id),
3219            fragment_type_mask: Set(FragmentTypeFlag::CrossDbSnapshotBackfillStreamScan as i32),
3220            distribution_type: Set(fragment::DistributionType::Hash),
3221            stream_node: Set(StreamNode::from(&PbStreamNode {
3222                node_body: Some(PbNodeBody::StreamScan(Box::new(StreamScanNode {
3223                    table_id: upstream_job_id.as_mv_table_id(),
3224                    stream_scan_type: StreamScanType::CrossDbSnapshotBackfill as i32,
3225                    state_table: Some(PbTable {
3226                        id: progress_table_id,
3227                        maybe_vnode_count: VnodeCount::set(1).to_protobuf(),
3228                        ..Default::default()
3229                    }),
3230                    ..Default::default()
3231                }))),
3232                ..Default::default()
3233            })),
3234            state_table_ids: Set(vec![progress_table_id].into()),
3235            upstream_fragment_id: Set(I32Array::default()),
3236            vnode_count: Set(1),
3237            parallelism: Set(None),
3238        }
3239        .insert(&txn)
3240        .await?;
3241        txn.commit().await?;
3242        drop(inner);
3243
3244        let truncate_info_without_subscription = mgr.get_table_change_log_truncate_info().await?;
3245        assert_eq!(
3246            truncate_info_without_subscription.progress_table_subscribers[0].progress_table_id,
3247            progress_table_id
3248        );
3249
3250        let subscriptions = mgr
3251            .create_cross_db_subscriptions(downstream_job_id, [upstream_job_id.as_mv_table_id()])
3252            .await?;
3253        assert_eq!(subscriptions.len(), 1);
3254        let subscription = &subscriptions[0];
3255        assert_eq!(
3256            subscription.upstream_database_id,
3257            upstream_database.database_id
3258        );
3259        assert_eq!(
3260            subscription.upstream_table_id,
3261            upstream_job_id.as_mv_table_id()
3262        );
3263        let subscription_model = Subscription::find_by_id(subscription.subscription_id)
3264            .one(&mgr.inner.read().await.db)
3265            .await?
3266            .unwrap();
3267        assert_eq!(subscription_model.retention_seconds, None);
3268        assert_eq!(
3269            subscription_model.cross_db_downstream_job_id,
3270            Some(downstream_job_id)
3271        );
3272        let subscription_object = Object::find_by_id(subscription.subscription_id)
3273            .one(&mgr.inner.read().await.db)
3274            .await?
3275            .unwrap();
3276        assert_eq!(
3277            subscription_object.belong_to_oid,
3278            Some(downstream_job_id.as_object_id())
3279        );
3280
3281        let upstream_subscriptions = mgr
3282            .get_mv_depended_subscriptions(Some(upstream_database.database_id))
3283            .await?;
3284        assert!(
3285            upstream_subscriptions[&upstream_job_id.as_mv_table_id()]
3286                .contains(&subscription.subscription_id)
3287        );
3288        assert!(
3289            mgr.get_mv_depended_subscriptions(Some(TEST_DATABASE_ID))
3290                .await?
3291                .is_empty()
3292        );
3293
3294        let truncate_info = mgr.get_table_change_log_truncate_info().await?;
3295        assert!(truncate_info.subscription_retention_seconds.is_empty());
3296        assert_eq!(truncate_info.progress_table_subscribers.len(), 1);
3297        assert_eq!(
3298            truncate_info.progress_table_subscribers[0].progress_table_id,
3299            progress_table_id
3300        );
3301
3302        let aborted_subscriptions = mgr
3303            .create_cross_db_subscriptions(
3304                aborted_downstream_job_id,
3305                [upstream_job_id.as_mv_table_id()],
3306            )
3307            .await?;
3308        let abort_result = mgr
3309            .try_abort_creating_streaming_job(aborted_downstream_job_id, false)
3310            .await?;
3311        assert!(abort_result.aborted);
3312        assert_eq!(abort_result.cross_db_subscriptions.len(), 1);
3313        assert_eq!(
3314            abort_result.cross_db_subscriptions[0].subscription_id,
3315            aborted_subscriptions[0].subscription_id
3316        );
3317        assert_eq!(
3318            abort_result.cross_db_subscriptions[0].upstream_table_id,
3319            upstream_job_id.as_mv_table_id()
3320        );
3321        assert_eq!(
3322            abort_result.cross_db_subscriptions[0].upstream_database_id,
3323            upstream_database.database_id
3324        );
3325        assert!(
3326            Subscription::find_by_id(aborted_subscriptions[0].subscription_id)
3327                .one(&mgr.inner.read().await.db)
3328                .await?
3329                .is_none()
3330        );
3331
3332        let (release_context, _) = mgr
3333            .drop_object(ObjectType::Table, downstream_table_id, DropMode::Restrict)
3334            .await?;
3335        assert_eq!(release_context.removed_cross_db_subscriptions.len(), 1);
3336        assert!(
3337            Subscription::find_by_id(subscription.subscription_id)
3338                .one(&mgr.inner.read().await.db)
3339                .await?
3340                .is_none()
3341        );
3342
3343        Ok(())
3344    }
3345}