Repository navigation
fix(plan): surface destructive and additive schema changes on forward-only models before prod deploy #6232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
fix(plan): surface destructive and additive schema changes on forward-only models before prod deploy #6232
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,8 @@ | |
| from functools import cached_property | ||
| from datetime import datetime | ||
|
|
||
| from sqlglot import exp | ||
|
|
||
|
|
||
| from sqlmesh.core.console import PlanBuilderConsole, get_console | ||
| from sqlmesh.core.config import ( | ||
|
|
@@ -16,6 +18,7 @@ | |
| ) | ||
| from sqlmesh.core.context_diff import ContextDiff | ||
| from sqlmesh.core.environment import EnvironmentNamingInfo | ||
| from sqlmesh.core.model import Model, SCDType2ByTimeKind | ||
| from sqlmesh.core.plan.common import should_force_rebuild, is_breaking_kind_change | ||
| from sqlmesh.core.plan.definition import ( | ||
| Plan, | ||
|
|
@@ -27,6 +30,8 @@ | |
| get_schema_differ, | ||
| has_drop_alteration, | ||
| has_additive_alteration, | ||
| prepare_columns_for_static_diff, | ||
| TableAlterDropColumnOperation, | ||
| TableAlterOperation, | ||
| ) | ||
| from sqlmesh.core.snapshot import ( | ||
|
|
@@ -36,7 +41,7 @@ | |
| ) | ||
| from sqlmesh.core.snapshot.categorizer import categorize_change | ||
| from sqlmesh.core.snapshot.definition import Interval, SnapshotDataVersion, SnapshotId | ||
| from sqlmesh.utils import columns_to_types_all_known, random_id | ||
| from sqlmesh.utils import random_id | ||
| from sqlmesh.utils.dag import DAG | ||
| from sqlmesh.utils.date import ( | ||
| TimeLike, | ||
|
|
@@ -60,6 +65,25 @@ | |
| } | ||
|
|
||
|
|
||
| def _physical_columns_to_types(model: Model) -> t.Optional[t.Dict[str, exp.DataType]]: | ||
| """Returns the model's columns as they are materialized in the physical table. | ||
|
|
||
| SCD Type 2 by time models always create the `updated_at` column with `time_data_type`, | ||
| regardless of the type that the model's query projects. | ||
|
|
||
| Table creation only forces this for annotated models. For unannotated ones the comparison is | ||
| still consistent: both sides are overridden the same way, and `valid_from` / `valid_to` already | ||
| use `time_data_type`. | ||
| """ | ||
| columns_to_types = model.columns_to_types | ||
| if columns_to_types is not None and isinstance(model.kind, SCDType2ByTimeKind): | ||
| columns_to_types = dict(columns_to_types) | ||
| updated_at = model.kind.updated_at_name.name | ||
| if updated_at in columns_to_types: | ||
| columns_to_types[updated_at] = model.kind.time_data_type | ||
| return columns_to_types | ||
|
|
||
|
|
||
| class PlanBuilder: | ||
| """Plan Builder constructs a Plan based on user choices for how they want to backfill, preview, etc. their changes. | ||
|
|
||
|
|
@@ -106,6 +130,8 @@ class PlanBuilder: | |
| end_override_per_model: A mapping of model FQNs to target end dates. | ||
| ignore_cron: Whether to ignore the node's cron schedule when computing missing intervals. | ||
| explain: Whether to explain the plan instead of applying it. | ||
| schema_differ_overrides: Optional mapping from gateway name (or None for the default | ||
| gateway) to SchemaDiffer keyword argument overrides for static schema diffing. | ||
| """ | ||
|
|
||
| def __init__( | ||
|
|
@@ -146,6 +172,7 @@ def __init__( | |
| console: t.Optional[PlanBuilderConsole] = None, | ||
| user_provided_flags: t.Optional[t.Dict[str, UserProvidedFlags]] = None, | ||
| selected_models: t.Optional[t.Set[str]] = None, | ||
| schema_differ_overrides: t.Optional[t.Dict[t.Optional[str], t.Dict[str, t.Any]]] = None, | ||
| ): | ||
| self._context_diff = context_diff | ||
| self._no_gaps = no_gaps | ||
|
|
@@ -220,6 +247,10 @@ def __init__( | |
| gateway_managed=self._context_diff.gateway_managed_virtual_layer, | ||
| ) | ||
|
|
||
| self._schema_differ_overrides: t.Dict[t.Optional[str], t.Dict[str, t.Any]] = ( | ||
| schema_differ_overrides or {} | ||
| ) | ||
| self._logged_schema_warnings: t.Set[t.Tuple[SnapshotId, bool]] = set() | ||
| self._latest_plan: t.Optional[Plan] = None | ||
|
|
||
| @property | ||
|
|
@@ -318,8 +349,8 @@ def build(self) -> Plan: | |
| dag = self._build_dag() | ||
| directly_modified, indirectly_modified = self._build_directly_and_indirectly_modified(dag) | ||
|
|
||
| self._check_destructive_additive_changes(directly_modified) | ||
| self._categorize_snapshots(dag, indirectly_modified) | ||
| self._check_destructive_additive_changes(dag) | ||
| self._adjust_snapshot_intervals() | ||
|
|
||
| deployability_index = ( | ||
|
|
@@ -592,68 +623,154 @@ def _adjust_snapshot_intervals(self) -> None: | |
| if new.is_forward_only: | ||
| new.dev_intervals = new.intervals.copy() | ||
|
|
||
| def _check_destructive_additive_changes(self, directly_modified: t.Set[SnapshotId]) -> None: | ||
| for s_id in sorted(directly_modified): | ||
| def _is_breaking_kind_or_seed_modification(self, s_id: SnapshotId) -> bool: | ||
| if s_id.name not in self._context_diff.modified_snapshots: | ||
| return False | ||
| snapshot = self._context_diff.snapshots[s_id] | ||
| if snapshot.is_seed: | ||
| return True | ||
| new, old = self._context_diff.modified_snapshots[s_id.name] | ||
| return is_breaking_kind_change(old, new) | ||
|
|
||
| def _compute_snapshot_forward_only(self, s_id: SnapshotId) -> bool: | ||
| if not (self._forward_only or self._is_forward_only_change(s_id)): | ||
| return False | ||
| # Breaking kind changes and seed changes can't be forward-only. | ||
| return not self._is_breaking_kind_or_seed_modification(s_id) | ||
|
|
||
| def _check_destructive_additive_changes(self, dag: DAG[SnapshotId]) -> None: | ||
| effective_forward_only: t.Dict[SnapshotId, bool] = {} | ||
|
|
||
| for s_id in dag: | ||
| snapshot = self._context_diff.snapshots.get(s_id) | ||
| if not snapshot: | ||
| continue | ||
|
|
||
| if snapshot.is_seed or self._is_breaking_kind_or_seed_modification(s_id): | ||
| is_fo = False | ||
| elif ( | ||
| snapshot.is_forward_only or self._forward_only or self._is_forward_only_change(s_id) | ||
| ): | ||
| is_fo = True | ||
| elif self._context_diff.indirectly_modified(s_id.name): | ||
| upstream_new_fo = { | ||
| effective_forward_only[p_id] | ||
| for p_id in dag.upstream(s_id) | ||
| if p_id in effective_forward_only | ||
| and self._is_new_snapshot(self._context_diff.snapshots[p_id]) | ||
| } | ||
| is_fo = upstream_new_fo == {True} | ||
|
Comment on lines
+655
to
+662
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not reject schema changes for downstream models that will rebuild. If new parent For categorized snapshots, use the resulting rebuild decision instead of recomputing the parent vote. Keep the provisional check for uncategorized snapshots where the plan or model requires forward-only behavior. Keep checking a categorized child when all relevant votes are forward-only.
|
||
| else: | ||
| is_fo = False | ||
| effective_forward_only[s_id] = is_fo | ||
|
|
||
| if s_id.name not in self._context_diff.modified_snapshots: | ||
| continue | ||
| if not ( | ||
| self._context_diff.directly_modified(s_id.name) | ||
| or self._context_diff.indirectly_modified(s_id.name) | ||
| ): | ||
| continue | ||
| if not snapshot.is_model or not snapshot.is_materialized or snapshot.is_seed: | ||
| continue | ||
|
|
||
| is_final_indirect_non_breaking = ( | ||
| snapshot.categorized | ||
| and snapshot.is_indirect_non_breaking | ||
| and all( | ||
| self._context_diff.snapshots[p_id].categorized | ||
| for p_id in dag.upstream(s_id) | ||
| if p_id in self._context_diff.snapshots | ||
| ) | ||
| ) | ||
| if not (is_fo or is_final_indirect_non_breaking): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check additions to existing pinned physical versions before production. If a non-forward-only incremental model keeps Include known in-place migrations in additive validation. Keep excluding rebuilds that create a fresh physical table.
|
||
| continue | ||
|
|
||
| snapshot = self._context_diff.snapshots[s_id] | ||
| needs_destructive_check = snapshot.needs_destructive_check( | ||
| self._allow_destructive_models | ||
| ) | ||
| needs_additive_check = snapshot.needs_additive_check(self._allow_additive_models) | ||
| # should we raise/warn if this snapshot has/inherits a destructive change? | ||
| should_raise_or_warn = (self._is_forward_only_change(s_id) or self._forward_only) and ( | ||
| needs_destructive_check or needs_additive_check | ||
| ) | ||
|
|
||
| if not should_raise_or_warn or not snapshot.is_model: | ||
| continue | ||
|
|
||
| new, old = self._context_diff.modified_snapshots[snapshot.name] | ||
|
|
||
| # we must know all columns_to_types to determine whether a change is destructive | ||
| old_columns_to_types = old.model.columns_to_types or {} | ||
| new_columns_to_types = new.model.columns_to_types or {} | ||
| if not (needs_destructive_check or needs_additive_check): | ||
| continue | ||
| comparable = prepare_columns_for_static_diff( | ||
| _physical_columns_to_types(old.model), _physical_columns_to_types(new.model) | ||
| ) | ||
| if comparable is None: | ||
| continue | ||
|
|
||
| if columns_to_types_all_known(old_columns_to_types) and columns_to_types_all_known( | ||
| new_columns_to_types | ||
| ): | ||
| alter_operations = t.cast( | ||
| t.List[TableAlterOperation], | ||
| get_schema_differ(snapshot.model.dialect).compare_columns( | ||
| new.name, | ||
| old_columns_to_types, | ||
| new_columns_to_types, | ||
| ignore_destructive=new.model.on_destructive_change.is_ignore, | ||
| ignore_additive=new.model.on_additive_change.is_ignore, | ||
| ), | ||
| ) | ||
| old_columns_to_types, new_columns_to_types = comparable | ||
| if snapshot.model_gateway in self._schema_differ_overrides: | ||
| differ_overrides = self._schema_differ_overrides[snapshot.model_gateway] or None | ||
| elif snapshot.model_gateway is None: | ||
| differ_overrides = self._schema_differ_overrides.get(None) or None | ||
| else: | ||
| differ_overrides = None | ||
|
Comment on lines
+704
to
+709
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Resolve an empty model gateway the same way as the evaluator. The model validator preserves
|
||
|
|
||
| alter_operations = t.cast( | ||
| t.List[TableAlterOperation], | ||
| get_schema_differ( | ||
| snapshot.model.dialect, overrides=differ_overrides | ||
| ).compare_columns( | ||
| new.name, | ||
| old_columns_to_types, | ||
| new_columns_to_types, | ||
| ignore_destructive=new.model.on_destructive_change.is_ignore, | ||
| ignore_additive=new.model.on_additive_change.is_ignore, | ||
| ), | ||
| ) | ||
|
|
||
| snapshot_name = snapshot.name | ||
| model_dialect = snapshot.model.dialect | ||
| if old.model.on_additive_change.is_ignore: | ||
| # Columns that the previous definition added under an ignored additive policy may | ||
| # never have reached its physical table, so the saved definitions can't establish | ||
| # that dropping them is destructive. That is left to the physical validation. | ||
| alter_operations = [ | ||
| op | ||
| for op in alter_operations | ||
| if not isinstance(op, TableAlterDropColumnOperation) | ||
|
Comment on lines
+724
to
+731
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not reject a physical widening because the earlier additive policy ignored it. Under the default The static check must not reject a change that widens the physical column. It must still reject a narrowing from the physical type. The author can choose how to meet this. Options include comparing against the physical type, or deferring the destructive decision for the whole replacement to physical validation.
|
||
| ] | ||
|
|
||
| if needs_destructive_check and has_drop_alteration(alter_operations): | ||
| snapshot_name = snapshot.name | ||
| model_dialect = snapshot.model.dialect | ||
|
|
||
| if needs_destructive_check and has_drop_alteration(alter_operations): | ||
| if snapshot.model.on_destructive_change.is_warn: | ||
| if (s_id, True) not in self._logged_schema_warnings: | ||
| self._console.log_destructive_change( | ||
| snapshot_name, | ||
| alter_operations, | ||
| model_dialect, | ||
| error=False, | ||
| ) | ||
| self._logged_schema_warnings.add((s_id, True)) | ||
| elif snapshot.model.on_destructive_change.is_error: | ||
| self._console.log_destructive_change( | ||
| snapshot_name, | ||
| alter_operations, | ||
| model_dialect, | ||
| error=not snapshot.model.on_destructive_change.is_warn, | ||
| error=True, | ||
| ) | ||
| if snapshot.model.on_destructive_change.is_error: | ||
| raise PlanError( | ||
| "Plan requires a destructive change to a forward-only model." | ||
| raise PlanError("Plan requires a destructive change to a forward-only model.") | ||
|
|
||
| if needs_additive_check and has_additive_alteration(alter_operations): | ||
| if snapshot.model.on_additive_change.is_warn: | ||
| if (s_id, False) not in self._logged_schema_warnings: | ||
| self._console.log_additive_change( | ||
| snapshot_name, | ||
| alter_operations, | ||
| model_dialect, | ||
| error=False, | ||
| ) | ||
|
|
||
| if needs_additive_check and has_additive_alteration(alter_operations): | ||
| self._logged_schema_warnings.add((s_id, False)) | ||
| elif snapshot.model.on_additive_change.is_error: | ||
| self._console.log_additive_change( | ||
| snapshot_name, | ||
| alter_operations, | ||
| model_dialect, | ||
| error=not snapshot.model.on_additive_change.is_warn, | ||
| error=True, | ||
| ) | ||
| if snapshot.model.on_additive_change.is_error: | ||
| raise PlanError("Plan requires an additive change to a forward-only model.") | ||
| raise PlanError("Plan requires an additive change to a forward-only model.") | ||
|
|
||
| def _categorize_snapshots( | ||
| self, dag: DAG[SnapshotId], indirectly_modified: SnapshotMapping | ||
|
|
@@ -671,12 +788,7 @@ def _categorize_snapshots( | |
| if not snapshot or not self._is_new_snapshot(snapshot): | ||
| continue | ||
|
|
||
| forward_only = self._forward_only or self._is_forward_only_change(s_id) | ||
| if forward_only and s_id.name in self._context_diff.modified_snapshots: | ||
| new, old = self._context_diff.modified_snapshots[s_id.name] | ||
| if is_breaking_kind_change(old, new) or snapshot.is_seed: | ||
| # Breaking kind changes and seed changes can't be forward-only. | ||
| forward_only = False | ||
| forward_only = self._compute_snapshot_forward_only(s_id) | ||
|
|
||
| if s_id in self._choices: | ||
| snapshot.categorize_as(self._choices[s_id], forward_only) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apply the SCD type override only to annotated models.
If both queries contain
NULL AS val, both models are unannotated. Withtime_data_type=TIMESTAMP, changing the projectedupdated_atfromDATEtoTIMESTAMPchanges the physical CTAS schema. The creation strategy applies the SCD override only to annotated models. This helper instead substitutesTIMESTAMPon both sides and hides that predictable change from planning. (raw.githubusercontent.com)Add
model.annotatedto this condition. Keep the current substitution for fully known schemas, and add a regression with a shared NULL-typed sibling.