Skip to content
Open
3 changes: 3 additions & 0 deletions docs/concepts/plans.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<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.

Expand Down
1 change: 1 addition & 0 deletions docs/guides/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<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.
Expand Down
1 change: 1 addition & 0 deletions sqlmesh/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -1975,6 +1975,7 @@ def plan_builder(
},
explain=explain or False,
ignore_cron=ignore_cron or False,
default_catalog=self.default_catalog,
)

def apply(
Expand Down
82 changes: 82 additions & 0 deletions sqlmesh/core/plan/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<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.

Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
17 changes: 16 additions & 1 deletion tests/core/integration/test_dev_only_vde.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"
)
Expand Down Expand Up @@ -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")

Expand Down
Loading