From fd1313d08a0381ec40bf39ed7c4d0461ec6c71e8 Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Thu, 3 Dec 2026 11:47:16 +0100 Subject: [PATCH 1/7] feat(plan): warn when dev_only prod changes are applied without backfill Under `virtual_environment_mode: dev_only`, changes deployed to prod are applied going forward without a backfill, whatever category the plan assigns. Nothing in the plan output said so, which made a "Breaking" label look like it implied a rebuild. Emit a single aggregated warning from `PlanBuilder.build()` for modified models categorized breaking, indirect breaking or non-breaking (the categories that would be rebuilt under `full`), pointing users at `--restate-model`. Dev plans, `full` mode, new models, forced rebuilds, restated models, symbolic models, plain views, models with `disable_restatement` and models with a forward-only kind are skipped. `PlanBuilder` takes a new optional `default_catalog` argument so model names in the warning are displayed like other plan messages. Also document the tradeoff in the `dev_only` docs and the plans concept page. Refs #6269 Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- docs/concepts/plans.md | 3 + docs/guides/configuration.md | 2 + sqlmesh/core/context.py | 1 + sqlmesh/core/plan/builder.py | 73 ++++ tests/core/integration/test_dev_only_vde.py | 16 +- tests/core/test_plan.py | 454 +++++++++++++++++++- 6 files changed, 547 insertions(+), 2 deletions(-) diff --git a/docs/concepts/plans.md b/docs/concepts/plans.md index c3e12652ee..e08fd97b96 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 each model has a single in-place table in production, so breaking and non-breaking changes are applied going forward without a backfill, and SQLMesh displays a warning listing the affected models. The warning only appears for changes that would have been rebuilt under the default `full` mode, so models with a model-level `forward_only` kind, plain (non-materialized) views, symbolic models (embedded and external), and models with `disable_restatement` enabled are not affected. Use `sqlmesh plan --restate-model ""` to rebuild the data. Note that `--restate-model` can't rebuild models with `disable_restatement` enabled. + ## 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 38f6814c8b..c8b140ef22 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -594,6 +594,8 @@ 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. Existing rows are not updated, so changes such as a modified `WHERE` clause or a recomputed column only affect data processed after the deployment, and SQLMesh displays a warning when a production plan contains such changes (listing at most 10 models). +- To rebuild the data, explicitly restate the model with `sqlmesh plan --restate-model ""`. This is not done automatically because each model has a single, in-place table in production: a rebuild overwrites that table and there is no previous version to fall back to if it fails. !!! 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 b70ccae141..781d81a98e 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -1905,6 +1905,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 a6307a9ffd..e963f41d46 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -52,6 +52,10 @@ logger = logging.getLogger(__name__) +# Maximum number of models listed in the warning about changes to `dev_only` models in prod. +MAX_WARNED_MODELS = 10 + + class PlanBuilder: """Plan Builder constructs a Plan based on user choices for how they want to backfill, preview, etc. their changes. @@ -98,6 +102,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__( @@ -138,8 +143,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 @@ -330,6 +337,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 @@ -584,6 +593,70 @@ 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. + + 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, views, + symbolic models, ...) or that are rebuilt anyway (forced rebuilds, restatements) are not reported. + """ + if self._is_dev: + return + + # Change categories that would trigger a backfill if the model was using `full` mode. + category_labels = { + SnapshotChangeCategory.BREAKING: "breaking", + SnapshotChangeCategory.INDIRECT_BREAKING: "indirect breaking", + SnapshotChangeCategory.NON_BREAKING: "non-breaking", + } + affected: t.Dict[str, str] = {} + 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 not old.is_model + or new.virtual_environment_mode.is_full + or new.change_category not in category_labels + or new.model.forward_only + or new.is_symbolic + or (new.is_view and not 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[display_name] = category_labels[new.change_category] + + if not affected: + return + + def format_models(names: t.List[str]) -> str: + return ", ".join(f"{name} ({affected[name]})" for name in names) + + names = sorted(affected) + shown, hidden = names[:MAX_WARNED_MODELS], names[MAX_WARNED_MODELS:] + message = ( + "Models changed in production with `virtual_environment_mode: dev_only` are applied " + "going forward without a backfill, and existing rows are not updated. " + "Affected models: {models}. " + 'To rebuild the data, run `sqlmesh plan --restate-model ""`.' + ) + if not hidden: + self._console.log_warning(message.format(models=format_models(shown))) + return + + # The full list is only included in the log message when the displayed one is truncated. + self._console.log_warning( + message.format(models=f"{format_models(shown)} and {len(hidden)} more"), + message.format(models=format_models(names)), + ) + 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..35dc40f418 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,20 @@ 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 = [ + call.args[0] + for call in log_warning_spy.call_args_list + if "virtual_environment_mode: dev_only" in call.args[0] + ] + assert len(dev_only_warnings) == 1 + assert "without a backfill" in dev_only_warnings[0] + assert "Affected models: sushi.waiter_revenue_by_day (breaking)." 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 add85d2eec..c2444cf598 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,7 +27,12 @@ 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.snapshot import ( @@ -4510,3 +4516,449 @@ def test_forward_only_indirect_change_to_materialized_view(make_snapshot): # Forward-only indirect changes to MVs should not always be classified as indirect breaking. # Instead, we want to preserve the standard categorization. assert snapshot_b_new.change_category == SnapshotChangeCategory.INDIRECT_NON_BREAKING + + +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, + restate_models: t.Optional[t.Set[str]] = None, + # Context always sets forward_only=True when the virtual environment mode is not full. + forward_only: bool = True, + default_catalog: t.Optional[str] = None, +) -> 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, + restate_models=restate_models, + console=mock_console, + forward_only=forward_only, + default_catalog=default_catalog, + ) + 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 + + +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_downstream_model( + mode: VirtualEnvironmentMode = VirtualEnvironmentMode.DEV_ONLY, +) -> SqlModel: + return _dev_only_sql_model("select col from db.a", name="db.b", virtual_environment_mode=mode) + + +@pytest.mark.parametrize( + "choice, expected_category", + [ + (SnapshotChangeCategory.BREAKING, "breaking"), + (SnapshotChangeCategory.NON_BREAKING, "non-breaking"), + ], +) +def test_dev_only_prod_directly_modified_warns( + make_snapshot, mocker: MockerFixture, choice, expected_category +): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], + choice=choice, + ) + plan_builder.build() + + console.log_warning.assert_called_once() + assert console.log_warning.call_args.args == ( + "Models changed in production with `virtual_environment_mode: dev_only` are applied " + "going forward without a backfill, and existing rows are not updated. " + f"Affected models: db.a ({expected_category}). " + 'To rebuild the data, run `sqlmesh plan --restate-model ""`.', + ) + + # The warning must not be repeated when the plan is built again. + plan_builder.build() + console.log_warning.assert_called_once() + + +def test_dev_only_prod_indirect_breaking_warns_with_aggregated_message( + make_snapshot, mocker: MockerFixture +): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), + (_dev_only_downstream_model(), _dev_only_downstream_model()), + ], + choice=SnapshotChangeCategory.BREAKING, + ) + plan_builder.build() + + console.log_warning.assert_called_once() + message = console.log_warning.call_args.args[0] + assert "Affected models: db.a (breaking), db.b (indirect breaking)." in message + + +def test_dev_only_prod_indirect_non_breaking_is_not_listed(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), + (_dev_only_downstream_model(), _dev_only_downstream_model()), + ], + choice=SnapshotChangeCategory.NON_BREAKING, + ) + plan_builder.build() + + console.log_warning.assert_called_once() + assert "Affected models: db.a (non-breaking)." in console.log_warning.call_args.args[0] + + +def test_dev_only_prod_metadata_change_does_not_warn(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + ( + _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_full_mode_does_not_warn(make_snapshot, mocker: MockerFixture): + full = VirtualEnvironmentMode.FULL + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + ( + _dev_only_sql_model("select 1 as col", virtual_environment_mode=full), + _dev_only_sql_model("select 2 as col", virtual_environment_mode=full), + ), + (_dev_only_downstream_model(full), _dev_only_downstream_model(full)), + ], + choice=SnapshotChangeCategory.BREAKING, + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(make_snapshot, mocker: MockerFixture): + full = VirtualEnvironmentMode.FULL + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + ( + _dev_only_sql_model("select 1 as col", name="db.a"), + _dev_only_sql_model("select 2 as col", name="db.a"), + ), + ( + _dev_only_sql_model("select 1 as col", name="db.c", virtual_environment_mode=full), + _dev_only_sql_model("select 2 as col", name="db.c", virtual_environment_mode=full), + ), + ], + choice=SnapshotChangeCategory.BREAKING, + ) + plan_builder.build() + + console.log_warning.assert_called_once() + assert "Affected models: db.a (breaking)." in console.log_warning.call_args.args[0] + + +def test_dev_only_dev_plan_does_not_warn(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], + choice=SnapshotChangeCategory.BREAKING, + is_dev=True, + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +def test_dev_only_prod_added_model_does_not_warn(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, [(None, _dev_only_sql_model("select 2 as col"))] + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +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( + "old_model, new_model", + [ + # Seed changes are always rebuilt. + (_dev_only_seed("old"), _dev_only_seed("new")), + # Breaking kind changes are always rebuilt. + ( + _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") + ), + ), + # So are changes of the virtual environment mode. + ( + _dev_only_sql_model( + "select 1 as col", virtual_environment_mode=VirtualEnvironmentMode.FULL + ), + _dev_only_sql_model("select 2 as col"), + ), + ], + ids=["seed", "kind_change", "mode_change"], +) +def test_dev_only_prod_forced_rebuild_does_not_warn( + make_snapshot, mocker: MockerFixture, old_model, new_model +): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, [(old_model, new_model)], choice=SnapshotChangeCategory.BREAKING + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +@pytest.mark.parametrize( + "old_model, new_model", + [ + ( + _dev_only_sql_model( + "select 1 as col, ds", + kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), + ), + _dev_only_sql_model( + "select 2 as col, ds", + kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), + ), + ), + ( + _dev_only_sql_model("select 1 as col", kind=EmbeddedKind()), + _dev_only_sql_model("select 2 as col", kind=EmbeddedKind()), + ), + ( + 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, + ), + ), + ( + _dev_only_sql_model("select 1 as col", kind=ViewKind()), + _dev_only_sql_model("select 2 as col", kind=ViewKind()), + ), + ( + _dev_only_sql_model( + "select 1 as col, ds", + kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), + ), + _dev_only_sql_model( + "select 2 as col, ds", + kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), + ), + ), + ], + ids=["model_forward_only", "embedded", "external", "view", "disable_restatement"], +) +def test_dev_only_prod_models_without_data_to_backfill_do_not_warn( + make_snapshot, mocker: MockerFixture, old_model, new_model +): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, [(old_model, new_model)], choice=SnapshotChangeCategory.BREAKING + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +def test_dev_only_prod_materialized_view_warns(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + ( + _dev_only_sql_model("select 1 as col", kind=ViewKind(materialized=True)), + _dev_only_sql_model("select 2 as col", kind=ViewKind(materialized=True)), + ) + ], + choice=SnapshotChangeCategory.BREAKING, + ) + plan_builder.build() + console.log_warning.assert_called_once() + assert "Affected models: db.a (breaking)." in console.log_warning.call_args.args[0] + + +@pytest.mark.parametrize("forward_only", [True, False]) +def test_dev_only_prod_warns_regardless_of_forward_only_flag( + make_snapshot, mocker: MockerFixture, forward_only: bool +): + # In the non-full modes Context makes all plans forward-only, so an explicit `--forward-only` + # is indistinguishable from the default and the flag must not affect the warning. + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], + choice=SnapshotChangeCategory.BREAKING, + forward_only=forward_only, + ) + plan_builder.build() + console.log_warning.assert_called_once() + + +def test_dev_only_prod_warning_hides_default_catalog(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + ( + _dev_only_sql_model("select 1 as col", name="other_catalog.db.a"), + _dev_only_sql_model("select 2 as col", name="other_catalog.db.a"), + ), + ( + _dev_only_sql_model("select 1 as col", name="main_catalog.db.b"), + _dev_only_sql_model("select 2 as col", name="main_catalog.db.b"), + ), + ], + choice=SnapshotChangeCategory.BREAKING, + default_catalog="main_catalog", + ) + plan_builder.build() + + console.log_warning.assert_called_once() + assert ( + "Affected models: db.b (breaking), other_catalog.db.a (breaking)." + in console.log_warning.call_args.args[0] + ) + + +def test_dev_only_prod_restated_model_does_not_warn(make_snapshot, mocker: MockerFixture): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], + choice=SnapshotChangeCategory.BREAKING, + restate_models={'"db"."a"'}, + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +def test_dev_only_prod_downstream_of_restated_model_does_not_warn( + make_snapshot, mocker: MockerFixture +): + plan_builder, console = _dev_only_plan_builder( + make_snapshot, + mocker, + [ + (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), + (_dev_only_downstream_model(), _dev_only_downstream_model()), + ], + choice=SnapshotChangeCategory.BREAKING, + restate_models={'"db"."a"'}, + ) + plan_builder.build() + console.log_warning.assert_not_called() + + +def test_dev_only_prod_warning_caps_listed_models(make_snapshot, mocker: MockerFixture): + def changes(count: int) -> t.List[t.Tuple[SqlModel, SqlModel]]: + return [ + ( + _dev_only_sql_model("select 1 as col", name=f"db.model_{i:02d}"), + _dev_only_sql_model("select 2 as col", name=f"db.model_{i:02d}"), + ) + for i in range(count) + ] + + # Exactly at the cap: everything is listed and there is no separate log message. + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, changes(10), choice=SnapshotChangeCategory.BREAKING + ) + plan_builder.build() + assert len(console.log_warning.call_args.args) == 1 + assert "db.model_09 (breaking)." in console.log_warning.call_args.args[0] + assert "more" not in console.log_warning.call_args.args[0] + + # Above the cap: the message is truncated and the full list goes to the log message. + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, changes(12), choice=SnapshotChangeCategory.BREAKING + ) + plan_builder.build() + console.log_warning.assert_called_once() + short_message, long_message = console.log_warning.call_args.args + assert "db.model_09 (breaking) and 2 more." in short_message + assert "db.model_10" not in short_message + assert "db.model_10 (breaking), db.model_11 (breaking)." in long_message + assert "more" not in long_message From 5506073e21c398a54d6fae9f3d4e5f9c0703eddb Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Thu, 3 Dec 2026 11:53:17 +0100 Subject: [PATCH 2/7] docs: shorten dev_only tradeoff bullet in configuration guide Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- docs/guides/configuration.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index c8b140ef22..9ac46de801 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -594,8 +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. Existing rows are not updated, so changes such as a modified `WHERE` clause or a recomputed column only affect data processed after the deployment, and SQLMesh displays a warning when a production plan contains such changes (listing at most 10 models). -- To rebuild the data, explicitly restate the model with `sqlmesh plan --restate-model ""`. This is not done automatically because each model has a single, in-place table in production: a rebuild overwrites that table and there is no previous version to fall back to if it fails. +- 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 --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. From b9ec2b23072554e2bdf4e409fb2e7d92d0e9d203 Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Thu, 3 Dec 2026 12:33:06 +0100 Subject: [PATCH 3/7] refactor(plan): simplify dev_only prod warning and its tests Split the warning into a selector and a formatter, reuse `is_materialized`/`is_materialized_view` for the view and symbolic checks, hoist the category labels to a module constant and always emit a single `log_warning` call. Skip models with a pinned `physical_version`, which `full` mode would not backfill either. Share test helpers and parametrize duplicated tests. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- sqlmesh/core/plan/builder.py | 84 ++++---- tests/core/test_plan.py | 395 ++++++++++++----------------------- 2 files changed, 181 insertions(+), 298 deletions(-) diff --git a/sqlmesh/core/plan/builder.py b/sqlmesh/core/plan/builder.py index e963f41d46..ad2c11da80 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -55,6 +55,31 @@ # 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.""" + message = ( + "Models changed in production with `virtual_environment_mode: dev_only` are applied " + "going forward without a backfill, and existing rows are not updated. " + "Affected models: {models}. " + 'To rebuild the data, run `sqlmesh plan --restate-model ""`.' + ) + shown = affected[:MAX_WARNED_MODELS] + hidden = len(affected) - len(shown) + if not hidden: + return message.format(models=", ".join(shown)), None + return ( + message.format(models=f"{', '.join(shown)} and {hidden} more"), + message.format(models=", ".join(affected)), + ) + class PlanBuilder: """Plan Builder constructs a Plan based on user choices for how they want to backfill, preview, etc. their changes. @@ -594,35 +619,33 @@ def _adjust_snapshot_intervals(self) -> None: 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. + """Warns that breaking and non-breaking changes to `dev_only` models in prod are not backfilled.""" + if self._is_dev: + return + if affected := self._dev_only_prod_changes(restatements): + self._console.log_warning(*_format_dev_only_warning(sorted(affected))) + + def _dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> t.List[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, views, - symbolic models, ...) or that are rebuilt anyway (forced rebuilds, restatements) are not reported. + 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. """ - if self._is_dev: - return - - # Change categories that would trigger a backfill if the model was using `full` mode. - category_labels = { - SnapshotChangeCategory.BREAKING: "breaking", - SnapshotChangeCategory.INDIRECT_BREAKING: "indirect breaking", - SnapshotChangeCategory.NON_BREAKING: "non-breaking", - } - affected: t.Dict[str, str] = {} + affected: t.List[str] = [] 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 not old.is_model or new.virtual_environment_mode.is_full - or new.change_category not in category_labels + or new.change_category not in _DEV_ONLY_WARNED_CATEGORIES or new.model.forward_only - or new.is_symbolic - or (new.is_view and not new.is_materialized_view) + 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) @@ -631,31 +654,8 @@ def _warn_dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> display_name = new.display_name( self.environment_naming_info, self._default_catalog, new.model.dialect ) - affected[display_name] = category_labels[new.change_category] - - if not affected: - return - - def format_models(names: t.List[str]) -> str: - return ", ".join(f"{name} ({affected[name]})" for name in names) - - names = sorted(affected) - shown, hidden = names[:MAX_WARNED_MODELS], names[MAX_WARNED_MODELS:] - message = ( - "Models changed in production with `virtual_environment_mode: dev_only` are applied " - "going forward without a backfill, and existing rows are not updated. " - "Affected models: {models}. " - 'To rebuild the data, run `sqlmesh plan --restate-model ""`.' - ) - if not hidden: - self._console.log_warning(message.format(models=format_models(shown))) - return - - # The full list is only included in the log message when the displayed one is truncated. - self._console.log_warning( - message.format(models=f"{format_models(shown)} and {len(hidden)} more"), - message.format(models=format_models(names)), - ) + affected.append(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): diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index c2444cf598..4e4622bda3 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -35,6 +35,7 @@ ) 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, @@ -4592,10 +4593,51 @@ def _dev_only_sql_model( return SqlModel(name=name, query=parse_one(query), dialect="duckdb", **kwargs) -def _dev_only_downstream_model( +def _dev_only_change( + name: str = "db.a", extra_columns: str = "", **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(f"select 1 as col{extra_columns}", name=name, **kwargs), + _dev_only_sql_model(f"select 2 as col{extra_columns}", name=name, **kwargs), + ) + + +def _dev_only_downstream_change( mode: VirtualEnvironmentMode = VirtualEnvironmentMode.DEV_ONLY, -) -> SqlModel: - return _dev_only_sql_model("select col from db.a", name="db.b", virtual_environment_mode=mode) +) -> 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_warning( + make_snapshot, + mocker: MockerFixture, + changes: t.Sequence[t.Tuple[t.Optional[t.Any], t.Any]], + choice: t.Optional[SnapshotChangeCategory] = SnapshotChangeCategory.BREAKING, + **kwargs: t.Any, +) -> t.Optional[t.Tuple[str, t.Optional[str]]]: + """Builds the plan and returns the `(short, long)` warning arguments, or None if nothing was logged.""" + plan_builder, console = _dev_only_plan_builder( + make_snapshot, mocker, changes, choice=choice, **kwargs + ) + plan_builder.build() + if not console.log_warning.called: + return None + console.log_warning.assert_called_once() + return console.log_warning.call_args.args + + +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( @@ -4609,19 +4651,16 @@ def test_dev_only_prod_directly_modified_warns( make_snapshot, mocker: MockerFixture, choice, expected_category ): plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], - choice=choice, + make_snapshot, mocker, [_dev_only_change()], choice=choice ) plan_builder.build() - console.log_warning.assert_called_once() - assert console.log_warning.call_args.args == ( + console.log_warning.assert_called_once_with( "Models changed in production with `virtual_environment_mode: dev_only` are applied " "going forward without a backfill, and existing rows are not updated. " f"Affected models: db.a ({expected_category}). " 'To rebuild the data, run `sqlmesh plan --restate-model ""`.', + None, ) # The warning must not be repeated when the plan is built again. @@ -4629,39 +4668,22 @@ def test_dev_only_prod_directly_modified_warns( console.log_warning.assert_called_once() -def test_dev_only_prod_indirect_breaking_warns_with_aggregated_message( - make_snapshot, mocker: MockerFixture +@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( + make_snapshot, mocker: MockerFixture, choice, expected_models ): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), - (_dev_only_downstream_model(), _dev_only_downstream_model()), - ], - choice=SnapshotChangeCategory.BREAKING, + warning = _dev_only_warning( + make_snapshot, mocker, [_dev_only_change(), _dev_only_downstream_change()], choice ) - plan_builder.build() - - console.log_warning.assert_called_once() - message = console.log_warning.call_args.args[0] - assert "Affected models: db.a (breaking), db.b (indirect breaking)." in message - - -def test_dev_only_prod_indirect_non_breaking_is_not_listed(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), - (_dev_only_downstream_model(), _dev_only_downstream_model()), - ], - choice=SnapshotChangeCategory.NON_BREAKING, - ) - plan_builder.build() - - console.log_warning.assert_called_once() - assert "Affected models: db.a (non-breaking)." in console.log_warning.call_args.args[0] + assert warning + assert f"Affected models: {expected_models}." in warning[0] def test_dev_only_prod_metadata_change_does_not_warn(make_snapshot, mocker: MockerFixture): @@ -4685,125 +4707,51 @@ def test_dev_only_prod_metadata_change_does_not_warn(make_snapshot, mocker: Mock def test_dev_only_prod_full_mode_does_not_warn(make_snapshot, mocker: MockerFixture): full = VirtualEnvironmentMode.FULL - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - ( - _dev_only_sql_model("select 1 as col", virtual_environment_mode=full), - _dev_only_sql_model("select 2 as col", virtual_environment_mode=full), - ), - (_dev_only_downstream_model(full), _dev_only_downstream_model(full)), - ], - choice=SnapshotChangeCategory.BREAKING, - ) - plan_builder.build() - console.log_warning.assert_not_called() + changes = [_dev_only_change(virtual_environment_mode=full), _dev_only_downstream_change(full)] + assert _dev_only_warning(make_snapshot, mocker, changes) is None def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(make_snapshot, mocker: MockerFixture): - full = VirtualEnvironmentMode.FULL - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - ( - _dev_only_sql_model("select 1 as col", name="db.a"), - _dev_only_sql_model("select 2 as col", name="db.a"), - ), - ( - _dev_only_sql_model("select 1 as col", name="db.c", virtual_environment_mode=full), - _dev_only_sql_model("select 2 as col", name="db.c", virtual_environment_mode=full), - ), - ], - choice=SnapshotChangeCategory.BREAKING, - ) - plan_builder.build() - - console.log_warning.assert_called_once() - assert "Affected models: db.a (breaking)." in console.log_warning.call_args.args[0] + changes = [ + _dev_only_change("db.a"), + _dev_only_change("db.c", virtual_environment_mode=VirtualEnvironmentMode.FULL), + ] + warning = _dev_only_warning(make_snapshot, mocker, changes) + assert warning + assert "Affected models: db.a (breaking)." in warning[0] def test_dev_only_dev_plan_does_not_warn(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], - choice=SnapshotChangeCategory.BREAKING, - is_dev=True, - ) - plan_builder.build() - console.log_warning.assert_not_called() + assert _dev_only_warning(make_snapshot, mocker, [_dev_only_change()], is_dev=True) is None def test_dev_only_prod_added_model_does_not_warn(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, [(None, _dev_only_sql_model("select 2 as col"))] - ) - plan_builder.build() - console.log_warning.assert_not_called() - - -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, - ) + changes = [(None, _dev_only_sql_model("select 2 as col"))] + assert _dev_only_warning(make_snapshot, mocker, changes, choice=None) is None @pytest.mark.parametrize( "old_model, new_model", [ - # Seed changes are always rebuilt. + # Rebuilt anyway: seed changes, breaking kind changes and changes of the virtual environment mode. (_dev_only_seed("old"), _dev_only_seed("new")), - # Breaking kind changes are always rebuilt. ( _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") ), ), - # So are changes of the virtual environment mode. ( - _dev_only_sql_model( - "select 1 as col", virtual_environment_mode=VirtualEnvironmentMode.FULL - ), + _dev_only_sql_model(virtual_environment_mode=VirtualEnvironmentMode.FULL), _dev_only_sql_model("select 2 as col"), ), - ], - ids=["seed", "kind_change", "mode_change"], -) -def test_dev_only_prod_forced_rebuild_does_not_warn( - make_snapshot, mocker: MockerFixture, old_model, new_model -): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, [(old_model, new_model)], choice=SnapshotChangeCategory.BREAKING - ) - plan_builder.build() - console.log_warning.assert_not_called() - - -@pytest.mark.parametrize( - "old_model, new_model", - [ - ( - _dev_only_sql_model( - "select 1 as col, ds", - kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), - ), - _dev_only_sql_model( - "select 2 as col, ds", - kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), - ), - ), - ( - _dev_only_sql_model("select 1 as col", kind=EmbeddedKind()), - _dev_only_sql_model("select 2 as col", kind=EmbeddedKind()), + # Would not be backfilled under `full` mode either. + _dev_only_change( + extra_columns=", ds", + kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), ), + _dev_only_change(physical_version="pinned"), + _dev_only_change(kind=EmbeddedKind()), ( ExternalModel( name="db.a", @@ -4816,48 +4764,36 @@ def test_dev_only_prod_forced_rebuild_does_not_warn( virtual_environment_mode=VirtualEnvironmentMode.DEV_ONLY, ), ), - ( - _dev_only_sql_model("select 1 as col", kind=ViewKind()), - _dev_only_sql_model("select 2 as col", kind=ViewKind()), - ), - ( - _dev_only_sql_model( - "select 1 as col, ds", - kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), - ), - _dev_only_sql_model( - "select 2 as col, ds", - kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), - ), + _dev_only_change(kind=ViewKind()), + _dev_only_change( + extra_columns=", ds", + kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), ), ], - ids=["model_forward_only", "embedded", "external", "view", "disable_restatement"], + ids=[ + "seed", + "kind_change", + "mode_change", + "model_forward_only", + "physical_version", + "embedded", + "external", + "view", + "disable_restatement", + ], ) -def test_dev_only_prod_models_without_data_to_backfill_do_not_warn( +def test_dev_only_prod_models_not_backfilled_in_full_mode_do_not_warn( make_snapshot, mocker: MockerFixture, old_model, new_model ): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, [(old_model, new_model)], choice=SnapshotChangeCategory.BREAKING - ) - plan_builder.build() - console.log_warning.assert_not_called() + assert _dev_only_warning(make_snapshot, mocker, [(old_model, new_model)]) is None def test_dev_only_prod_materialized_view_warns(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - ( - _dev_only_sql_model("select 1 as col", kind=ViewKind(materialized=True)), - _dev_only_sql_model("select 2 as col", kind=ViewKind(materialized=True)), - ) - ], - choice=SnapshotChangeCategory.BREAKING, + warning = _dev_only_warning( + make_snapshot, mocker, [_dev_only_change(kind=ViewKind(materialized=True))] ) - plan_builder.build() - console.log_warning.assert_called_once() - assert "Affected models: db.a (breaking)." in console.log_warning.call_args.args[0] + assert warning + assert "Affected models: db.a (breaking)." in warning[0] @pytest.mark.parametrize("forward_only", [True, False]) @@ -4866,99 +4802,46 @@ def test_dev_only_prod_warns_regardless_of_forward_only_flag( ): # In the non-full modes Context makes all plans forward-only, so an explicit `--forward-only` # is indistinguishable from the default and the flag must not affect the warning. - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], - choice=SnapshotChangeCategory.BREAKING, - forward_only=forward_only, + warning = _dev_only_warning( + make_snapshot, mocker, [_dev_only_change()], forward_only=forward_only ) - plan_builder.build() - console.log_warning.assert_called_once() + assert warning def test_dev_only_prod_warning_hides_default_catalog(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - ( - _dev_only_sql_model("select 1 as col", name="other_catalog.db.a"), - _dev_only_sql_model("select 2 as col", name="other_catalog.db.a"), - ), - ( - _dev_only_sql_model("select 1 as col", name="main_catalog.db.b"), - _dev_only_sql_model("select 2 as col", name="main_catalog.db.b"), - ), - ], - choice=SnapshotChangeCategory.BREAKING, - default_catalog="main_catalog", - ) - plan_builder.build() - - console.log_warning.assert_called_once() - assert ( - "Affected models: db.b (breaking), other_catalog.db.a (breaking)." - in console.log_warning.call_args.args[0] - ) - - -def test_dev_only_prod_restated_model_does_not_warn(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [(_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col"))], - choice=SnapshotChangeCategory.BREAKING, - restate_models={'"db"."a"'}, - ) - plan_builder.build() - console.log_warning.assert_not_called() + changes = [_dev_only_change("other_catalog.db.a"), _dev_only_change("main_catalog.db.b")] + warning = _dev_only_warning(make_snapshot, mocker, changes, default_catalog="main_catalog") + assert warning + assert "Affected models: db.b (breaking), other_catalog.db.a (breaking)." in warning[0] -def test_dev_only_prod_downstream_of_restated_model_does_not_warn( - make_snapshot, mocker: MockerFixture +@pytest.mark.parametrize("with_downstream", [False, True]) +def test_dev_only_prod_restated_model_and_downstream_do_not_warn( + make_snapshot, mocker: MockerFixture, with_downstream: bool ): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, - [ - (_dev_only_sql_model("select 1 as col"), _dev_only_sql_model("select 2 as col")), - (_dev_only_downstream_model(), _dev_only_downstream_model()), - ], - choice=SnapshotChangeCategory.BREAKING, - restate_models={'"db"."a"'}, - ) - plan_builder.build() - console.log_warning.assert_not_called() - - -def test_dev_only_prod_warning_caps_listed_models(make_snapshot, mocker: MockerFixture): - def changes(count: int) -> t.List[t.Tuple[SqlModel, SqlModel]]: - return [ - ( - _dev_only_sql_model("select 1 as col", name=f"db.model_{i:02d}"), - _dev_only_sql_model("select 2 as col", name=f"db.model_{i:02d}"), - ) - for i in range(count) - ] - - # Exactly at the cap: everything is listed and there is no separate log message. - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, changes(10), choice=SnapshotChangeCategory.BREAKING - ) - plan_builder.build() - assert len(console.log_warning.call_args.args) == 1 - assert "db.model_09 (breaking)." in console.log_warning.call_args.args[0] - assert "more" not in console.log_warning.call_args.args[0] - - # Above the cap: the message is truncated and the full list goes to the log message. - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, changes(12), choice=SnapshotChangeCategory.BREAKING - ) - plan_builder.build() - console.log_warning.assert_called_once() - short_message, long_message = console.log_warning.call_args.args - assert "db.model_09 (breaking) and 2 more." in short_message - assert "db.model_10" not in short_message - assert "db.model_10 (breaking), db.model_11 (breaking)." in long_message - assert "more" not in long_message + changes = [_dev_only_change()] + if with_downstream: + changes.append(_dev_only_downstream_change()) + assert _dev_only_warning(make_snapshot, mocker, changes, restate_models={'"db"."a"'}) is None + + +@pytest.mark.parametrize("count", [MAX_WARNED_MODELS, MAX_WARNED_MODELS + 2]) +def test_dev_only_prod_warning_caps_listed_models(make_snapshot, mocker: MockerFixture, count: int): + changes = [_dev_only_change(f"db.model_{i:02d}") for i in range(count)] + warning = _dev_only_warning(make_snapshot, mocker, changes) + assert warning + short_message, long_message = warning + last_shown = f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)" + + if count == MAX_WARNED_MODELS: + # Exactly at the cap: everything is listed and there is no separate log message. + assert f"{last_shown}." in short_message + assert "more" not in short_message + assert long_message is None + else: + # Above the cap: the message is truncated and the full list goes to the log message. + assert f"{last_shown} and 2 more." in short_message + assert f"db.model_{MAX_WARNED_MODELS:02d}" not in short_message + assert long_message + assert f"db.model_{MAX_WARNED_MODELS:02d} (breaking)" in long_message + assert "more" not in long_message From bce3531609d30ba2e3e23754d5e999d416b45460 Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Thu, 3 Dec 2026 13:11:09 +0100 Subject: [PATCH 4/7] fix(plan): address review feedback on dev_only prod warning Report each change only once per plan builder so that rebuilding the plan after a user choice doesn't repeat the warning, and skip it when the backfill is explicitly skipped or empty. Shorten the note in the plans concept page and make the integration test's warning filter robust to keyword-only calls. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- docs/concepts/plans.md | 2 +- sqlmesh/core/plan/builder.py | 20 ++++++++++++++------ tests/core/integration/test_dev_only_vde.py | 5 +++-- tests/core/test_plan.py | 15 ++++++++++++++- 4 files changed, 32 insertions(+), 10 deletions(-) diff --git a/docs/concepts/plans.md b/docs/concepts/plans.md index e08fd97b96..943ab865a3 100644 --- a/docs/concepts/plans.md +++ b/docs/concepts/plans.md @@ -52,7 +52,7 @@ If any downstream models contain a `select *` from the model, SQLMesh attempts t | [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 each model has a single in-place table in production, so breaking and non-breaking changes are applied going forward without a backfill, and SQLMesh displays a warning listing the affected models. The warning only appears for changes that would have been rebuilt under the default `full` mode, so models with a model-level `forward_only` kind, plain (non-materialized) views, symbolic models (embedded and external), and models with `disable_restatement` enabled are not affected. Use `sqlmesh plan --restate-model ""` to rebuild the data. Note that `--restate-model` can't rebuild models with `disable_restatement` enabled. + 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 --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/sqlmesh/core/plan/builder.py b/sqlmesh/core/plan/builder.py index ad2c11da80..cdee7c7c4e 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -213,6 +213,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 @@ -619,13 +621,19 @@ def _adjust_snapshot_intervals(self) -> None: 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.""" - if self._is_dev: + """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 - if affected := self._dev_only_prod_changes(restatements): + 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.List[str]: + 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 @@ -634,7 +642,7 @@ def _dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> t.Li physical versions, views, symbolic models, ...) or that are rebuilt anyway (forced rebuilds, restatements) are not reported. """ - affected: t.List[str] = [] + 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 @@ -654,7 +662,7 @@ def _dev_only_prod_changes(self, restatements: t.Collection[SnapshotId]) -> t.Li display_name = new.display_name( self.environment_naming_info, self._default_catalog, new.model.dialect ) - affected.append(f"{display_name} ({_DEV_ONLY_WARNED_CATEGORIES[new.change_category]})") + 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: diff --git a/tests/core/integration/test_dev_only_vde.py b/tests/core/integration/test_dev_only_vde.py index 35dc40f418..b82ebdbc8c 100644 --- a/tests/core/integration/test_dev_only_vde.py +++ b/tests/core/integration/test_dev_only_vde.py @@ -100,9 +100,10 @@ def test_virtual_environment_mode_dev_only( assert not plan_prod.requires_backfill assert not plan_prod.missing_intervals dev_only_warnings = [ - call.args[0] + message for call in log_warning_spy.call_args_list - if "virtual_environment_mode: dev_only" in call.args[0] + 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] diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index 4e4622bda3..a820bb93c7 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -4530,6 +4530,7 @@ def _dev_only_plan_builder( # Context always sets forward_only=True when the virtual environment mode is not full. forward_only: bool = True, default_catalog: t.Optional[str] = None, + **builder_kwargs: t.Any, ) -> t.Tuple[PlanBuilder, t.Any]: """Creates a plan builder for a list of `(old_model, new_model)` changes. @@ -4577,6 +4578,7 @@ def _dev_only_plan_builder( console=mock_console, forward_only=forward_only, default_catalog=default_catalog, + **builder_kwargs, ) if choice is not None: for name, snapshot in new_snapshots.items(): @@ -4663,7 +4665,10 @@ def test_dev_only_prod_directly_modified_warns( None, ) - # The warning must not be repeated when the plan is built again. + # The warning must not be repeated when the plan is built again, including after the plan is + # invalidated by a user choice, which happens in the interactive flow. + snapshot = next(iter(plan_builder.build().context_diff.snapshots.values())) + plan_builder.set_choice(snapshot, choice) plan_builder.build() console.log_warning.assert_called_once() @@ -4721,6 +4726,14 @@ def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(make_snapshot, moc assert "Affected models: db.a (breaking)." in warning[0] +@pytest.mark.parametrize("option", ["skip_backfill", "empty_backfill"]) +def test_dev_only_prod_explicit_no_backfill_does_not_warn( + make_snapshot, mocker: MockerFixture, option: str +): + builder_options: t.Dict[str, t.Any] = {option: True} + assert _dev_only_warning(make_snapshot, mocker, [_dev_only_change()], **builder_options) is None + + def test_dev_only_dev_plan_does_not_warn(make_snapshot, mocker: MockerFixture): assert _dev_only_warning(make_snapshot, mocker, [_dev_only_change()], is_dev=True) is None From 384c7869a2ce5fb768e4077d23c1a5de0f85d762 Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Fri, 4 Dec 2026 09:24:28 +0100 Subject: [PATCH 5/7] test(plan): simplify dev_only prod warning tests Use fixtures instead of threading `make_snapshot` and `mocker` through every test, assert on the listed models directly, collect the cases that must not warn into a single parametrized test and split the dedupe and cap tests into straight-line tests. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- tests/core/test_plan.py | 352 ++++++++++++++++++++-------------------- 1 file changed, 174 insertions(+), 178 deletions(-) diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index a820bb93c7..2656a128b2 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -4526,10 +4526,8 @@ def _dev_only_plan_builder( *, choice: t.Optional[SnapshotChangeCategory] = None, is_dev: bool = False, - restate_models: t.Optional[t.Set[str]] = None, # Context always sets forward_only=True when the virtual environment mode is not full. forward_only: bool = True, - default_catalog: t.Optional[str] = None, **builder_kwargs: t.Any, ) -> t.Tuple[PlanBuilder, t.Any]: """Creates a plan builder for a list of `(old_model, new_model)` changes. @@ -4574,10 +4572,8 @@ def _dev_only_plan_builder( plan_builder = PlanBuilder( context_diff, is_dev=is_dev, - restate_models=restate_models, console=mock_console, forward_only=forward_only, - default_catalog=default_catalog, **builder_kwargs, ) if choice is not None: @@ -4587,6 +4583,46 @@ def _dev_only_plan_builder( 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) -> str: + return self.short.split("Affected models: ")[1].split(". To rebuild")[0] + + +@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: @@ -4595,13 +4631,11 @@ def _dev_only_sql_model( return SqlModel(name=name, query=parse_one(query), dialect="duckdb", **kwargs) -def _dev_only_change( - name: str = "db.a", extra_columns: str = "", **kwargs: t.Any -) -> t.Tuple[SqlModel, SqlModel]: +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(f"select 1 as col{extra_columns}", name=name, **kwargs), - _dev_only_sql_model(f"select 2 as col{extra_columns}", name=name, **kwargs), + _dev_only_sql_model("select 1 as col, ds", name=name, **kwargs), + _dev_only_sql_model("select 2 as col, ds", name=name, **kwargs), ) @@ -4613,24 +4647,6 @@ def _dev_only_downstream_change( return model, model -def _dev_only_warning( - make_snapshot, - mocker: MockerFixture, - changes: t.Sequence[t.Tuple[t.Optional[t.Any], t.Any]], - choice: t.Optional[SnapshotChangeCategory] = SnapshotChangeCategory.BREAKING, - **kwargs: t.Any, -) -> t.Optional[t.Tuple[str, t.Optional[str]]]: - """Builds the plan and returns the `(short, long)` warning arguments, or None if nothing was logged.""" - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, changes, choice=choice, **kwargs - ) - plan_builder.build() - if not console.log_warning.called: - return None - console.log_warning.assert_called_once() - return console.log_warning.call_args.args - - def _dev_only_seed(content: str) -> SeedModel: return SeedModel( name="db.a", @@ -4649,15 +4665,9 @@ def _dev_only_seed(content: str) -> SeedModel: (SnapshotChangeCategory.NON_BREAKING, "non-breaking"), ], ) -def test_dev_only_prod_directly_modified_warns( - make_snapshot, mocker: MockerFixture, choice, expected_category -): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, mocker, [_dev_only_change()], choice=choice - ) - plan_builder.build() - - console.log_warning.assert_called_once_with( +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. " f"Affected models: db.a ({expected_category}). " @@ -4665,10 +4675,17 @@ def test_dev_only_prod_directly_modified_warns( None, ) - # The warning must not be repeated when the plan is built again, including after the plan is - # invalidated by a user choice, which happens in the interactive flow. - snapshot = next(iter(plan_builder.build().context_diff.snapshots.values())) - plan_builder.set_choice(snapshot, choice) + +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() @@ -4681,26 +4698,19 @@ def test_dev_only_prod_directly_modified_warns( (SnapshotChangeCategory.NON_BREAKING, "db.a (non-breaking)"), ], ) -def test_dev_only_prod_downstream_models( - make_snapshot, mocker: MockerFixture, choice, expected_models -): - warning = _dev_only_warning( - make_snapshot, mocker, [_dev_only_change(), _dev_only_downstream_change()], choice - ) - assert warning - assert f"Affected models: {expected_models}." in warning[0] +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(make_snapshot, mocker: MockerFixture): - plan_builder, console = _dev_only_plan_builder( - make_snapshot, - mocker, +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() @@ -4710,151 +4720,137 @@ def test_dev_only_prod_metadata_change_does_not_warn(make_snapshot, mocker: Mock console.log_warning.assert_not_called() -def test_dev_only_prod_full_mode_does_not_warn(make_snapshot, mocker: MockerFixture): - full = VirtualEnvironmentMode.FULL - changes = [_dev_only_change(virtual_environment_mode=full), _dev_only_downstream_change(full)] - assert _dev_only_warning(make_snapshot, mocker, changes) is None - - -def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(make_snapshot, mocker: MockerFixture): - changes = [ - _dev_only_change("db.a"), - _dev_only_change("db.c", virtual_environment_mode=VirtualEnvironmentMode.FULL), - ] - warning = _dev_only_warning(make_snapshot, mocker, changes) - assert warning - assert "Affected models: db.a (breaking)." in warning[0] +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)" -@pytest.mark.parametrize("option", ["skip_backfill", "empty_backfill"]) -def test_dev_only_prod_explicit_no_backfill_does_not_warn( - make_snapshot, mocker: MockerFixture, option: str -): - builder_options: t.Dict[str, t.Any] = {option: True} - assert _dev_only_warning(make_snapshot, mocker, [_dev_only_change()], **builder_options) is None +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_dev_plan_does_not_warn(make_snapshot, mocker: MockerFixture): - assert _dev_only_warning(make_snapshot, mocker, [_dev_only_change()], is_dev=True) is None +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_added_model_does_not_warn(make_snapshot, mocker: MockerFixture): - changes = [(None, _dev_only_sql_model("select 2 as col"))] - assert _dev_only_warning(make_snapshot, mocker, changes, choice=None) is None +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)" -@pytest.mark.parametrize( - "old_model, new_model", - [ +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. - (_dev_only_seed("old"), _dev_only_seed("new")), - ( - _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") - ), + 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", ), - ( - _dev_only_sql_model(virtual_environment_mode=VirtualEnvironmentMode.FULL), - _dev_only_sql_model("select 2 as col"), + 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. - _dev_only_change( - extra_columns=", ds", - kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True), + pytest.param( + [ + _dev_only_change( + kind=IncrementalByTimeRangeKind(time_column="ds", forward_only=True) + ) + ], + {}, + id="model_forward_only", ), - _dev_only_change(physical_version="pinned"), - _dev_only_change(kind=EmbeddedKind()), - ( - 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, - ), + 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", ), - _dev_only_change(kind=ViewKind()), - _dev_only_change( - extra_columns=", ds", - kind=IncrementalByTimeRangeKind(time_column="ds", disable_restatement=True), + 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", ), - ], - ids=[ - "seed", - "kind_change", - "mode_change", - "model_forward_only", - "physical_version", - "embedded", - "external", - "view", - "disable_restatement", - ], -) -def test_dev_only_prod_models_not_backfilled_in_full_mode_do_not_warn( - make_snapshot, mocker: MockerFixture, old_model, new_model -): - assert _dev_only_warning(make_snapshot, mocker, [(old_model, new_model)]) is None - - -def test_dev_only_prod_materialized_view_warns(make_snapshot, mocker: MockerFixture): - warning = _dev_only_warning( - make_snapshot, mocker, [_dev_only_change(kind=ViewKind(materialized=True))] - ) - assert warning - assert "Affected models: db.a (breaking)." in warning[0] + ] -@pytest.mark.parametrize("forward_only", [True, False]) -def test_dev_only_prod_warns_regardless_of_forward_only_flag( - make_snapshot, mocker: MockerFixture, forward_only: bool -): - # In the non-full modes Context makes all plans forward-only, so an explicit `--forward-only` - # is indistinguishable from the default and the flag must not affect the warning. - warning = _dev_only_warning( - make_snapshot, mocker, [_dev_only_change()], forward_only=forward_only - ) - assert warning +@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_hides_default_catalog(make_snapshot, mocker: MockerFixture): - changes = [_dev_only_change("other_catalog.db.a"), _dev_only_change("main_catalog.db.b")] - warning = _dev_only_warning(make_snapshot, mocker, changes, default_catalog="main_catalog") +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 "Affected models: db.b (breaking), other_catalog.db.a (breaking)." in warning[0] + assert warning.models.endswith(f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)") + assert "more" not in warning.short + assert warning.long is None -@pytest.mark.parametrize("with_downstream", [False, True]) -def test_dev_only_prod_restated_model_and_downstream_do_not_warn( - make_snapshot, mocker: MockerFixture, with_downstream: bool -): - changes = [_dev_only_change()] - if with_downstream: - changes.append(_dev_only_downstream_change()) - assert _dev_only_warning(make_snapshot, mocker, changes, restate_models={'"db"."a"'}) is None - - -@pytest.mark.parametrize("count", [MAX_WARNED_MODELS, MAX_WARNED_MODELS + 2]) -def test_dev_only_prod_warning_caps_listed_models(make_snapshot, mocker: MockerFixture, count: int): - changes = [_dev_only_change(f"db.model_{i:02d}") for i in range(count)] - warning = _dev_only_warning(make_snapshot, mocker, changes) +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 - short_message, long_message = warning - last_shown = f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)" - - if count == MAX_WARNED_MODELS: - # Exactly at the cap: everything is listed and there is no separate log message. - assert f"{last_shown}." in short_message - assert "more" not in short_message - assert long_message is None - else: - # Above the cap: the message is truncated and the full list goes to the log message. - assert f"{last_shown} and 2 more." in short_message - assert f"db.model_{MAX_WARNED_MODELS:02d}" not in short_message - assert long_message - assert f"db.model_{MAX_WARNED_MODELS:02d} (breaking)" in long_message - assert "more" not in long_message + assert warning.models.endswith(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 From da55dd88c610e4f6bee4fa96dd533bad472ef73f Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Fri, 4 Dec 2026 10:06:40 +0100 Subject: [PATCH 6/7] fix(plan): list dev_only prod warning models one per line The affected models were joined into one long sentence, which was hard to read and to scan for the models that matter. List them as bullets, with a trailing "... and N more" entry when the list is truncated. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- sqlmesh/core/plan/builder.py | 23 +++++++++-------- tests/core/integration/test_dev_only_vde.py | 2 +- tests/core/test_plan.py | 28 +++++++++++++-------- 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/sqlmesh/core/plan/builder.py b/sqlmesh/core/plan/builder.py index cdee7c7c4e..1eb2268b75 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -65,20 +65,21 @@ 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.""" - message = ( - "Models changed in production with `virtual_environment_mode: dev_only` are applied " - "going forward without a backfill, and existing rows are not updated. " - "Affected models: {models}. " - 'To rebuild the data, run `sqlmesh plan --restate-model ""`.' - ) + + 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 --restate-model ""`.' + ) + shown = affected[:MAX_WARNED_MODELS] hidden = len(affected) - len(shown) if not hidden: - return message.format(models=", ".join(shown)), None - return ( - message.format(models=f"{', '.join(shown)} and {hidden} more"), - message.format(models=", ".join(affected)), - ) + return format_message(shown), None + return format_message([*shown, f"... and {hidden} more"]), format_message(affected) class PlanBuilder: diff --git a/tests/core/integration/test_dev_only_vde.py b/tests/core/integration/test_dev_only_vde.py index b82ebdbc8c..dcee8235a0 100644 --- a/tests/core/integration/test_dev_only_vde.py +++ b/tests/core/integration/test_dev_only_vde.py @@ -107,7 +107,7 @@ def test_virtual_environment_mode_dev_only( ] assert len(dev_only_warnings) == 1 assert "without a backfill" in dev_only_warnings[0] - assert "Affected models: sushi.waiter_revenue_by_day (breaking)." 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) diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index 2656a128b2..48a19ff05d 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -4590,8 +4590,10 @@ class _DevOnlyWarning(t.NamedTuple): long: t.Optional[str] @property - def models(self) -> str: - return self.short.split("Affected models: ")[1].split(". To rebuild")[0] + 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 @@ -4669,8 +4671,8 @@ def test_dev_only_prod_directly_modified_warns(dev_only_warning, choice, expecte 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. " - f"Affected models: db.a ({expected_category}). " + "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 --restate-model ""`.', None, ) @@ -4693,9 +4695,9 @@ def test_dev_only_prod_warning_is_not_repeated(dev_only_plan_builder): @pytest.mark.parametrize( "choice, expected_models", [ - (SnapshotChangeCategory.BREAKING, "db.a (breaking), db.b (indirect breaking)"), + (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)"), + (SnapshotChangeCategory.NON_BREAKING, ["db.a (non-breaking)"]), ], ) def test_dev_only_prod_downstream_models(dev_only_warning, choice, expected_models): @@ -4727,12 +4729,12 @@ def test_dev_only_prod_mixed_modes_only_lists_dev_only_models(dev_only_warning): _dev_only_change("db.c", virtual_environment_mode=VirtualEnvironmentMode.FULL), ] ) - assert warning and warning.models == "db.a (breaking)" + 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)" + assert warning and warning.models == ["db.a (breaking)"] def test_dev_only_prod_warns_without_forward_only_flag(dev_only_warning): @@ -4746,7 +4748,7 @@ def test_dev_only_prod_warning_hides_default_catalog(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)" + assert warning and warning.models == ["db.b (breaking)", "other_catalog.db.a (breaking)"] def _no_warning_cases() -> t.List[t.Any]: @@ -4839,7 +4841,8 @@ 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 warning.models.endswith(f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking)") + 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 @@ -4848,7 +4851,10 @@ 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.endswith(f"db.model_{MAX_WARNED_MODELS - 1:02d} (breaking) and 2 more") + 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 From cf5384fa5377f96bcbc62e3a46b18daeb1eb49d2 Mon Sep 17 00:00:00 2001 From: EhabEasee Date: Fri, 4 Dec 2026 11:23:13 +0100 Subject: [PATCH 7/7] fix(plan): target prod in the dev_only restate hint Make the recovery command in the warning and docs explicit with `sqlmesh plan prod --restate-model`, so following it can't restate the default development environment instead. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: EhabEasee --- docs/concepts/plans.md | 2 +- docs/guides/configuration.md | 2 +- sqlmesh/core/plan/builder.py | 2 +- tests/core/test_plan.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/concepts/plans.md b/docs/concepts/plans.md index 943ab865a3..a518e7abdb 100644 --- a/docs/concepts/plans.md +++ b/docs/concepts/plans.md @@ -52,7 +52,7 @@ If any downstream models contain a `select *` from the model, SQLMesh attempts t | [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 --restate-model ""` to rebuild the data. + 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 b03521ed4a..b395ea8666 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -594,7 +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 --restate-model ""`. +- 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/plan/builder.py b/sqlmesh/core/plan/builder.py index a793a103d8..937c99a783 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -80,7 +80,7 @@ def format_message(models: t.List[str]) -> str: "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 --restate-model ""`.' + + '\n\nTo rebuild the data, run `sqlmesh plan prod --restate-model ""`.' ) shown = affected[:MAX_WARNED_MODELS] diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index 19e31b5775..bfa5fb8a9f 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -5212,7 +5212,7 @@ def test_dev_only_prod_directly_modified_warns(dev_only_warning, choice, expecte "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 --restate-model ""`.', + 'To rebuild the data, run `sqlmesh plan prod --restate-model ""`.', None, )