diff --git a/sqlmesh/core/plan/definition.py b/sqlmesh/core/plan/definition.py index 866299eff8..0204cd5deb 100644 --- a/sqlmesh/core/plan/definition.py +++ b/sqlmesh/core/plan/definition.py @@ -120,6 +120,16 @@ def requires_backfill(self) -> bool: def has_changes(self) -> bool: return self.context_diff.has_changes + @property + def is_initial_plan(self) -> bool: + """Whether the plan is creating or completing an environment built from scratch.""" + if self.context_diff.is_new_environment: + return not self.context_diff.create_from_env_exists + return ( + self.context_diff.is_unfinalized_environment + and self.context_diff.previous_finalized_snapshots == [] + ) + @property def has_unmodified_unpromoted(self) -> bool: """Is the plan for an existing dev environment, has the include unmodified flag, and contains unmodified nodes that have not been promoted.""" @@ -197,6 +207,7 @@ def missing_intervals(self) -> t.List[SnapshotIntervals]: end_override_per_model=self.end_override_per_model, end_bounded=self.end_bounded, ignore_cron=self.ignore_cron, + is_initial_plan=self.is_initial_plan, ).items() if snapshot.is_model and missing ] @@ -280,6 +291,7 @@ def to_evaluatable(self) -> EvaluatablePlan: end_bounded=self.end_bounded, ensure_finalized_snapshots=self.ensure_finalized_snapshots, ignore_cron=self.ignore_cron, + is_initial_plan=self.is_initial_plan, directly_modified_snapshots=sorted(self.directly_modified), indirectly_modified_snapshots={ s.name: sorted(snapshot_ids) for s, snapshot_ids in self.indirectly_modified.items() @@ -325,6 +337,7 @@ class EvaluatablePlan(PydanticModel): end_bounded: bool ensure_finalized_snapshots: bool ignore_cron: bool = False + is_initial_plan: bool = False directly_modified_snapshots: t.List[SnapshotId] indirectly_modified_snapshots: t.Dict[str, t.List[SnapshotId]] metadata_updated_snapshots: t.List[SnapshotId] diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..b031e05435 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -601,6 +601,7 @@ def _missing_intervals( ignore_cron=plan.ignore_cron, start_override_per_model=plan.start_override_per_model, end_override_per_model=plan.end_override_per_model, + is_initial_plan=plan.is_initial_plan, ) def _get_audit_only_snapshots( diff --git a/sqlmesh/core/scheduler.py b/sqlmesh/core/scheduler.py index 7345d92888..b67a247168 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -1059,6 +1059,7 @@ def merged_missing_intervals( end_override_per_model: t.Optional[t.Dict[str, datetime]] = None, ignore_cron: bool = False, end_bounded: bool = False, + is_initial_plan: bool = False, ) -> SnapshotToIntervals: """Find the largest contiguous date interval parameters based only on what is missing. @@ -1079,6 +1080,7 @@ def merged_missing_intervals( ignore_cron: Whether to ignore the node's cron schedule. end_bounded: If set to true, the returned intervals will be bounded by the target end date, disregarding lookback, allow_partials, and other attributes that could cause the intervals to exceed the target end date. + is_initial_plan: Use the plan start when inferring a model start from its cron. """ restatements = restatements or {} validate_date_range(start, end) @@ -1094,6 +1096,7 @@ def merged_missing_intervals( end_override_per_model=end_override_per_model, ignore_cron=ignore_cron, end_bounded=end_bounded, + is_initial_plan=is_initial_plan, ) @@ -1109,6 +1112,7 @@ def compute_interval_params( end_override_per_model: t.Optional[t.Dict[str, datetime]] = None, ignore_cron: bool = False, end_bounded: bool = False, + is_initial_plan: bool = False, ) -> SnapshotToIntervals: """Find the largest contiguous date interval parameters based only on what is missing. @@ -1129,6 +1133,7 @@ def compute_interval_params( ignore_cron: Whether to ignore the node's cron schedule. end_bounded: If set to true, the returned intervals will be bounded by the target end date, disregarding lookback, allow_partials, and other attributes that could cause the intervals to exceed the target end date. + is_initial_plan: Use the plan start when inferring a model start from its cron. Returns: A dict containing all snapshots needing to be run with their associated interval params. @@ -1146,6 +1151,7 @@ def compute_interval_params( end_override_per_model=end_override_per_model, ignore_cron=ignore_cron, end_bounded=end_bounded, + is_initial_plan=is_initial_plan, ).items(): contiguous_batch = [] next_batch: Intervals = [] diff --git a/sqlmesh/core/snapshot/definition.py b/sqlmesh/core/snapshot/definition.py index 0cdb033be0..d5181e3895 100644 --- a/sqlmesh/core/snapshot/definition.py +++ b/sqlmesh/core/snapshot/definition.py @@ -2045,6 +2045,7 @@ def missing_intervals( end_override_per_model: t.Optional[t.Dict[str, datetime]] = None, ignore_cron: bool = False, end_bounded: bool = False, + is_initial_plan: bool = False, ) -> t.Dict[Snapshot, Intervals]: """Returns all missing intervals given a collection of snapshots.""" if not isinstance(snapshots, dict): @@ -2085,9 +2086,14 @@ def missing_intervals( continue snapshot_end_date = existing_interval_end + # For a first plan, anchor cron-based inference to the start of the backfill window. + # This lets parent models supply the early intervals their children need. + start_reference = ( + snapshot_start_date if is_initial_plan and not restated_interval else snapshot_end_date + ) snapshot_start_date = max( to_datetime(snapshot_start_date), - to_datetime(start_date(snapshot, snapshots, cache, relative_to=snapshot_end_date)), + to_datetime(start_date(snapshot, snapshots, cache, relative_to=start_reference)), ) if snapshot_start_date > to_datetime(snapshot_end_date): continue diff --git a/tests/core/integration/test_cron.py b/tests/core/integration/test_cron.py index fa327ac36f..1da46fdfdb 100644 --- a/tests/core/integration/test_cron.py +++ b/tests/core/integration/test_cron.py @@ -1,15 +1,22 @@ from __future__ import annotations import typing as t +from contextlib import closing +from pathlib import Path + import pytest import time_machine +from pytest_mock.plugin import MockerFixture from sqlmesh.core import dialect as d +from sqlmesh.core.config import Config, ModelDefaultsConfig +from sqlmesh.core.context import Context from sqlmesh.core.model import ( SqlModel, load_sql_based_model, ) from sqlmesh.core.plan import SnapshotIntervals +from sqlmesh.core.plan.evaluator import BuiltInPlanEvaluator from sqlmesh.utils.date import to_timestamp from tests.core.integration.utils import add_projection_to_model @@ -83,6 +90,68 @@ def test_cron_not_aligned_with_day_boundary( ] +@time_machine.travel("2024-01-05 00:00:00 UTC", tick=False) +@pytest.mark.parametrize( + "environment, start, retry", + [("prod", None, False), ("dev", "2024-01-01", False), ("prod", None, True)], + ids=["prod", "dev-with-start", "prod-retry"], +) +def test_first_plan_backfills_parent_from_plan_start( + tmp_path: Path, mocker: MockerFixture, environment: str, start: t.Optional[str], retry: bool +): + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + with closing(Context(paths=tmp_path, config=config)) as context: + forward_only = "true" if retry else "false" + parent = context.upsert_model( + load_sql_based_model( + d.parse(f""" + MODEL ( + name test.parent, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + batch_size 1, + forward_only {forward_only} + ) + ); + SELECT CAST(@start_ds AS DATE) AS ds; + """) + ) + ) + context.upsert_model( + load_sql_based_model( + d.parse(""" + MODEL (name test.child, kind FULL, start '2024-01-01'); + SELECT ds FROM test.parent; + """) + ) + ) + + plan = context.plan_builder(environment, start=start, skip_tests=True).build() + if retry: + # Forward-only models backfill after the production environment record is saved. + backfill = mocker.patch.object( + BuiltInPlanEvaluator, + "visit_backfill_stage", + side_effect=RuntimeError("interrupted"), + ) + with pytest.raises(RuntimeError, match="interrupted"): + context.apply(plan) + mocker.stop(backfill) + assert context.state_sync.get_environment(environment) is not None + plan = context.plan_builder(environment, start=start, skip_tests=True).build() + + parent_intervals = next( + item.intervals for item in plan.missing_intervals if item.snapshot_id.name == parent.fqn + ) + assert parent_intervals[0][0] == to_timestamp("2024-01-01") + assert parent_intervals[-1][1] == to_timestamp("2024-01-05") + + context.apply(plan) + + schema = "test" if environment == "prod" else "test__dev" + assert context.engine_adapter.fetchone(f"SELECT COUNT(*) FROM {schema}.child") == (4,) + + @time_machine.travel("2023-01-08 00:00:00 UTC") def test_cron_not_aligned_with_day_boundary_new_model(init_and_plan_context: t.Callable): context, _ = init_and_plan_context("examples/sushi")