Skip to content

Commit 01a6725

Browse files
fix(plan): avoid recreating materialized views on metadata-only changes
Signed-off-by: Sruthi <codewithsruthi@users.noreply.github.com>
1 parent 1f96a72 commit 01a6725

7 files changed

Lines changed: 1681 additions & 49 deletions

File tree

‎sqlmesh/core/plan/evaluator.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,8 @@ def visit_migrate_schemas_stage(
382382
allow_destructive_snapshots=plan.allow_destructive_models,
383383
allow_additive_snapshots=plan.allow_additive_models,
384384
deployability_index=stage.deployability_index,
385+
grants_only_snapshot_ids=stage.grants_only_snapshot_ids,
386+
create_only_snapshot_ids=stage.create_only_snapshot_ids,
385387
)
386388
except NodeExecutionFailedError as ex:
387389
raise PlanError(str(ex.__cause__) if ex.__cause__ else str(ex))

‎sqlmesh/core/plan/explainer.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -315,14 +315,35 @@ def visit_backfill_stage(self, stage: stages.BackfillStage) -> Tree:
315315
tree.add(f"{display_name} \\[standalone audit]")
316316
return tree
317317

318-
def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> Tree:
319-
tree = Tree(
320-
"[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]"
321-
)
318+
def visit_migrate_schemas_stage(self, stage: stages.MigrateSchemasStage) -> t.Optional[Tree]:
319+
migrated_snapshots = [
320+
s
321+
for s in stage.snapshots
322+
if s.snapshot_id not in stage.grants_only_snapshot_ids
323+
and s.snapshot_id not in stage.create_only_snapshot_ids
324+
]
325+
grants_only_snapshots = [
326+
s for s in stage.snapshots if s.snapshot_id in stage.grants_only_snapshot_ids
327+
]
328+
if not migrated_snapshots and not grants_only_snapshots:
329+
return None
330+
331+
if migrated_snapshots:
332+
tree = Tree(
333+
"[bold]Update schemas (add, drop, alter columns) of production physical tables to reflect forward-only changes[/bold]"
334+
)
335+
else:
336+
tree = Tree("[bold]Sync grants on production physical tables[/bold]")
337+
322338
for snapshot in stage.snapshots:
339+
if snapshot.snapshot_id in stage.create_only_snapshot_ids:
340+
continue
323341
display_name = self._display_name(snapshot)
324342
table_name = snapshot.table_name(True)
325-
tree.add(f"{display_name} -> {table_name}")
343+
if migrated_snapshots and snapshot.snapshot_id in stage.grants_only_snapshot_ids:
344+
tree.add(f"{display_name} -> {table_name} (sync grants)")
345+
else:
346+
tree.add(f"{display_name} -> {table_name}")
326347
return tree
327348

328349
def visit_virtual_layer_update_stage(self, stage: stages.VirtualLayerUpdateStage) -> Tree:

‎sqlmesh/core/plan/stages.py‎

Lines changed: 179 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from __future__ import annotations
2+
13
import typing as t
24

3-
from dataclasses import dataclass
5+
from dataclasses import dataclass, field
46
from sqlmesh.core import constants as c
57
from sqlmesh.core.environment import EnvironmentStatements, EnvironmentNamingInfo, Environment
68
from sqlmesh.core.plan.common import should_force_rebuild
@@ -14,6 +16,7 @@
1416
SnapshotId,
1517
snapshots_to_dag,
1618
)
19+
from sqlmesh.utils.dag import DAG
1720
from sqlmesh.utils.errors import PlanError
1821

1922

