diff --git a/sqlmesh/core/plan/evaluator.py b/sqlmesh/core/plan/evaluator.py index 71e5285d63..4c23827b5b 100644 --- a/sqlmesh/core/plan/evaluator.py +++ b/sqlmesh/core/plan/evaluator.py @@ -382,6 +382,8 @@ def visit_migrate_schemas_stage( allow_destructive_snapshots=plan.allow_destructive_models, allow_additive_snapshots=plan.allow_additive_models, deployability_index=stage.deployability_index, + grants_only_snapshot_ids=stage.grants_only_snapshot_ids, + create_only_snapshot_ids=stage.create_only_snapshot_ids, ) except NodeExecutionFailedError as ex: raise PlanError(str(ex.__cause__) if ex.__cause__ else str(ex)) diff --git a/sqlmesh/core/plan/explainer.py b/sqlmesh/core/plan/explainer.py index 6e3fb8f9c3..e22c13d05c 100644 --- a/sqlmesh/core/plan/explainer.py +++ b/sqlmesh/core/plan/explainer.py @@ -315,14 +315,35 @@ def visit_backfill_stage(self, stage: stages.BackfillStage) -> Tree: tree.add(f"{display_name} \\[standalone audit]") return tree - def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> Tree: - tree = Tree( - "[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]" - ) + def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> t.Optional[Tree]: + migrated_snapshots = [ + s + for s in stage.snapshots + if s.snapshot_id not in stage.grants_only_snapshot_ids + and s.snapshot_id not in stage.create_only_snapshot_ids + ] + grants_only_snapshots = [ + s for s in stage.snapshots if s.snapshot_id in stage.grants_only_snapshot_ids + ] + if not migrated_snapshots and not grants_only_snapshots: + return None + + if migrated_snapshots: + tree = Tree( + "[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]" + ) + else: + tree = Tree("[bold]Sync grants on production physical tables[/bold]") + for snapshot in stage.snapshots: + if snapshot.snapshot_id in stage.create_only_snapshot_ids: + continue display_name = self._display_name(snapshot) table_name = snapshot.table_name(True) - tree.add(f"{display_name} -> {table_name}") + if migrated_snapshots and snapshot.snapshot_id in stage.grants_only_snapshot_ids: + tree.add(f"{display_name} -> {table_name} (sync grants)") + else: + tree.add(f"{display_name} -> {table_name}") return tree def visit_virtual_layer_update_stage(self, stage: stages.VirtualLayerUpdateStage) -> Tree: diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..b7bb9ab088 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import typing as t -from dataclasses import dataclass +from dataclasses import dataclass, field from sqlmesh.core import constants as c from sqlmesh.core.environment import EnvironmentStatements, EnvironmentNamingInfo, Environment from sqlmesh.core.plan.common import should_force_rebuild @@ -14,6 +16,7 @@ SnapshotId, snapshots_to_dag, ) +from sqlmesh.utils.dag import DAG from sqlmesh.utils.errors import PlanError @@ -154,11 +157,17 @@ class MigrateSchemasStage: snapshots: Snapshots to migrate schemas for. all_snapshots: All snapshots in the plan by snapshot ID. deployability_index: Deployability index for this stage. + grants_only_snapshot_ids: Snapshot IDs that only need physical grants synchronized + without recreating or altering their physical objects. + create_only_snapshot_ids: Snapshot IDs that should only be created if their physical + object does not yet exist, without being migrated or recreated if it already exists. """ snapshots: t.List[Snapshot] all_snapshots: t.Dict[SnapshotId, Snapshot] deployability_index: DeployabilityIndex + grants_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set) + create_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set) @dataclass @@ -263,7 +272,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: if plan.is_dev: before_promote_snapshots = all_selected_for_backfill_snapshots after_promote_snapshots = set() - snapshots_with_schema_migration = [] else: before_promote_snapshots = { s.snapshot_id @@ -274,30 +282,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: after_promote_snapshots = all_selected_for_backfill_snapshots - before_promote_snapshots deployability_index = DeployabilityIndex.all_deployable() - snapshot_ids_with_schema_migration = [ - s.snapshot_id for s in snapshots.values() if s.requires_schema_migration_in_prod - ] - # Include all upstream dependencies of snapshots that require schema migration to make sure - # the upstream tables are created before the schema updates are applied - snapshot_ids_to_migrate = set(dag.subdag(*snapshot_ids_with_schema_migration)) - # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE, - # so those are migrated too to be recreated - for s_id in dag: - snapshot = snapshots[s_id] - if snapshot.is_view and any( - p_id in snapshot_ids_to_migrate - and snapshots[p_id].is_view - and snapshots[p_id].supports_schema_migration_in_prod - for p_id in snapshot.parents - ): - snapshot_ids_to_migrate.add(s_id) - snapshots_with_schema_migration = [ - snapshots[s_id] - for s_id in dag - if s_id in snapshot_ids_to_migrate - and snapshots[s_id].supports_schema_migration_in_prod - ] - snapshots_to_intervals = self._missing_intervals( plan, snapshots_by_name, deployability_index ) @@ -387,14 +371,12 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: ) ) - if snapshots_with_schema_migration: - stages.append( - MigrateSchemasStage( - snapshots=snapshots_with_schema_migration, - all_snapshots=snapshots, - deployability_index=deployability_index, - ) + if not plan.is_dev: + migrate_schemas_stage = self._get_migrate_schemas_stage( + snapshots, dag, existing_environment, deployability_index, needs_backfill ) + if migrate_schemas_stage: + stages.append(migrate_schemas_stage) if not plan.is_dev and not plan.ensure_finalized_snapshots and promoted_snapshots: # Only unpause at this point if we don't have to use the finalized snapshots @@ -507,6 +489,170 @@ def _get_physical_layer_update_stage( deployability_index=deployability_index, ) + def _get_migrate_schemas_stage( + self, + snapshots: t.Dict[SnapshotId, Snapshot], + dag: DAG[SnapshotId], + existing_environment: t.Optional[Environment], + deployability_index: DeployabilityIndex, + needs_backfill: bool, + ) -> t.Optional[MigrateSchemasStage]: + if existing_environment and not existing_environment.expired: + if existing_environment.finalized_ts: + prod_baselines: t.List[t.Dict[str, SnapshotTableInfo]] = [ + {s.name: s for s in existing_environment.snapshots} + ] + elif existing_environment.previous_finalized_snapshots: + # Unfinalized prod environment: the previous failed plan may have stopped either + # before or after MigrateSchemasStage, so the live physical MV could match either + # previous_finalized_snapshots or existing_environment.snapshots. Only skip + # recreation when the candidate matches both baselines. + prod_baselines = [ + {s.name: s for s in existing_environment.previous_finalized_snapshots}, + {s.name: s for s in existing_environment.snapshots}, + ] + else: + prod_baselines = [] + else: + prod_baselines = [] + + candidate_mv_old_ids: t.Set[SnapshotId] = { + baseline[s.name].snapshot_id + for s in snapshots.values() + if s.requires_schema_migration_in_prod and s.is_materialized_view + for baseline in prod_baselines + if s.name in baseline + } + old_snapshots_by_id: t.Dict[SnapshotId, Snapshot] = {} + if candidate_mv_old_ids: + missing_old_ids = [s_id for s_id in candidate_mv_old_ids if s_id not in snapshots] + fetched_old_snapshots = ( + self.state_reader.get_snapshots(missing_old_ids) if missing_old_ids else {} + ) + for s_id in candidate_mv_old_ids: + old_snapshot = snapshots.get(s_id) or fetched_old_snapshots.get(s_id) + if old_snapshot: + old_snapshots_by_id[s_id] = old_snapshot + + def _matches_baseline(s: Snapshot, baseline: t.Dict[str, SnapshotTableInfo]) -> bool: + existing = baseline.get(s.name) + if existing is None or not existing.is_model or existing.is_symbolic: + return False + if existing.table_name(is_deployable=True) != s.table_name(is_deployable=True): + return False + old = old_snapshots_by_id.get(existing.snapshot_id) + if old is not None: + if not old.is_model or s.is_directly_modified(old): + return False + elif existing.fingerprint.data_hash != s.fingerprint.data_hash: + return False + if existing.fingerprint.parent_data_hash != s.fingerprint.parent_data_hash: + return False + parents_to_check = list(s.parents) + visited_parents: t.Set[SnapshotId] = set() + while parents_to_check: + p_id = parents_to_check.pop() + if p_id in visited_parents: + continue + visited_parents.add(p_id) + parent = snapshots.get(p_id) + if parent is None: + return False + if parent.is_symbolic: + parents_to_check.extend(parent.parents) + continue + if not parent.is_model: + return False + existing_parent = baseline.get(parent.name) + if ( + existing_parent is None + or not existing_parent.is_model + or existing_parent.is_symbolic + or existing_parent.table_name(is_deployable=True) + != parent.table_name(is_deployable=True) + ): + return False + return True + + def _is_metadata_only_in_prod(s: Snapshot) -> bool: + return bool(prod_baselines) and all( + _matches_baseline(s, baseline) for baseline in prod_baselines + ) + + schema_migration_snapshot_ids: t.List[SnapshotId] = [] + grants_only_snapshot_ids: t.Set[SnapshotId] = set() + metadata_only_create_ids: t.Set[SnapshotId] = set() + for s in snapshots.values(): + if not s.requires_schema_migration_in_prod: + continue + if s.is_materialized_view and _is_metadata_only_in_prod(s): + targets_physical_grants = s.model.grants is not None and ( + s.model.grants_target_layer.is_all + or s.model.grants_target_layer.is_physical + or s.model.virtual_environment_mode.is_dev_only + ) + grants_changed = any( + (old := old_snapshots_by_id.get(baseline[s.name].snapshot_id)) is None + or not old.is_model + or s.model.grants != old.model.grants + or s.model.grants_target_layer != old.model.grants_target_layer + for baseline in prod_baselines + ) + if targets_physical_grants and grants_changed: + grants_only_snapshot_ids.add(s.snapshot_id) + elif needs_backfill: + # When backfill runs, PhysicalLayerUpdateStage is skipped. Route metadata-only + # MVs to create-only handling so a missing physical MV is still created while an + # existing MV is untouched. + metadata_only_create_ids.add(s.snapshot_id) + continue + schema_migration_snapshot_ids.append(s.snapshot_id) + + # Include all upstream dependencies of snapshots that require schema migration to make sure + # the upstream tables are created before the schema updates are applied + snapshot_ids_to_migrate = set(dag.subdag(*schema_migration_snapshot_ids)) + upstream_only_ids = snapshot_ids_to_migrate - set(schema_migration_snapshot_ids) + create_only_snapshot_ids = { + s_id + for s_id in upstream_only_ids + if s_id not in grants_only_snapshot_ids + and snapshots[s_id].is_materialized_view + and snapshots[s_id].supports_schema_migration_in_prod + } | metadata_only_create_ids + snapshot_ids_to_migrate |= metadata_only_create_ids + # Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE, + # so those are migrated too to be recreated + for s_id in dag: + snapshot = snapshots[s_id] + if snapshot.is_view and any( + p_id in snapshot_ids_to_migrate + and p_id not in create_only_snapshot_ids + and p_id not in grants_only_snapshot_ids + and snapshots[p_id].is_view + and snapshots[p_id].supports_schema_migration_in_prod + for p_id in snapshot.parents + ): + snapshot_ids_to_migrate.add(s_id) + grants_only_snapshot_ids.discard(s_id) + create_only_snapshot_ids.discard(s_id) + + all_migrate_stage_ids = snapshot_ids_to_migrate | grants_only_snapshot_ids + snapshots_with_schema_migration = [ + snapshots[s_id] + for s_id in dag + if s_id in all_migrate_stage_ids and snapshots[s_id].supports_schema_migration_in_prod + ] + if not snapshots_with_schema_migration: + return None + + return MigrateSchemasStage( + snapshots=snapshots_with_schema_migration, + all_snapshots=snapshots, + deployability_index=deployability_index, + grants_only_snapshot_ids=grants_only_snapshot_ids, + create_only_snapshot_ids=create_only_snapshot_ids, + ) + def _get_virtual_layer_update_stage( self, promoted_snapshots: t.Set[SnapshotTableInfo], diff --git a/sqlmesh/core/snapshot/evaluator.py b/sqlmesh/core/snapshot/evaluator.py index 345f8816e6..303746b214 100644 --- a/sqlmesh/core/snapshot/evaluator.py +++ b/sqlmesh/core/snapshot/evaluator.py @@ -488,6 +488,8 @@ def migrate( allow_destructive_snapshots: t.Optional[t.Set[str]] = None, allow_additive_snapshots: t.Optional[t.Set[str]] = None, deployability_index: t.Optional[DeployabilityIndex] = None, + grants_only_snapshot_ids: t.Optional[t.Set[SnapshotId]] = None, + create_only_snapshot_ids: t.Optional[t.Set[SnapshotId]] = None, ) -> None: """Alters a physical snapshot table to match its snapshot's schema for the given collection of snapshots. @@ -497,30 +499,48 @@ def migrate( allow_destructive_snapshots: Set of snapshots that are allowed to have destructive schema changes. allow_additive_snapshots: Set of snapshots that are allowed to have additive schema changes. deployability_index: Determines snapshots that are deployable in the context of this evaluation. + grants_only_snapshot_ids: Snapshot IDs for which only physical grants should be synced if + the physical object already exists. + create_only_snapshot_ids: Snapshot IDs that should only be created if their physical + object does not yet exist. """ + allow_destructive_snapshots = allow_destructive_snapshots or set() + allow_additive_snapshots = allow_additive_snapshots or set() + grants_only_snapshot_ids = grants_only_snapshot_ids or set() + create_only_snapshot_ids = create_only_snapshot_ids or set() + deployability_index = deployability_index or DeployabilityIndex.all_deployable() target_data_objects = self._get_physical_data_objects(target_snapshots, deployability_index) - if not target_data_objects: + if ( + not target_data_objects + and not create_only_snapshot_ids + and not grants_only_snapshot_ids + ): return if not snapshots: snapshots = {s.snapshot_id: s for s in target_snapshots} - allow_destructive_snapshots = allow_destructive_snapshots or set() - allow_additive_snapshots = allow_additive_snapshots or set() snapshots_by_name = {s.name: s for s in snapshots.values()} with self.concurrent_context(): # Only migrate snapshots for which there's an existing data object concurrent_apply_to_snapshots( target_snapshots, - lambda s: self._migrate_snapshot( - s, - snapshots_by_name, - target_data_objects.get(s.snapshot_id), - allow_destructive_snapshots, - allow_additive_snapshots, - self.get_adapter(s.model_gateway), - deployability_index, + lambda s: ( + None + if s.snapshot_id in create_only_snapshot_ids + and s.snapshot_id in target_data_objects + else self._migrate_snapshot( + s, + snapshots_by_name, + target_data_objects.get(s.snapshot_id), + allow_destructive_snapshots, + allow_additive_snapshots, + self.get_adapter(s.model_gateway), + deployability_index, + grants_only=s.snapshot_id in grants_only_snapshot_ids, + create_only=s.snapshot_id in create_only_snapshot_ids, + ) ), self.ddl_concurrent_tasks, context_factory=execution_context_factory(), @@ -1164,6 +1184,8 @@ def _migrate_snapshot( allow_additive_snapshots: t.Set[str], adapter: EngineAdapter, deployability_index: DeployabilityIndex, + grants_only: bool = False, + create_only: bool = False, ) -> None: if not snapshot.is_model or snapshot.is_symbolic: return @@ -1179,6 +1201,22 @@ def _migrate_snapshot( update_execution(target=target_table_name, existed=target_data_object is not None) evaluation_strategy = _evaluation_strategy(snapshot, adapter) + if target_data_object is not None: + if grants_only: + with ( + adapter.transaction(), + adapter.session(snapshot.model.render_session_properties(**render_kwargs)), + ): + evaluation_strategy._apply_grants( + snapshot.model, + target_table_name, + GrantsTargetLayer.PHYSICAL, + is_snapshot_deployable=True, + ) + return + if create_only: + return + evaluation_strategy.run_pre_statements( snapshot=snapshot, render_kwargs={**render_kwargs, "inside_transaction": False} ) diff --git a/tests/core/integration/test_forward_only.py b/tests/core/integration/test_forward_only.py index 2dddf18efd..2d9068e001 100644 --- a/tests/core/integration/test_forward_only.py +++ b/tests/core/integration/test_forward_only.py @@ -1495,3 +1495,255 @@ def test_new_forward_only_model_same_dev_environment(init_and_plan_context: t.Ca df = context.fetchdf("SELECT * FROM memory.sushi__dev.new_model").replace({np.nan: None}) assert df.to_dict() == {"ds": {0: "2023-01-07"}, "b": {0: 1}} + + +def _init_mv_context(tmp_path): + from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig + from tests.utils.test_filesystem import create_temp_file + + models_dir = tmp_path / "models" + create_temp_file( + tmp_path, + models_dir / "src.sql", + """ + MODEL ( + name db.src, + kind FULL, + ); + SELECT 1 AS a, '2023-01-01' AS ds; + """, + ) + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + ); + SELECT a, ds FROM db.src; + """, + ) + config = Config( + gateways={"": GatewayConfig(connection=DuckDBConnectionConfig())}, + default_gateway="", + ) + return Context(paths=tmp_path, config=config) + + +def test_materialized_view_metadata_only_no_recreate(tmp_path, mocker): + from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter + from tests.utils.test_filesystem import create_temp_file + + context = _init_mv_context(tmp_path) + create_view_spy = mocker.spy(DuckDBEngineAdapter, "create_view") + drop_view_spy = mocker.spy(DuckDBEngineAdapter, "drop_view") + + # Initial prod deploy builds the physical MV once + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + models_dir = tmp_path / "models" + + # 1. Metadata-only change in prod (owner + tags + SQL comment) -> zero physical MV recreate/drop + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + tags ['analytics'], + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + # 2. Dev -> prod metadata-only change -> zero physical MV recreate/drop on prod deploy + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner bob, + tags ['analytics', 'core'], + ); + SELECT a, ds FROM db.src -- updated doc comment + """, + ) + context.load() + context.plan("dev", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(1,)] + + # 3. Rollback in prod to previous metadata-only snapshot -> zero physical MV recreate/drop + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + tags ['analytics'], + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + + # 4. Physical grants sync (add, update, revoke-all) -> sync_grants_config without MV recreation + mocker.patch.object(DuckDBEngineAdapter, "SUPPORTS_GRANTS", True) + sync_grants_mock = mocker.patch.object(DuckDBEngineAdapter, "sync_grants_config") + for grants_sql, expected_grants in [ + ("grants ('select' = ['analyst'])", {"select": ["analyst"]}), + ("grants ('select' = ['analyst', 'viewer'])", {"select": ["analyst", "viewer"]}), + ("grants ()", {}), + ]: + create_view_spy.reset_mock() + drop_view_spy.reset_mock() + sync_grants_mock.reset_mock() + create_temp_file( + tmp_path, + models_dir / "mv.sql", + f""" + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + grants_target_layer physical, + {grants_sql}, + ); + SELECT a, ds FROM db.src -- trailing doc comment + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + assert [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] == [] + assert drop_view_spy.call_count == 0 + assert sync_grants_mock.call_count == 1 + assert sync_grants_mock.call_args[0][1] == expected_grants + + # 5. Stacked dev forward-only SQL change + metadata-only change -> prod MUST migrate MV + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner alice, + ); + SELECT a + 10 AS a, ds FROM db.src + """, + ) + context.load() + context.plan("dev", forward_only=True, auto_apply=True, no_prompts=True, skip_tests=True) + + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + owner charlie, + ); + SELECT a + 10 AS a, ds FROM db.src + """, + ) + context.load() + context.plan("dev", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy.reset_mock() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a FROM db.mv") == [(11,)] + + +def test_materialized_view_upstream_breaking_with_downstream_forward_only_created_once( + tmp_path, mocker +): + from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter + from tests.utils.test_filesystem import create_temp_file + + context = _init_mv_context(tmp_path) + models_dir = tmp_path / "models" + create_temp_file( + tmp_path, + models_dir / "downstream.sql", + """ + MODEL ( + name db.downstream, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true, + ), + start '2023-01-01', + ); + SELECT a, ds FROM db.mv; + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + + create_view_spy = mocker.spy(DuckDBEngineAdapter, "create_view") + # Breaking change on upstream MV + forward_only downstream table + create_temp_file( + tmp_path, + models_dir / "mv.sql", + """ + MODEL ( + name db.mv, + kind VIEW (materialized true), + ); + SELECT a * 2 AS a, 99 AS b, ds FROM db.src; + """, + ) + create_temp_file( + tmp_path, + models_dir / "downstream.sql", + """ + MODEL ( + name db.downstream, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true, + ), + start '2023-01-01', + ); + SELECT a, b, ds FROM db.mv; + """, + ) + context.load() + context.plan("prod", auto_apply=True, no_prompts=True, skip_tests=True) + + mv_creates = [c for c in create_view_spy.call_args_list if c.kwargs.get("materialized")] + # Upstream MV must be created once (during BackfillStage), NOT recreated during MigrateSchemasStage + assert len(mv_creates) == 1 + assert context.engine_adapter.fetchall("SELECT a, b FROM db.mv") == [(2, 99)] + # Downstream forward-only table had column `b` added without re-backfilling historical intervals + assert context.engine_adapter.fetchall("SELECT a, b FROM db.downstream") == [(1, None)] diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..5306610c5e 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -2267,3 +2267,1014 @@ def test_adjust_intervals_should_force_rebuild(make_snapshot, mocker: MockerFixt (snapshot, intervals) = next(iter(backfill_stages[0].snapshot_to_intervals.items())) assert not snapshot.intervals assert intervals == [(to_timestamp("2023-01-01"), to_timestamp("2023-01-02"))] + + +def _make_mv( + make_snapshot, + name: str = "db.mv", + query: str = "SELECT 1 AS a", + nodes: t.Optional[t.Dict[str, t.Any]] = None, + category: SnapshotChangeCategory = SnapshotChangeCategory.BREAKING, + forward_only: bool = False, + previous_versions: t.Optional[t.Tuple[t.Any, ...]] = None, + unpaused: bool = False, + **model_kwargs: t.Any, +) -> Snapshot: + snapshot = make_snapshot( + SqlModel( + name=name, + query=parse_one(query), + kind=dict(name=ModelKindName.VIEW, materialized=True), + **model_kwargs, + ), + nodes=nodes, + ) + if previous_versions is not None: + snapshot.previous_versions = previous_versions + snapshot.categorize_as(category, forward_only=forward_only) + if unpaused: + snapshot.unpaused_ts = to_timestamp("2023-01-02") + return snapshot + + +def _make_prod_env( + snapshots: t.List[Snapshot], + plan_id: str = "prod_v1", + finalized: bool = True, + previous_finalized_snapshots: t.Optional[t.List[Snapshot]] = None, + expiration_ts: t.Optional[int] = None, +) -> Environment: + return Environment( + name="prod", + snapshots=[s.table_info for s in snapshots], + previous_finalized_snapshots=( + [s.table_info for s in previous_finalized_snapshots] + if previous_finalized_snapshots is not None + else None + ), + start_at="2023-01-01", + end_at="2023-01-02", + plan_id=plan_id, + finalized_ts=to_timestamp("2023-01-02") if finalized else None, + expiration_ts=expiration_ts, + ) + + +def _build_prod_plan_for_mv( + snapshots: t.List[Snapshot], + new_snapshots: t.List[Snapshot], + existing_environment: t.Optional[Environment], + stored_snapshots: t.Dict[SnapshotId, Snapshot], + mocker: MockerFixture, +) -> t.List[t.Any]: + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.side_effect = lambda ids: { + s_id: stored_snapshots[s_id] + for s_id in (x.snapshot_id for x in ids) + if s_id in stored_snapshots + } + state_reader.get_environment.return_value = existing_environment + + existing_name_versions = set() + if existing_environment: + for s in existing_environment.snapshots: + existing_name_versions.add((s.name, s.version)) + for s in existing_environment.previous_finalized_snapshots or []: + existing_name_versions.add((s.name, s.version)) + + def _refresh_intervals(snaps: t.Iterable[Snapshot]) -> t.List[Snapshot]: + refreshed = list(snaps) + for s in refreshed: + if s.is_model and not s.intervals and (s.name, s.version) in existing_name_versions: + s.add_interval("2023-01-01", "2023-01-02") + return refreshed + + state_reader.refresh_snapshot_intervals.side_effect = _refresh_intervals + + environment = Environment( + name="prod", + snapshots=[s.table_info for s in snapshots], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id=existing_environment.plan_id if existing_environment else None, + promoted_snapshot_ids=None, + ) + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=new_snapshots, + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=False, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=False, + ensure_finalized_snapshots=False, + ignore_cron=False, + directly_modified_snapshots=[], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[s.snapshot_id for s in new_snapshots if s.is_metadata], + removed_snapshots=[], + requires_backfill=False, + models_to_backfill=None, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + return build_plan_stages(plan, state_reader, None) + + +@pytest.mark.registry_isolation +@pytest.mark.parametrize( + "change_type", + ["tags", "owner", "sql_comment", "metadata_only_macro"], +) +def test_build_plan_stages_mv_metadata_only_skips_migrate( + make_snapshot, mocker: MockerFixture, change_type: str +) -> None: + from sqlmesh.core.dialect import parse as parse_sql + from sqlmesh.core.macros import macro + from sqlmesh.core.model import load_sql_based_model + + if change_type == "metadata_only_macro": + try: + macro.registry().pop("my_meta_macro", None) + + @macro(metadata_only=True) + def my_meta_macro(evaluator): # type: ignore + return "1" + + mv_v1 = make_snapshot( + load_sql_based_model( + parse_sql( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT @my_meta_macro() AS a" + ), + macros=macro.get_registry(), + ) + ) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + macro.registry().pop("my_meta_macro", None) + + @macro(metadata_only=True) + def my_meta_macro(evaluator): # type: ignore + _unused = 1 + return "1" + + mv_v2 = make_snapshot( + load_sql_based_model( + parse_sql( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT @my_meta_macro() AS a" + ), + macros=macro.get_registry(), + ) + ) + assert mv_v2.snapshot_id != mv_v1.snapshot_id + finally: + macro.registry().pop("my_meta_macro", None) + else: + base_sql = "MODEL (name db.mv, kind VIEW (materialized true)); SELECT 1 AS a" + mv_v1 = make_snapshot(load_sql_based_model(parse_sql(base_sql))) + mv_v1.categorize_as(SnapshotChangeCategory.BREAKING) + mv_v1.unpaused_ts = to_timestamp("2023-01-02") + + if change_type == "tags": + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true), tags ['analytics']); " + "SELECT 1 AS a" + ) + elif change_type == "owner": + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true), owner alice); SELECT 1 AS a" + ) + else: + updated_sql = ( + "MODEL (name db.mv, kind VIEW (materialized true)); " + "SELECT 1 AS a -- column doc comment" + ) + mv_v2 = make_snapshot(load_sql_based_model(parse_sql(updated_sql))) + + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + assert mv_v2.requires_schema_migration_in_prod + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=_make_prod_env([mv_v1], plan_id="prev_plan"), + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + assert not any(isinstance(s, MigrateSchemasStage) for s in stages) + + +@pytest.mark.parametrize( + "case,expect_migrate", + [ + ("unfinalized_forward_only_retry", True), + ("unfinalized_forward_only_revert_to_metadata", True), + ("unfinalized_metadata_retry", False), + ("never_finalized", True), + ("expired", True), + ], +) +def test_build_plan_stages_mv_unfinalized_or_expired_env( + make_snapshot, mocker: MockerFixture, case: str, expect_migrate: bool +) -> None: + mv_v1 = _make_mv(make_snapshot, unpaused=case != "never_finalized") + + if case == "unfinalized_forward_only_retry": + mv_v2 = _make_mv( + make_snapshot, + query="SELECT 2 AS a", + category=SnapshotChangeCategory.NON_BREAKING, + forward_only=True, + previous_versions=mv_v1.all_versions, + ) + existing_env = _make_prod_env( + [mv_v2], + plan_id="failed_plan", + finalized=False, + previous_finalized_snapshots=[mv_v1], + ) + candidate = mv_v2 + new_snapshots: t.List[Snapshot] = [] + stored = {mv_v1.snapshot_id: mv_v1, mv_v2.snapshot_id: mv_v2} + elif case == "unfinalized_forward_only_revert_to_metadata": + # Plan 1 ran MigrateSchemasStage with forward-only SQL `SELECT 2` and then failed before + # finalization. Plan 2 reverts to `SELECT 1` + metadata edit; it must migrate so the live + # warehouse MV is not left on Plan 1's SQL. + mv_failed_fo = _make_mv( + make_snapshot, + query="SELECT 2 AS a", + category=SnapshotChangeCategory.NON_BREAKING, + forward_only=True, + previous_versions=mv_v1.all_versions, + ) + mv_reverted = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_reverted.previous_versions = mv_v1.all_versions + mv_reverted.categorize_as(SnapshotChangeCategory.METADATA) + existing_env = _make_prod_env( + [mv_failed_fo], + plan_id="failed_plan", + finalized=False, + previous_finalized_snapshots=[mv_v1], + ) + candidate = mv_reverted + new_snapshots = [mv_reverted] + stored = {mv_v1.snapshot_id: mv_v1, mv_failed_fo.snapshot_id: mv_failed_fo} + else: + mv_v2 = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + candidate = mv_v2 + if case == "unfinalized_metadata_retry": + existing_env = _make_prod_env( + [mv_v2], + plan_id="failed_plan", + finalized=False, + previous_finalized_snapshots=[mv_v1], + ) + new_snapshots = [] + stored = {mv_v1.snapshot_id: mv_v1, mv_v2.snapshot_id: mv_v2} + elif case == "never_finalized": + existing_env = _make_prod_env( + [mv_v1], + plan_id="failed_initial", + finalized=False, + previous_finalized_snapshots=None, + ) + new_snapshots = [mv_v2] + stored = {mv_v1.snapshot_id: mv_v1} + else: + existing_env = _make_prod_env( + [mv_v1], + plan_id="expired_plan", + finalized=True, + expiration_ts=1, + ) + new_snapshots = [mv_v2] + stored = {mv_v1.snapshot_id: mv_v1} + + stages = _build_prod_plan_for_mv( + snapshots=[candidate], + new_snapshots=new_snapshots, + existing_environment=existing_env, + stored_snapshots=stored, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + if expect_migrate: + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [candidate.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + else: + assert len(migrate_stages) == 0 + + +def test_build_plan_stages_mv_unfinalized_grants_revert_syncs_grants( + make_snapshot, mocker: MockerFixture +) -> None: + from sqlmesh.core.model.meta import GrantsTargetLayer + + mv_v1 = _make_mv( + make_snapshot, + unpaused=True, + grants={"SELECT": ["role_a"]}, + grants_target_layer=GrantsTargetLayer.ALL, + ) + mv_failed_grants = make_snapshot(mv_v1.model.copy(update={"grants": {"SELECT": ["role_b"]}})) + mv_failed_grants.previous_versions = mv_v1.all_versions + mv_failed_grants.categorize_as(SnapshotChangeCategory.METADATA) + + mv_reverted = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_reverted.previous_versions = mv_v1.all_versions + mv_reverted.categorize_as(SnapshotChangeCategory.METADATA) + + existing_env = _make_prod_env( + [mv_failed_grants], + plan_id="failed_grants_plan", + finalized=False, + previous_finalized_snapshots=[mv_v1], + ) + stages = _build_prod_plan_for_mv( + snapshots=[mv_reverted], + new_snapshots=[mv_reverted], + existing_environment=existing_env, + stored_snapshots={mv_v1.snapshot_id: mv_v1, mv_failed_grants.snapshot_id: mv_failed_grants}, + mocker=mocker, + ) + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_reverted.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == {mv_reverted.snapshot_id} + assert migrate_stages[0].create_only_snapshot_ids == set() + + +def test_build_plan_stages_mv_metadata_only_with_backfill_routes_to_create_only( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = _make_mv(make_snapshot, unpaused=True) + mv_v2 = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_v2.previous_versions = mv_v1.all_versions + mv_v2.categorize_as(SnapshotChangeCategory.METADATA) + + # An unrelated model requires backfill, so PhysicalLayerUpdateStage is skipped. + # The metadata-only MV must be routed into create_only_snapshot_ids so it is created if missing + # without being recreated when it already exists. + other_model = make_snapshot( + SqlModel( + name="db.other", + query=parse_one("SELECT 1 AS x"), + kind=dict(name=ModelKindName.FULL), + start="2023-01-01", + ) + ) + other_model.categorize_as(SnapshotChangeCategory.BREAKING) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2, other_model], + new_snapshots=[mv_v2, other_model], + existing_environment=_make_prod_env([mv_v1]), + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + assert not any(isinstance(s, PhysicalLayerUpdateStage) for s in stages) + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == {mv_v2.snapshot_id} + + +def test_build_plan_stages_mv_stacked_dev_forward_only_plus_metadata_migrates( + make_snapshot, mocker: MockerFixture +) -> None: + mv_v1 = _make_mv(make_snapshot, unpaused=True) + + # Dev step 1: forward-only SQL change (never deployed to prod) + mv_v2 = _make_mv( + make_snapshot, + query="SELECT 2 AS a", + category=SnapshotChangeCategory.NON_BREAKING, + forward_only=True, + previous_versions=mv_v1.all_versions, + ) + + # Dev step 2: metadata-only change stacked on top of v2 + mv_v3 = make_snapshot(mv_v2.model.copy(update={"owner": "bob"})) + mv_v3.previous_versions = mv_v2.all_versions + mv_v3.categorize_as(SnapshotChangeCategory.METADATA) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v3], + new_snapshots=[], + existing_environment=_make_prod_env([mv_v1]), + stored_snapshots={mv_v1.snapshot_id: mv_v1, mv_v3.snapshot_id: mv_v3}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v3.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + + +@pytest.mark.parametrize( + "mode", + ["physical_version", "vde_dev_only"], +) +def test_build_plan_stages_mv_physical_version_and_vde_dev_only( + make_snapshot, mocker: MockerFixture, mode: str +) -> None: + kwargs: t.Dict[str, t.Any] = ( + {"physical_version": "v1"} + if mode == "physical_version" + else {"virtual_environment_mode": VirtualEnvironmentMode.DEV_ONLY} + ) + mv_v1 = _make_mv(make_snapshot, unpaused=True, **kwargs) + existing_prod = _make_prod_env([mv_v1]) + + # Metadata-only change: must skip MigrateSchemasStage + mv_meta = make_snapshot(mv_v1.model.copy(update={"owner": "alice"})) + mv_meta.previous_versions = mv_v1.all_versions + mv_meta.categorize_as(SnapshotChangeCategory.METADATA) + + stages_meta = _build_prod_plan_for_mv( + snapshots=[mv_meta], + new_snapshots=[mv_meta], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + assert not any(isinstance(s, MigrateSchemasStage) for s in stages_meta) + + # Data change (or physical_version bump): must still emit MigrateSchemasStage + changed_kwargs: t.Dict[str, t.Any] = ( + {"physical_version": "v2"} + if mode == "physical_version" + else {"virtual_environment_mode": VirtualEnvironmentMode.DEV_ONLY} + ) + mv_changed = _make_mv( + make_snapshot, + query="SELECT 1 AS a" if mode == "physical_version" else "SELECT 2 AS a", + previous_versions=mv_v1.all_versions, + **changed_kwargs, + ) + + stages_changed = _build_prod_plan_for_mv( + snapshots=[mv_changed], + new_snapshots=[mv_changed], + existing_environment=existing_prod, + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + migrate_stages = [s for s in stages_changed if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_changed.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + + +@pytest.mark.parametrize( + "old_grants,old_layer,new_grants,new_layer,vde_mode,expect_grants_only", + [ + # Add physical grants + (None, "physical", {"select": ["u1"]}, "physical", VirtualEnvironmentMode.FULL, True), + # Add grants targeting ALL layers + (None, "all", {"select": ["u1"]}, "all", VirtualEnvironmentMode.FULL, True), + # Update physical grants + ( + {"select": ["u1"]}, + "physical", + {"select": ["u2"]}, + "physical", + VirtualEnvironmentMode.FULL, + True, + ), + # Revoke all physical grants ({} != None) + ({"select": ["u1"]}, "physical", {}, "physical", VirtualEnvironmentMode.FULL, True), + # Switch grants_target_layer from virtual -> physical + ( + {"select": ["u1"]}, + "virtual", + {"select": ["u1"]}, + "physical", + VirtualEnvironmentMode.FULL, + True, + ), + # VDE=DEV_ONLY with virtual layer still targets physical in prod + ( + None, + "virtual", + {"select": ["u1"]}, + "virtual", + VirtualEnvironmentMode.DEV_ONLY, + True, + ), + # Unchanged physical grants (only owner changed) -> skip MigrateSchemasStage + ( + {"select": ["u1"]}, + "physical", + {"select": ["u1"]}, + "physical", + VirtualEnvironmentMode.FULL, + False, + ), + # Virtual-only grants change under FULL VDE -> handled in virtual layer only + ( + None, + "virtual", + {"select": ["u1"]}, + "virtual", + VirtualEnvironmentMode.FULL, + False, + ), + ], +) +def test_build_plan_stages_mv_grants_only_sync( + make_snapshot, + mocker: MockerFixture, + old_grants: t.Optional[t.Dict[str, t.List[str]]], + old_layer: str, + new_grants: t.Optional[t.Dict[str, t.List[str]]], + new_layer: str, + vde_mode: VirtualEnvironmentMode, + expect_grants_only: bool, +) -> None: + from sqlmesh.core.model.meta import GrantsTargetLayer + + v1_kwargs: t.Dict[str, t.Any] = { + "grants_target_layer": GrantsTargetLayer(old_layer), + "virtual_environment_mode": vde_mode, + } + if old_grants is not None: + v1_kwargs["grants"] = old_grants + + mv_v1 = _make_mv(make_snapshot, unpaused=True, **v1_kwargs) + + v2_kwargs: t.Dict[str, t.Any] = { + "grants_target_layer": GrantsTargetLayer(new_layer), + "virtual_environment_mode": vde_mode, + "owner": "alice", + } + if new_grants is not None: + v2_kwargs["grants"] = new_grants + + mv_v2 = _make_mv( + make_snapshot, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_v1.all_versions, + **v2_kwargs, + ) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=_make_prod_env([mv_v1]), + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + if expect_grants_only: + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == {mv_v2.snapshot_id} + assert migrate_stages[0].create_only_snapshot_ids == set() + else: + assert len(migrate_stages) == 0 + + +def test_build_plan_stages_mv_upstream_subdag_create_only( + make_snapshot, mocker: MockerFixture +) -> None: + mv_upstream = _make_mv( + make_snapshot, + name="db.mv_upstream", + query="SELECT 1 AS a, '2023-01-01' AS ds", + ) + # Sibling downstream MV that should NOT be cascaded into MigrateSchemasStage + mv_sibling = _make_mv( + make_snapshot, + name="db.mv_sibling", + query="SELECT a FROM db.mv_upstream", + nodes={mv_upstream.name: mv_upstream.model}, + ) + downstream_fo = make_snapshot( + SqlModel( + name="db.downstream_fo", + query=parse_one("SELECT a, ds FROM db.mv_upstream"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ), + nodes={mv_upstream.name: mv_upstream.model}, + ) + downstream_fo.categorize_as(SnapshotChangeCategory.BREAKING) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_upstream, mv_sibling, downstream_fo], + new_snapshots=[mv_upstream, mv_sibling, downstream_fo], + existing_environment=None, + stored_snapshots={}, + mocker=mocker, + ) + + migrate_stage = next(s for s in stages if isinstance(s, MigrateSchemasStage)) + assert {s.snapshot_id for s in migrate_stage.snapshots} == { + mv_upstream.snapshot_id, + downstream_fo.snapshot_id, + } + assert migrate_stage.create_only_snapshot_ids == {mv_upstream.snapshot_id} + assert migrate_stage.grants_only_snapshot_ids == set() + + +def test_build_plan_stages_mv_cascade_override_from_upstream_regular_view( + make_snapshot, mocker: MockerFixture +) -> None: + from sqlmesh.core.model.meta import GrantsTargetLayer + + v_up_v1 = make_snapshot( + SqlModel( + name="db.v_up", + query=parse_one("SELECT 1 AS a, '2023-01-01' AS ds"), + kind=dict(name=ModelKindName.VIEW), + ) + ) + v_up_v1.categorize_as(SnapshotChangeCategory.BREAKING) + v_up_v1.unpaused_ts = to_timestamp("2023-01-02") + + mv_meta_v1 = _make_mv( + make_snapshot, + name="db.mv_meta", + query="SELECT a FROM db.v_up", + nodes={v_up_v1.name: v_up_v1.model}, + unpaused=True, + ) + mv_grants_v1 = _make_mv( + make_snapshot, + name="db.mv_grants", + query="SELECT a FROM db.v_up", + nodes={v_up_v1.name: v_up_v1.model}, + unpaused=True, + grants_target_layer=GrantsTargetLayer.PHYSICAL, + ) + mv_create_only_v1 = _make_mv( + make_snapshot, + name="db.mv_create_only", + query="SELECT a, ds FROM db.v_up", + nodes={v_up_v1.name: v_up_v1.model}, + unpaused=True, + ) + tbl_fo_v1 = make_snapshot( + SqlModel( + name="db.tbl_fo", + query=parse_one("SELECT a, ds FROM db.mv_create_only"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ), + nodes={v_up_v1.name: v_up_v1.model, mv_create_only_v1.name: mv_create_only_v1.model}, + ) + tbl_fo_v1.categorize_as(SnapshotChangeCategory.BREAKING) + tbl_fo_v1.unpaused_ts = to_timestamp("2023-01-02") + + # Upstream regular VIEW gets a metadata-only change -> still migrated (not materialized) + v_up_v2 = make_snapshot(v_up_v1.model.copy(update={"owner": "alice"})) + v_up_v2.previous_versions = v_up_v1.all_versions + v_up_v2.categorize_as(SnapshotChangeCategory.METADATA) + + # Downstream MVs would otherwise be skipped / grants_only / create_only + mv_meta_v2 = _make_mv( + make_snapshot, + name="db.mv_meta", + query="SELECT a FROM db.v_up", + nodes={v_up_v2.name: v_up_v2.model}, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_meta_v1.all_versions, + ) + mv_grants_v2 = _make_mv( + make_snapshot, + name="db.mv_grants", + query="SELECT a FROM db.v_up", + nodes={v_up_v2.name: v_up_v2.model}, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_grants_v1.all_versions, + grants={"select": ["u1"]}, + grants_target_layer=GrantsTargetLayer.PHYSICAL, + ) + mv_create_only_v2 = _make_mv( + make_snapshot, + name="db.mv_create_only", + query="SELECT a, ds FROM db.v_up", + nodes={v_up_v2.name: v_up_v2.model}, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_create_only_v1.all_versions, + ) + tbl_fo_v2 = make_snapshot( + SqlModel( + name="db.tbl_fo", + query=parse_one("SELECT a, a AS b, ds FROM db.mv_create_only"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ), + nodes={v_up_v2.name: v_up_v2.model, mv_create_only_v2.name: mv_create_only_v2.model}, + ) + tbl_fo_v2.previous_versions = tbl_fo_v1.all_versions + tbl_fo_v2.categorize_as(SnapshotChangeCategory.NON_BREAKING, forward_only=True) + + existing_prod = _make_prod_env( + [v_up_v1, mv_meta_v1, mv_grants_v1, mv_create_only_v1, tbl_fo_v1] + ) + new_snaps = [v_up_v2, mv_meta_v2, mv_grants_v2, mv_create_only_v2, tbl_fo_v2] + stored = { + s.snapshot_id: s for s in (v_up_v1, mv_meta_v1, mv_grants_v1, mv_create_only_v1, tbl_fo_v1) + } + + stages = _build_prod_plan_for_mv( + snapshots=new_snaps, + new_snapshots=new_snaps, + existing_environment=existing_prod, + stored_snapshots=stored, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + migrate_stage = migrate_stages[0] + assert {s.snapshot_id for s in migrate_stage.snapshots} == {s.snapshot_id for s in new_snaps} + assert migrate_stage.grants_only_snapshot_ids == set() + assert migrate_stage.create_only_snapshot_ids == set() + + +def test_build_plan_stages_mv_upstream_metadata_only_propagates_without_recreate( + make_snapshot, mocker: MockerFixture +) -> None: + src_v1 = make_snapshot( + SqlModel( + name="db.src", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.FULL), + ) + ) + src_v1.categorize_as(SnapshotChangeCategory.BREAKING) + src_v1.unpaused_ts = to_timestamp("2023-01-02") + + mv_v1 = _make_mv( + make_snapshot, + query="SELECT a FROM db.src", + nodes={src_v1.name: src_v1.model}, + unpaused=True, + ) + + src_v2 = make_snapshot(src_v1.model.copy(update={"owner": "alice", "tags": ["core"]})) + src_v2.previous_versions = src_v1.all_versions + src_v2.categorize_as(SnapshotChangeCategory.METADATA) + + mv_v2 = _make_mv( + make_snapshot, + query="SELECT a FROM db.src", + nodes={src_v2.name: src_v2.model}, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_v1.all_versions, + ) + assert mv_v2.requires_schema_migration_in_prod + + stages = _build_prod_plan_for_mv( + snapshots=[src_v2, mv_v2], + new_snapshots=[src_v2, mv_v2], + existing_environment=_make_prod_env([src_v1, mv_v1]), + stored_snapshots={src_v1.snapshot_id: src_v1, mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [src_v2.snapshot_id] + assert mv_v2.snapshot_id not in {s.snapshot_id for s in migrate_stages[0].snapshots} + + +@pytest.mark.parametrize( + "ddl_update", + [ + {"physical_properties": {"storage_tier": parse_one("'hot'")}}, + {"clustered_by": ["a"]}, + {"partitioned_by": ["ds"]}, + ], +) +def test_build_plan_stages_mv_non_sql_physical_ddl_change_migrates( + make_snapshot, mocker: MockerFixture, ddl_update: t.Dict[str, t.Any] +) -> None: + mv_v1 = _make_mv( + make_snapshot, + query="SELECT 1 AS a, '2023-01-01' AS ds", + unpaused=True, + ) + mv_v2 = _make_mv( + make_snapshot, + query="SELECT 1 AS a, '2023-01-01' AS ds", + category=SnapshotChangeCategory.NON_BREAKING, + forward_only=True, + previous_versions=mv_v1.all_versions, + **ddl_update, + ) + assert mv_v2.table_name(is_deployable=True) == mv_v1.table_name(is_deployable=True) + + stages = _build_prod_plan_for_mv( + snapshots=[mv_v2], + new_snapshots=[mv_v2], + existing_environment=_make_prod_env([mv_v1]), + stored_snapshots={mv_v1.snapshot_id: mv_v1}, + mocker=mocker, + ) + + migrate_stages = [s for s in stages if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [mv_v2.snapshot_id] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + + +def test_build_plan_stages_mv_transitive_embedded_parent( + make_snapshot, mocker: MockerFixture +) -> None: + base_v1 = make_snapshot( + SqlModel( + name="db.base_tbl", + query=parse_one("SELECT 1 AS a"), + kind=dict(name=ModelKindName.FULL), + ) + ) + base_v1.categorize_as(SnapshotChangeCategory.BREAKING) + base_v1.version = "v1" + base_v1.unpaused_ts = to_timestamp("2023-01-02") + + embedded_v1 = make_snapshot( + SqlModel( + name="db.embedded", + query=parse_one("SELECT a FROM db.base_tbl"), + kind=dict(name=ModelKindName.EMBEDDED), + ), + nodes={base_v1.name: base_v1.model}, + ) + embedded_v1.categorize_as(SnapshotChangeCategory.BREAKING) + embedded_v1.unpaused_ts = to_timestamp("2023-01-02") + + mv_v1 = _make_mv( + make_snapshot, + query="SELECT a FROM db.embedded", + nodes={base_v1.name: base_v1.model, embedded_v1.name: embedded_v1.model}, + unpaused=True, + ) + + existing_prod = _make_prod_env([base_v1, embedded_v1, mv_v1]) + + # Case (a): Base table unchanged, MV metadata-only change -> MV is NOT recreated + mv_meta = make_snapshot( + mv_v1.model.copy(update={"owner": "alice"}), + nodes={base_v1.name: base_v1.model, embedded_v1.name: embedded_v1.model}, + ) + mv_meta.previous_versions = mv_v1.all_versions + mv_meta.categorize_as(SnapshotChangeCategory.METADATA) + + stages_unchanged = _build_prod_plan_for_mv( + snapshots=[base_v1, embedded_v1, mv_meta], + new_snapshots=[mv_meta], + existing_environment=existing_prod, + stored_snapshots={ + base_v1.snapshot_id: base_v1, + embedded_v1.snapshot_id: embedded_v1, + mv_v1.snapshot_id: mv_v1, + }, + mocker=mocker, + ) + assert not any(isinstance(s, MigrateSchemasStage) for s in stages_unchanged) + + # Case (b): Base table deployable table_name changed (same data_hash, different version) + # -> transitive check through EMBEDDED detects table_name change and migrates MV + base_v2 = make_snapshot(base_v1.model.copy(update={"owner": "bob"})) + base_v2.previous_versions = base_v1.all_versions + base_v2.categorize_as(SnapshotChangeCategory.BREAKING) + base_v2.version = "v2" + assert base_v2.fingerprint.data_hash == base_v1.fingerprint.data_hash + assert base_v2.table_name(is_deployable=True) != base_v1.table_name(is_deployable=True) + + embedded_v2 = make_snapshot( + embedded_v1.model, + nodes={base_v2.name: base_v2.model}, + ) + embedded_v2.previous_versions = embedded_v1.all_versions + embedded_v2.categorize_as(SnapshotChangeCategory.METADATA) + + mv_v2 = _make_mv( + make_snapshot, + query="SELECT a FROM db.embedded", + nodes={base_v2.name: base_v2.model, embedded_v2.name: embedded_v2.model}, + category=SnapshotChangeCategory.METADATA, + previous_versions=mv_v1.all_versions, + ) + assert mv_v2.fingerprint.parent_data_hash == mv_v1.fingerprint.parent_data_hash + assert mv_v2.table_name(is_deployable=True) == mv_v1.table_name(is_deployable=True) + + stages_changed = _build_prod_plan_for_mv( + snapshots=[base_v2, embedded_v2, mv_v2], + new_snapshots=[base_v2, embedded_v2, mv_v2], + existing_environment=existing_prod, + stored_snapshots={ + base_v1.snapshot_id: base_v1, + embedded_v1.snapshot_id: embedded_v1, + mv_v1.snapshot_id: mv_v1, + }, + mocker=mocker, + ) + migrate_stages = [s for s in stages_changed if isinstance(s, MigrateSchemasStage)] + assert len(migrate_stages) == 1 + assert [s.snapshot_id for s in migrate_stages[0].snapshots] == [ + base_v2.snapshot_id, + mv_v2.snapshot_id, + ] + assert migrate_stages[0].grants_only_snapshot_ids == set() + assert migrate_stages[0].create_only_snapshot_ids == set() + + +def test_plan_explainer_migrate_schemas_stage_grants_and_create_only( + make_snapshot, +) -> None: + from rich.console import Console as RichConsole + from sqlmesh.core.environment import EnvironmentNamingInfo + from sqlmesh.core.plan.explainer import RichExplainerConsole + + mv_grants = _make_mv(make_snapshot, name="db.mv_grants") + mv_create_only = _make_mv(make_snapshot, name="db.mv_create_only") + tbl_migrated = make_snapshot( + SqlModel( + name="db.tbl_migrated", + query=parse_one("SELECT 1 AS a, '2023-01-01' AS ds"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, time_column="ds", forward_only=True + ), + ) + ) + tbl_migrated.categorize_as(SnapshotChangeCategory.BREAKING) + + explainer = RichExplainerConsole( + environment_naming_info=EnvironmentNamingInfo(name="prod"), + dialect="duckdb", + default_catalog=None, + console=RichConsole(record=True), + ) + + # 1. Grants-only stage: header already says "Sync grants", child omits redundant suffix + grants_stage = MigrateSchemasStage( + snapshots=[mv_grants], + all_snapshots={mv_grants.snapshot_id: mv_grants}, + deployability_index=DeployabilityIndex.all_deployable(), + grants_only_snapshot_ids={mv_grants.snapshot_id}, + ) + grants_tree = explainer.visit_migrate_schemas_stage(grants_stage) + assert grants_tree is not None + assert "Sync grants" in str(grants_tree.label) + assert len(grants_tree.children) == 1 + assert "mv_grants" in str(grants_tree.children[0].label) + assert "(sync grants)" not in str(grants_tree.children[0].label) + + # 2. Mixed stage: regular migration + grants-only + create-only (create-only hidden) + mixed_stage = MigrateSchemasStage( + snapshots=[mv_create_only, mv_grants, tbl_migrated], + all_snapshots={s.snapshot_id: s for s in (mv_create_only, mv_grants, tbl_migrated)}, + deployability_index=DeployabilityIndex.all_deployable(), + grants_only_snapshot_ids={mv_grants.snapshot_id}, + create_only_snapshot_ids={mv_create_only.snapshot_id}, + ) + mixed_tree = explainer.visit_migrate_schemas_stage(mixed_stage) + assert mixed_tree is not None + assert "Update schemas" in str(mixed_tree.label) + child_labels = [str(c.label) for c in mixed_tree.children] + assert len(child_labels) == 2 + assert any("mv_grants" in lbl and "(sync grants)" in lbl for lbl in child_labels) + assert any("tbl_migrated" in lbl and "(sync grants)" not in lbl for lbl in child_labels) + assert not any("mv_create_only" in lbl for lbl in child_labels) + + # 3. Create-only stage returns None + create_only_stage = MigrateSchemasStage( + snapshots=[mv_create_only], + all_snapshots={mv_create_only.snapshot_id: mv_create_only}, + deployability_index=DeployabilityIndex.all_deployable(), + create_only_snapshot_ids={mv_create_only.snapshot_id}, + ) + assert explainer.visit_migrate_schemas_stage(create_only_stage) is None diff --git a/tests/core/test_snapshot_evaluator.py b/tests/core/test_snapshot_evaluator.py index 0955af331d..fc64a7d64f 100644 --- a/tests/core/test_snapshot_evaluator.py +++ b/tests/core/test_snapshot_evaluator.py @@ -6113,3 +6113,165 @@ def observer(phase, facts, error): consumer.reset(token) action = "schema_migration" if operation == "migrate" else operation assert events == [("start", action, None), ("finish", action, None)] + + +@pytest.mark.parametrize( + "grants_config", + [ + {"select": ["user1"]}, + {}, + ], +) +def test_migrate_grants_only_snapshot_ids( + mocker: MockerFixture, adapter_mock, make_snapshot, grants_config +): + from sqlmesh.core.model.meta import GrantsTargetLayer + + adapter_mock.SUPPORTS_GRANTS = True + sync_grants_mock = mocker.patch.object(adapter_mock, "sync_grants_config") + + model = SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=ViewKind(materialized=True), + grants=grants_config, + grants_target_layer=GrantsTargetLayer.PHYSICAL, + pre_statements=[parse_one("SELECT 'pre'")], + post_statements=[parse_one("SELECT 'post'")], + ) + snapshot = make_snapshot(model, version="1") + snapshot.categorize_as(SnapshotChangeCategory.METADATA) + + evaluator = SnapshotEvaluator(adapter_mock) + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + snapshot.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__mv__1", + type=DataObjectType.MATERIALIZED_VIEW, + ) + }, + ) + + evaluator.migrate( + [snapshot], + {snapshot.snapshot_id: snapshot}, + grants_only_snapshot_ids={snapshot.snapshot_id}, + ) + + sync_grants_mock.assert_called_once_with( + exp.to_table(snapshot.table_name(), dialect=adapter_mock.dialect), + grants_config, + DataObjectType.MATERIALIZED_VIEW, + ) + adapter_mock.create_view.assert_not_called() + adapter_mock.drop_view.assert_not_called() + adapter_mock.drop_table.assert_not_called() + adapter_mock.drop_data_object_on_type_mismatch.assert_not_called() + adapter_mock.execute.assert_not_called() + + +def test_migrate_create_only_snapshot_ids_skips_when_exists_creates_when_missing( + mocker: MockerFixture, adapter_mock, make_snapshot +): + mv_model = SqlModel( + name="db.mv", + query=parse_one("SELECT 1 AS a"), + kind=ViewKind(materialized=True), + pre_statements=[parse_one("SELECT 'pre'")], + post_statements=[parse_one("SELECT 'post'")], + ) + mv_snapshot = make_snapshot(mv_model, version="1") + mv_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + evaluator = SnapshotEvaluator(adapter_mock) + migrate_snapshot_spy = mocker.spy(evaluator, "_migrate_snapshot") + + # Case 1: Physical MV already exists -> complete no-op and _migrate_snapshot is skipped + # (preventing spurious schema_migration observer events) + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + mv_snapshot.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__mv__1", + type=DataObjectType.MATERIALIZED_VIEW, + ) + }, + ) + evaluator.migrate( + [mv_snapshot], + {mv_snapshot.snapshot_id: mv_snapshot}, + create_only_snapshot_ids={mv_snapshot.snapshot_id}, + ) + migrate_snapshot_spy.assert_not_called() + adapter_mock.create_view.assert_not_called() + adapter_mock.drop_view.assert_not_called() + adapter_mock.drop_data_object_on_type_mismatch.assert_not_called() + adapter_mock.execute.assert_not_called() + + # Case 2: Physical MV is missing while downstream exists -> falls through to _execute_create + downstream = make_snapshot( + SqlModel( + name="db.downstream", + query=parse_one("SELECT a FROM db.mv"), + kind=FullKind(), + ), + nodes={mv_snapshot.name: mv_snapshot.model}, + version="1", + ) + downstream.categorize_as(SnapshotChangeCategory.BREAKING) + mocker.patch.object( + evaluator, + "_get_physical_data_objects", + return_value={ + downstream.snapshot_id: DataObject( + schema="sqlmesh__db", + name="db__downstream__1", + type=DataObjectType.TABLE, + ) + }, + ) + execute_create_spy = mocker.spy(evaluator, "_execute_create") + mocker.patch.object(evaluator, "_migrate_target_table") + adapter_mock.drop_data_object_on_type_mismatch.return_value = False + adapter_mock.table_exists.return_value = False + + evaluator.migrate( + [mv_snapshot, downstream], + {mv_snapshot.snapshot_id: mv_snapshot, downstream.snapshot_id: downstream}, + create_only_snapshot_ids={mv_snapshot.snapshot_id}, + ) + + assert [c.args[0].snapshot_id for c in migrate_snapshot_spy.call_args_list] == [ + mv_snapshot.snapshot_id, + downstream.snapshot_id, + ] + assert execute_create_spy.call_count == 1 + assert execute_create_spy.call_args.kwargs["snapshot"].snapshot_id == mv_snapshot.snapshot_id + adapter_mock.create_view.assert_called_once() + assert adapter_mock.create_view.call_args.args[0] == mv_snapshot.table_name(is_deployable=True) + assert adapter_mock.create_view.call_args.kwargs["materialized"] is True + + # Case 3: Physical inventory is completely empty -> still dispatches to create missing MV + migrate_snapshot_spy.reset_mock() + execute_create_spy.reset_mock() + adapter_mock.create_view.reset_mock() + mocker.patch.object(evaluator, "_get_physical_data_objects", return_value={}) + + evaluator.migrate( + [mv_snapshot], + {mv_snapshot.snapshot_id: mv_snapshot}, + create_only_snapshot_ids={mv_snapshot.snapshot_id}, + ) + + assert [c.args[0].snapshot_id for c in migrate_snapshot_spy.call_args_list] == [ + mv_snapshot.snapshot_id, + ] + assert execute_create_spy.call_count == 1 + adapter_mock.create_view.assert_called_once() + assert adapter_mock.create_view.call_args.args[0] == mv_snapshot.table_name(is_deployable=True) + assert adapter_mock.create_view.call_args.kwargs["materialized"] is True