diff --git a/docs/concepts/plans.md b/docs/concepts/plans.md index c3e12652ee..a518e7abdb 100644 --- a/docs/concepts/plans.md +++ b/docs/concepts/plans.md @@ -51,6 +51,9 @@ If any downstream models contain a `select *` from the model, SQLMesh attempts t | [Non-breaking](#non-breaking-change) | [Direct](glossary.md#direct-modification) | [Backfill](glossary.md#backfill) | | [Non-breaking](#non-breaking-change) | [Indirect](glossary.md#indirect-modification) | [No Backfill](glossary.md#backfill) | +!!! note + The backfill behavior in the table above does not apply to production environments when the project uses the [`dev_only` virtual environment mode](../guides/configuration.md#virtual-data-environment-modes). In that mode, changes to existing models in production are applied going forward without a backfill, and SQLMesh displays a warning listing the affected models. Use `sqlmesh plan prod --restate-model ""` to rebuild the data. + ## Forward-only change In addition to categorizing a change as breaking or non-breaking, it can also be classified as forward-only. diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 46c6a5da2d..b395ea8666 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -594,6 +594,7 @@ Please note the following tradeoffs when enabling this mode: - All data inserted in development environments is used only for [preview](../concepts/plans.md#data-preview-for-forward-only-changes) and will **not** be reused in production - Reverting a model to a previous version will be applied going forward and may require an explicit data restatement +- Model changes deployed to production, including breaking changes, are applied going forward without a backfill. To rebuild the data, the model must be explicitly restated with `sqlmesh plan prod --restate-model ""`. !!! warning Switching the mode for an existing project will result in a **complete rebuild** of all models in the project. Refer to the [Table Migration Guide](./table_migration.md) to migrate existing tables without rebuilding them from scratch. diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index c3eaed4e6b..ce05d18906 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -1975,6 +1975,7 @@ def plan_builder( }, explain=explain or False, ignore_cron=ignore_cron or False, + default_catalog=self.default_catalog, ) def apply( diff --git a/sqlmesh/core/plan/builder.py b/sqlmesh/core/plan/builder.py index 89b7fdabcd..937c99a783 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -60,6 +60,36 @@ } +# Maximum number of models listed in the warning about changes to `dev_only` models in prod. +MAX_WARNED_MODELS = 10 + +# Change categories that would trigger a backfill if the model was using `full` mode. +_DEV_ONLY_WARNED_CATEGORIES = { + SnapshotChangeCategory.BREAKING: "breaking", + SnapshotChangeCategory.INDIRECT_BREAKING: "indirect breaking", + SnapshotChangeCategory.NON_BREAKING: "non-breaking", +} + + +def _format_dev_only_warning(affected: t.List[str]) -> t.Tuple[str, t.Optional[str]]: + """Returns the short warning message and, if the displayed list is truncated, the full one.""" + + def format_message(models: t.List[str]) -> str: + return ( + "Models changed in production with `virtual_environment_mode: dev_only` are applied " + "going forward without a backfill, and existing rows are not updated.\n" + "Affected models:\n" + + "\n".join(f"- {model}" for model in models) + + '\n\nTo rebuild the data, run `sqlmesh plan prod --restate-model ""`.' + ) + + shown = affected[:MAX_WARNED_MODELS] + hidden = len(affected) - len(shown) + if not hidden: + return format_message(shown), None + return format_message([*shown, f"... and {hidden} more"]), format_message(affected) + + class PlanBuilder: """Plan Builder constructs a Plan based on user choices for how they want to backfill, preview, etc. their changes. @@ -106,6 +136,7 @@ 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. + default_catalog: The default catalog used to format model names in user-facing messages. """ def __init__( @@ -146,8 +177,10 @@ 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, + default_catalog: t.Optional[str] = None, ): self._context_diff = context_diff + self._default_catalog = default_catalog self._no_gaps = no_gaps self._skip_backfill = skip_backfill self._empty_backfill = empty_backfill @@ -189,6 +222,8 @@ def __init__( self._apply = apply self._console = console or get_console() self._choices: t.Dict[SnapshotId, SnapshotChangeCategory] = {} + # Changes already reported by the `dev_only` warning, so that rebuilding the plan doesn't repeat it. + self._warned_dev_only_changes: t.Set[str] = set() self._user_provided_flags = user_provided_flags self._selected_models = selected_models self._explain = explain @@ -338,6 +373,8 @@ def build(self) -> Plan: ) models_to_backfill = self._build_models_to_backfill(dag, restatements) + self._warn_dev_only_prod_changes(restatements) + end_override_per_model = self._end_override_per_model if end_override_per_model and self.override_end: # If the end date was provided explicitly by a user, then interval end for each individual @@ -592,6 +629,51 @@ def _adjust_snapshot_intervals(self) -> None: if new.is_forward_only: new.dev_intervals = new.intervals.copy() + def _warn_dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> None: + """Warns that breaking and non-breaking changes to `dev_only` models in prod are not backfilled. + + The plan is rebuilt after every user choice, so only changes that haven't been reported yet are listed. + """ + # Users who explicitly skip the backfill don't need to be told that there won't be one. + if self._is_dev or self._skip_backfill or self._empty_backfill: + return + affected = self._dev_only_prod_changes(restatements) - self._warned_dev_only_changes + if affected: + self._warned_dev_only_changes |= affected + self._console.log_warning(*_format_dev_only_warning(sorted(affected))) + + def _dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> t.Set[str]: + """Returns `name (category)` for models whose changes would be backfilled under `full` mode but not in `dev_only`. + + With `virtual_environment_mode: dev_only` each model has a single in-place table in prod and the + snapshot version is fixed, so changes that would be backfilled under `full` mode are applied going + forward only. Models that would not be rebuilt under `full` mode either (forward-only kinds, pinned + physical versions, views, symbolic models, ...) or that are rebuilt anyway (forced rebuilds, + restatements) are not reported. + """ + affected: t.Set[str] = set() + for new, old in self._context_diff.modified_snapshots.values(): + # Note: `new.is_forward_only` can't be used below because in the non-full modes every snapshot is + # categorized as forward-only, so an explicit `--forward-only` plan is indistinguishable from the + # default one and is warned about as well. Only a model-level forward-only kind is excluded. + if ( + not new.is_model + or new.virtual_environment_mode.is_full + or new.change_category not in _DEV_ONLY_WARNED_CATEGORIES + or new.model.forward_only + or new.model.physical_version + or not (new.is_materialized or new.is_materialized_view) + or new.disable_restatement + or new.snapshot_id in restatements + or should_force_rebuild(old, new) + ): + continue + display_name = new.display_name( + self.environment_naming_info, self._default_catalog, new.model.dialect + ) + affected.add(f"{display_name} ({_DEV_ONLY_WARNED_CATEGORIES[new.change_category]})") + return affected + def _check_destructive_additive_changes(self, directly_modified: t.Set[SnapshotId]) -> None: for s_id in sorted(directly_modified): if s_id.name not in self._context_diff.modified_snapshots: diff --git a/tests/core/integration/test_dev_only_vde.py b/tests/core/integration/test_dev_only_vde.py index 611e207771..dcee8235a0 100644 --- a/tests/core/integration/test_dev_only_vde.py +++ b/tests/core/integration/test_dev_only_vde.py @@ -2,6 +2,7 @@ import typing as t import pytest +from pytest_mock.plugin import MockerFixture from sqlmesh.core.model.common import ParsableSql import time_machine @@ -25,7 +26,9 @@ @time_machine.travel("2023-01-08 15:00:00 UTC") -def test_virtual_environment_mode_dev_only(init_and_plan_context: t.Callable): +def test_virtual_environment_mode_dev_only( + init_and_plan_context: t.Callable, mocker: MockerFixture +): context, _ = init_and_plan_context( "examples/sushi", config="test_config_virtual_environment_mode_dev_only" ) @@ -92,9 +95,21 @@ def test_virtual_environment_mode_dev_only(init_and_plan_context: t.Callable): assert min_event_date == to_date("2023-01-07") # Make sure the changes are applied without backfill in prod + log_warning_spy = mocker.spy(context.console, "log_warning") plan_prod = context.plan_builder("prod").build() assert not plan_prod.requires_backfill assert not plan_prod.missing_intervals + dev_only_warnings = [ + message + for call in log_warning_spy.call_args_list + if "virtual_environment_mode: dev_only" + in (message := call.args[0] if call.args else call.kwargs.get("short_message", "")) + ] + assert len(dev_only_warnings) == 1 + assert "without a backfill" in dev_only_warnings[0] + assert "- sushi.waiter_revenue_by_day (breaking)\n" in dev_only_warnings[0] + # Views have no data to backfill, so the downstream view is not listed. + assert "top_waiters" not in dev_only_warnings[0] context.apply(plan_prod) assert "one" in context.engine_adapter.columns("sushi.waiter_revenue_by_day") diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index f412e63eb1..bfa5fb8a9f 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -5,6 +5,7 @@ import pytest +from sqlmesh.core.config.common import VirtualEnvironmentMode from sqlmesh.core.console import TerminalConsole from sqlmesh.utils.metaprogramming import Executable from tests.core.test_table_diff import create_test_console @@ -26,9 +27,15 @@ SqlModel, ModelKindName, ) -from sqlmesh.core.model.kind import OnDestructiveChange, OnAdditiveChange, ViewKind +from sqlmesh.core.model.kind import ( + EmbeddedKind, + OnDestructiveChange, + OnAdditiveChange, + ViewKind, +) from sqlmesh.core.model.seed import Seed from sqlmesh.core.plan import Plan, PlanBuilder, SnapshotIntervals +from sqlmesh.core.plan.builder import MAX_WARNED_MODELS from sqlmesh.core.snapshot import ( DeployabilityIndex, Snapshot, @@ -5049,3 +5056,346 @@ def test_indirect_change_forward_only_with_stored_forward_only_parent_and_new_pa assert child_new.is_forward_only == expected_forward_only # A forward-only child keeps its previous version, otherwise it's rebuilt. assert (child_new.version == child_old.version) == expected_forward_only + + +def _dev_only_plan_builder( + make_snapshot, + mocker: MockerFixture, + changes: t.Sequence[t.Tuple[t.Optional[t.Any], t.Any]], + *, + choice: t.Optional[SnapshotChangeCategory] = None, + is_dev: bool = False, + # Context always sets forward_only=True when the virtual environment mode is not full. + forward_only: bool = True, + **builder_kwargs: t.Any, +) -> t.Tuple[PlanBuilder, t.Any]: + """Creates a plan builder for a list of `(old_model, new_model)` changes. + + Models are expected in topological order. If `old_model` is None the new model is treated as newly + added. `choice` is applied to all directly modified snapshots. + """ + old_snapshots: t.Dict[str, Snapshot] = {} + new_snapshots: t.Dict[str, Snapshot] = {} + for old, new in changes: + old_nodes = {n: s.node for n, s in old_snapshots.items()} + new_nodes = {n: s.node for n, s in new_snapshots.items()} + new_snapshot = make_snapshot(new, nodes=new_nodes) + if old is not None: + old_snapshot = make_snapshot(old, nodes=old_nodes) + old_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + old_snapshots[old_snapshot.name] = old_snapshot + new_snapshot.previous_versions = old_snapshot.all_versions + new_snapshots[new_snapshot.name] = new_snapshot + + context_diff = ContextDiff( + environment="dev" if is_dev else "prod", + is_new_environment=is_dev, + is_unfinalized_environment=False, + normalize_environment_name=True, + create_from="prod", + create_from_env_exists=True, + added={s.snapshot_id for n, s in new_snapshots.items() if n not in old_snapshots}, + removed_snapshots={}, + modified_snapshots={n: (new_snapshots[n], old) for n, old in old_snapshots.items()}, + snapshots={s.snapshot_id: s for s in new_snapshots.values()}, + new_snapshots={s.snapshot_id: s for s in new_snapshots.values()}, + previous_plan_id=None, + previously_promoted_snapshot_ids=set(), + previous_finalized_snapshots=None, + previous_gateway_managed_virtual_layer=False, + gateway_managed_virtual_layer=False, + environment_statements=[], + ) + + mock_console = mocker.Mock() + plan_builder = PlanBuilder( + context_diff, + is_dev=is_dev, + console=mock_console, + forward_only=forward_only, + **builder_kwargs, + ) + if choice is not None: + for name, snapshot in new_snapshots.items(): + if name in old_snapshots and context_diff.directly_modified(name): + plan_builder.set_choice(snapshot, choice) + return plan_builder, mock_console + + +class _DevOnlyWarning(t.NamedTuple): + """The arguments of the `log_warning` call made for changes to `dev_only` models in prod.""" + + short: str + long: t.Optional[str] + + @property + def models(self) -> t.List[str]: + """The listed models, one entry per line of the list.""" + lines = self.short.split("Affected models:\n")[1].split("\n\n")[0].splitlines() + return [line.removeprefix("- ") for line in lines] + + +@pytest.fixture +def dev_only_plan_builder(make_snapshot, mocker: MockerFixture) -> t.Callable[..., t.Any]: + def create(changes, **kwargs: t.Any) -> t.Tuple[PlanBuilder, t.Any]: + return _dev_only_plan_builder(make_snapshot, mocker, changes, **kwargs) + + return create + + +@pytest.fixture +def dev_only_warning( + dev_only_plan_builder: t.Callable[..., t.Any], +) -> t.Callable[..., t.Optional[_DevOnlyWarning]]: + """Builds the plan for the changes and returns the warning that was logged, or None.""" + + def build( + changes, + choice: t.Optional[SnapshotChangeCategory] = SnapshotChangeCategory.BREAKING, + **kwargs: t.Any, + ) -> t.Optional[_DevOnlyWarning]: + plan_builder, console = dev_only_plan_builder(changes, choice=choice, **kwargs) + plan_builder.build() + if not console.log_warning.called: + return None + console.log_warning.assert_called_once() + return _DevOnlyWarning(*console.log_warning.call_args.args) + + return build + + +def _dev_only_sql_model( + query: str = "select 1 as col", name: str = "db.a", **kwargs: t.Any +) -> SqlModel: + kwargs.setdefault("kind", FullKind()) + kwargs.setdefault("virtual_environment_mode", VirtualEnvironmentMode.DEV_ONLY) + return SqlModel(name=name, query=parse_one(query), dialect="duckdb", **kwargs) + + +def _dev_only_change(name: str = "db.a", **kwargs: t.Any) -> t.Tuple[SqlModel, SqlModel]: + """Returns an `(old, new)` pair of `dev_only` models where only the query changes.""" + return ( + _dev_only_sql_model("select 1 as col, ds", name=name, **kwargs), + _dev_only_sql_model("select 2 as col, ds", name=name, **kwargs), + ) + + +def _dev_only_downstream_change( + mode: VirtualEnvironmentMode = VirtualEnvironmentMode.DEV_ONLY, +) -> t.Tuple[SqlModel, SqlModel]: + """Returns an `(old, new)` pair for an unchanged model that selects from `db.a`.""" + model = _dev_only_sql_model("select col from db.a", name="db.b", virtual_environment_mode=mode) + return model, model + + +def _dev_only_seed(content: str) -> SeedModel: + return SeedModel( + name="db.a", + kind=SeedKind(path="./path/to/seed"), + seed=Seed(content=content), + column_hashes={"col": content}, + depends_on=set(), + virtual_environment_mode=VirtualEnvironmentMode.DEV_ONLY, + ) + + +@pytest.mark.parametrize( + "choice, expected_category", + [ + (SnapshotChangeCategory.BREAKING, "breaking"), + (SnapshotChangeCategory.NON_BREAKING, "non-breaking"), + ], +) +def test_dev_only_prod_directly_modified_warns(dev_only_warning, choice, expected_category): + warning = dev_only_warning([_dev_only_change()], choice) + assert warning == ( + "Models changed in production with `virtual_environment_mode: dev_only` are applied " + "going forward without a backfill, and existing rows are not updated.\n" + f"Affected models:\n- db.a ({expected_category})\n\n" + 'To rebuild the data, run `sqlmesh plan prod --restate-model ""`.', + None, + ) + + +def test_dev_only_prod_warning_is_not_repeated(dev_only_plan_builder): + plan_builder, console = dev_only_plan_builder( + [_dev_only_change()], choice=SnapshotChangeCategory.BREAKING + ) + plan = plan_builder.build() + console.log_warning.assert_called_once() + + # The plan is invalidated by every user choice in the interactive flow and then rebuilt. + snapshot = next(iter(plan.context_diff.snapshots.values())) + plan_builder.set_choice(snapshot, SnapshotChangeCategory.BREAKING) + plan_builder.build() + console.log_warning.assert_called_once() + + +@pytest.mark.parametrize( + "choice, expected_models", + [ + (SnapshotChangeCategory.BREAKING, ["db.a (breaking)", "db.b (indirect breaking)"]), + # Indirect non-breaking changes would not be backfilled under `full` mode either. + (SnapshotChangeCategory.NON_BREAKING, ["db.a (non-breaking)"]), + ], +) +def test_dev_only_prod_downstream_models(dev_only_warning, choice, expected_models): + warning = dev_only_warning([_dev_only_change(), _dev_only_downstream_change()], choice) + assert warning and warning.models == expected_models + + +def test_dev_only_prod_metadata_change_does_not_warn(dev_only_plan_builder): + plan_builder, console = dev_only_plan_builder( + [ + ( + _dev_only_sql_model("select 1 as col"), + _dev_only_sql_model("select 1 as col", description="new description"), + ) + ] + ) + plan = plan_builder.build() + + assert [s.change_category for s in plan.context_diff.snapshots.values()] == [ + SnapshotChangeCategory.METADATA + ] + console.log_warning.assert_not_called() + + +def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(dev_only_warning): + warning = dev_only_warning( + [ + _dev_only_change("db.a"), + _dev_only_change("db.c", virtual_environment_mode=VirtualEnvironmentMode.FULL), + ] + ) + assert warning and warning.models == ["db.a (breaking)"] + + +def test_dev_only_prod_materialized_view_warns(dev_only_warning): + warning = dev_only_warning([_dev_only_change(kind=ViewKind(materialized=True))]) + assert warning and warning.models == ["db.a (breaking)"] + + +def test_dev_only_prod_warns_without_forward_only_flag(dev_only_warning): + # In the non-full modes Context makes all plans forward-only (the default of the helper), so + # an explicit `--forward-only` is indistinguishable from the default and must not matter. + assert dev_only_warning([_dev_only_change()], forward_only=False) + + +def test_dev_only_prod_warning_hides_default_catalog(dev_only_warning): + warning = dev_only_warning( + [_dev_only_change("other_catalog.db.a"), _dev_only_change("main_catalog.db.b")], + default_catalog="main_catalog", + ) + assert warning and warning.models == ["db.b (breaking)", "other_catalog.db.a (breaking)"] + + +def _no_warning_cases() -> t.List[t.Any]: + full = VirtualEnvironmentMode.FULL + restated = {"restate_models": {'"db"."a"'}} + return [ + # Plans that aren't prod plans of existing `dev_only` models. + pytest.param([_dev_only_change()], {"is_dev": True}, id="dev_plan"), + pytest.param([(None, _dev_only_sql_model())], {"choice": None}, id="added_model"), + pytest.param( + [_dev_only_change(virtual_environment_mode=full), _dev_only_downstream_change(full)], + {}, + id="full_mode", + ), + # The backfill is explicitly skipped or the models are restated anyway. + pytest.param([_dev_only_change()], {"skip_backfill": True}, id="skip_backfill"), + pytest.param([_dev_only_change()], {"empty_backfill": True}, id="empty_backfill"), + pytest.param([_dev_only_change()], restated, id="restated"), + pytest.param( + [_dev_only_change(), _dev_only_downstream_change()], restated, id="restated_downstream" + ), + # Rebuilt anyway: seed changes, breaking kind changes and changes of the virtual environment mode. + pytest.param([(_dev_only_seed("old"), _dev_only_seed("new"))], {}, id="seed"), + pytest.param( + [ + ( + _dev_only_sql_model("select 1 as col, ds", kind=FullKind()), + _dev_only_sql_model( + "select 1 as col, ds", kind=IncrementalByTimeRangeKind(time_column="ds") + ), + ) + ], + {}, + id="kind_change", + ), + pytest.param( + [(_dev_only_sql_model(virtual_environment_mode=full), _dev_only_sql_model())], + {}, + id="mode_change", + ), + # Would not be backfilled under `full` mode either. + pytest.param( + [ + _dev_only_change( + kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True) + ) + ], + {}, + id="model_forward_only", + ), + pytest.param([_dev_only_change(physical_version="pinned")], {}, id="physical_version"), + pytest.param([_dev_only_change(kind=EmbeddedKind())], {}, id="embedded"), + pytest.param( + [ + ( + ExternalModel( + name="db.a", + columns={"col": "int"}, + virtual_environment_mode=VirtualEnvironmentMode.DEV_ONLY, + ), + ExternalModel( + name="db.a", + columns={"col": "int", "col2": "int"}, + virtual_environment_mode=VirtualEnvironmentMode.DEV_ONLY, + ), + ) + ], + {}, + id="external", + ), + pytest.param([_dev_only_change(kind=ViewKind())], {}, id="view"), + pytest.param( + [ + _dev_only_change( + kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True) + ) + ], + {}, + id="disable_restatement", + ), + ] + + +@pytest.mark.parametrize("changes, options", _no_warning_cases()) +def test_dev_only_prod_does_not_warn(dev_only_warning, changes, options): + assert dev_only_warning(changes, **options) is None + + +def test_dev_only_prod_warning_lists_all_models_up_to_cap(dev_only_warning): + changes = [_dev_only_change(f"db.model_{i:02d}") for i in range(MAX_WARNED_MODELS)] + warning = dev_only_warning(changes) + assert warning + assert len(warning.models) == MAX_WARNED_MODELS + assert warning.models[-1] == f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)" + assert "more" not in warning.short + assert warning.long is None + + +def test_dev_only_prod_warning_truncates_models_above_cap(dev_only_warning): + changes = [_dev_only_change(f"db.model_{i:02d}") for i in range(MAX_WARNED_MODELS + 2)] + warning = dev_only_warning(changes) + assert warning + assert warning.models[-2:] == [ + f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)", + "... and 2 more", + ] + assert f"db.model_{MAX_WARNED_MODELS:02d}" not in warning.short + # The full list goes to the log message. + assert warning.long + assert f"db.model_{MAX_WARNED_MODELS + 1:02d} (breaking)" in warning.long + assert "more" not in warning.long