@@ -154,11 +157,17 @@ class MigrateSchemasStage:
154157
snapshots: Snapshots to migrate schemas for.
155158
all_snapshots: All snapshots in the plan by snapshot ID.
156159
deployability_index: Deployability index for this stage.
160+
grants_only_snapshot_ids: Snapshot IDs that only need physical grants synchronized
161+
without recreating or altering their physical objects.
162+
create_only_snapshot_ids: Snapshot IDs that should only be created if their physical
163+
object does not yet exist, without being migrated or recreated if it already exists.
157164
"""
158165

159166
snapshots: t.List[Snapshot]
160167
all_snapshots: t.Dict[SnapshotId, Snapshot]
161168
deployability_index: DeployabilityIndex
169+
grants_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set)
170+
create_only_snapshot_ids: t.Set[SnapshotId] = field(default_factory=set)
162171

163172

164173
@dataclass
@@ -263,7 +272,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
263272
if plan.is_dev:
264273
before_promote_snapshots = all_selected_for_backfill_snapshots
265274
after_promote_snapshots = set()
266-
snapshots_with_schema_migration = []
267275
else:
268276
before_promote_snapshots = {
269277
s.snapshot_id
@@ -274,30 +282,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
274282
after_promote_snapshots = all_selected_for_backfill_snapshots - before_promote_snapshots
275283
deployability_index = DeployabilityIndex.all_deployable()
276284

277-
snapshot_ids_with_schema_migration = [
278-
s.snapshot_id for s in snapshots.values() if s.requires_schema_migration_in_prod
279-
]
280-
# Include all upstream dependencies of snapshots that require schema migration to make sure
281-
# the upstream tables are created before the schema updates are applied
282-
snapshot_ids_to_migrate = set(dag.subdag(*snapshot_ids_with_schema_migration))
283-
# Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE,
284-
# so those are migrated too to be recreated
285-
for s_id in dag:
286-
snapshot = snapshots[s_id]
287-
if snapshot.is_view and any(
288-
p_id in snapshot_ids_to_migrate
289-
and snapshots[p_id].is_view
290-
and snapshots[p_id].supports_schema_migration_in_prod
291-
for p_id in snapshot.parents
292-
):
293-
snapshot_ids_to_migrate.add(s_id)
294-
snapshots_with_schema_migration = [
295-
snapshots[s_id]
296-
for s_id in dag
297-
if s_id in snapshot_ids_to_migrate
298-
and snapshots[s_id].supports_schema_migration_in_prod
299-
]
300-
301285
snapshots_to_intervals = self._missing_intervals(
302286
plan, snapshots_by_name, deployability_index
303287
)
@@ -387,14 +371,12 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
387371
)
388372
)
389373

390-
if snapshots_with_schema_migration:
391-
stages.append(
392-
MigrateSchemasStage(
393-
snapshots=snapshots_with_schema_migration,
394-
all_snapshots=snapshots,
395-
deployability_index=deployability_index,
396-
)
374+
if not plan.is_dev:
375+
migrate_schemas_stage = self._get_migrate_schemas_stage(
376+
snapshots, dag, existing_environment, deployability_index, needs_backfill
397377
)
378+
if migrate_schemas_stage:
379+
stages.append(migrate_schemas_stage)
398380

399381
if not plan.is_dev and not plan.ensure_finalized_snapshots and promoted_snapshots:
400382
# 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(
507489
deployability_index=deployability_index,
508490
)
509491

492+
def _get_migrate_schemas_stage(
493+
self,
494+
snapshots: t.Dict[SnapshotId, Snapshot],
495+
dag: DAG[SnapshotId],
496+
existing_environment: t.Optional[Environment],
497+
deployability_index: DeployabilityIndex,
498+
needs_backfill: bool,
499+
) -> t.Optional[MigrateSchemasStage]:
500+
if existing_environment and not existing_environment.expired:
501+
if existing_environment.finalized_ts:
502+
prod_baselines: t.List[t.Dict[str, SnapshotTableInfo]] = [
503+
{s.name: s for s in existing_environment.snapshots}
504+
]
505+
elif existing_environment.previous_finalized_snapshots:
506+
# Unfinalized prod environment: the previous failed plan may have stopped either
507+
# before or after MigrateSchemasStage, so the live physical MV could match either
508+
# previous_finalized_snapshots or existing_environment.snapshots. Only skip
509+
# recreation when the candidate matches both baselines.
510+
prod_baselines = [
511+
{s.name: s for s in existing_environment.previous_finalized_snapshots},
512+
{s.name: s for s in existing_environment.snapshots},
513+
]
514+
else:
515+
prod_baselines = []
516+
else:
517+
prod_baselines = []
518+
519+
candidate_mv_old_ids: t.Set[SnapshotId] = {
520+
baseline[s.name].snapshot_id
521+
for s in snapshots.values()
522+
if s.requires_schema_migration_in_prod and s.is_materialized_view
523+
for baseline in prod_baselines
524+
if s.name in baseline
525+
}
526+
old_snapshots_by_id: t.Dict[SnapshotId, Snapshot] = {}
527+
if candidate_mv_old_ids:
528+
missing_old_ids = [s_id for s_id in candidate_mv_old_ids if s_id not in snapshots]
529+
fetched_old_snapshots = (
530+
self.state_reader.get_snapshots(missing_old_ids) if missing_old_ids else {}
531+
)
532+
for s_id in candidate_mv_old_ids:
533+
old_snapshot = snapshots.get(s_id) or fetched_old_snapshots.get(s_id)
534+
if old_snapshot:
535+
old_snapshots_by_id[s_id] = old_snapshot
536+
537+
def _matches_baseline(s: Snapshot, baseline: t.Dict[str, SnapshotTableInfo]) -> bool:
538+
existing = baseline.get(s.name)
539+
if existing is None or not existing.is_model or existing.is_symbolic:
540+
return False
541+
if existing.table_name(is_deployable=True) != s.table_name(is_deployable=True):
542+
return False
543+
old = old_snapshots_by_id.get(existing.snapshot_id)
544+
if old is not None:
545+
if not old.is_model or s.is_directly_modified(old):
546+
return False
547+
elif existing.fingerprint.data_hash != s.fingerprint.data_hash:
548+
return False
549+
if existing.fingerprint.parent_data_hash != s.fingerprint.parent_data_hash:
550+
return False
551+
parents_to_check = list(s.parents)
552+
visited_parents: t.Set[SnapshotId] = set()
553+
while parents_to_check:
554+
p_id = parents_to_check.pop()
555+
if p_id in visited_parents:
556+
continue
557+
visited_parents.add(p_id)
558+
parent = snapshots.get(p_id)
559+
if parent is None:
560+
return False
561+
if parent.is_symbolic:
562+
parents_to_check.extend(parent.parents)
563+
continue
564+
if not parent.is_model:
565+
return False
566+
existing_parent = baseline.get(parent.name)
567+
if (
568+
existing_parent is None
569+
or not existing_parent.is_model
570+
or existing_parent.is_symbolic
571+
or existing_parent.table_name(is_deployable=True)
572+
!= parent.table_name(is_deployable=True)
573+
):
574+
return False
575+
return True
576+
577+
def _is_metadata_only_in_prod(s: Snapshot) -> bool:
578+
return bool(prod_baselines) and all(
579+
_matches_baseline(s, baseline) for baseline in prod_baselines
580+
)
581+
582+
schema_migration_snapshot_ids: t.List[SnapshotId] = []
583+
grants_only_snapshot_ids: t.Set[SnapshotId] = set()
584+
metadata_only_create_ids: t.Set[SnapshotId] = set()
585+
for s in snapshots.values():
586+
if not s.requires_schema_migration_in_prod:
587+
continue
588+
if s.is_materialized_view and _is_metadata_only_in_prod(s):
589+
targets_physical_grants = s.model.grants is not None and (
590+
s.model.grants_target_layer.is_all
591+
or s.model.grants_target_layer.is_physical
592+
or s.model.virtual_environment_mode.is_dev_only
593+
)
594+
grants_changed = any(
595+
(old := old_snapshots_by_id.get(baseline[s.name].snapshot_id)) is None
596+
or not old.is_model
597+
or s.model.grants != old.model.grants
598+
or s.model.grants_target_layer != old.model.grants_target_layer
599+
for baseline in prod_baselines
600+
)
601+
if targets_physical_grants and grants_changed:
602+
grants_only_snapshot_ids.add(s.snapshot_id)
603+
elif needs_backfill:
604+
# When backfill runs, PhysicalLayerUpdateStage is skipped. Route metadata-only
605+
# MVs to create-only handling so a missing physical MV is still created while an
606+
# existing MV is untouched.
607+
metadata_only_create_ids.add(s.snapshot_id)
608+
continue
609+
schema_migration_snapshot_ids.append(s.snapshot_id)
610+
611+
# Include all upstream dependencies of snapshots that require schema migration to make sure
612+
# the upstream tables are created before the schema updates are applied
613+
snapshot_ids_to_migrate = set(dag.subdag(*schema_migration_snapshot_ids))
614+
upstream_only_ids = snapshot_ids_to_migrate - set(schema_migration_snapshot_ids)
615+
create_only_snapshot_ids = {
616+
s_id
617+
for s_id in upstream_only_ids
618+
if s_id not in grants_only_snapshot_ids
619+
and snapshots[s_id].is_materialized_view
620+
and snapshots[s_id].supports_schema_migration_in_prod
621+
} | metadata_only_create_ids
622+
snapshot_ids_to_migrate |= metadata_only_create_ids
623+
# Migrating a view replaces it, and engines like Postgres drop its dependent views with CASCADE,
624+
# so those are migrated too to be recreated
625+
for s_id in dag:
626+
snapshot = snapshots[s_id]
627+
if snapshot.is_view and any(
628+
p_id in snapshot_ids_to_migrate
629+
and p_id not in create_only_snapshot_ids
630+
and p_id not in grants_only_snapshot_ids
631+
and snapshots[p_id].is_view
632+
and snapshots[p_id].supports_schema_migration_in_prod
633+
for p_id in snapshot.parents
634+
):
635+
snapshot_ids_to_migrate.add(s_id)
636+
grants_only_snapshot_ids.discard(s_id)
637+
create_only_snapshot_ids.discard(s_id)
638+
639+
all_migrate_stage_ids = snapshot_ids_to_migrate | grants_only_snapshot_ids
640+
snapshots_with_schema_migration = [
641+
snapshots[s_id]
642+
for s_id in dag
643+
if s_id in all_migrate_stage_ids and snapshots[s_id].supports_schema_migration_in_prod
644+
]
645+
if not snapshots_with_schema_migration:
646+
return None
647+
648+
return MigrateSchemasStage(
649+
snapshots=snapshots_with_schema_migration,
650+
all_snapshots=snapshots,
651+
deployability_index=deployability_index,
652+
grants_only_snapshot_ids=grants_only_snapshot_ids,
653+
create_only_snapshot_ids=create_only_snapshot_ids,
654+
)
655+
510656
def _get_virtual_layer_update_stage(
511657
self,
512658
promoted_snapshots: t.Set[SnapshotTableInfo],

0 commit comments

Comments
 (0)