diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..e9211d3d14 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -301,17 +301,16 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: snapshots_to_intervals = self._missing_intervals( plan, snapshots_by_name, deployability_index ) - needs_backfill = ( - not plan.empty_backfill and not plan.skip_backfill and bool(snapshots_to_intervals) - ) missing_intervals_before_promote: SnapshotToIntervals = {} missing_intervals_after_promote: SnapshotToIntervals = {} - if needs_backfill: + if not plan.empty_backfill and not plan.skip_backfill: for snapshot, intervals in snapshots_to_intervals.items(): if snapshot.snapshot_id in before_promote_snapshots: missing_intervals_before_promote[snapshot] = intervals elif snapshot.snapshot_id in after_promote_snapshots: missing_intervals_after_promote[snapshot] = intervals + # Only snapshots selected for backfill count, since the others are never backfilled + needs_backfill = bool(missing_intervals_before_promote or missing_intervals_after_promote) promoted_snapshots, demoted_snapshots, demoted_environment_naming_info = ( self._get_promoted_demoted_snapshots(plan, existing_environment) @@ -348,15 +347,17 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: if audit_only_snapshots: stages.append(AuditOnlyRunStage(snapshots=list(audit_only_snapshots.values()))) + # When only one backfill stage runs, it also creates missing tables for selected snapshots + # from the other phase. Those snapshots can have no intervals to backfill yet. if missing_intervals_before_promote: stages.append( BackfillStage( snapshot_to_intervals=missing_intervals_before_promote, - selected_snapshot_ids={ - s_id - for s_id in before_promote_snapshots - if plan.is_selected_for_backfill(s_id.name) - }, + selected_snapshot_ids=( + before_promote_snapshots + if missing_intervals_after_promote + else all_selected_for_backfill_snapshots + ), all_snapshots=snapshots_by_name, deployability_index=deployability_index, ) @@ -406,11 +407,11 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: stages.append( BackfillStage( snapshot_to_intervals=missing_intervals_after_promote, - selected_snapshot_ids={ - s_id - for s_id in after_promote_snapshots - if plan.is_selected_for_backfill(s_id.name) - }, + selected_snapshot_ids=( + after_promote_snapshots + if missing_intervals_before_promote + else all_selected_for_backfill_snapshots + ), all_snapshots=snapshots_by_name, deployability_index=deployability_index, ) diff --git a/sqlmesh/core/scheduler.py b/sqlmesh/core/scheduler.py index 7345d92888..33cb636a05 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -505,12 +505,14 @@ def run_merged_intervals( selected_models=selected_models, ) - # We only need to create physical tables if the snapshot is not representative or if it - # needs backfill + # A deployable snapshot that has never run can need a table even if its first + # interval isn't ready. The evaluator checks whether the table already exists. snapshots_to_create_candidates = [ s for s in selected_snapshots - if not deployability_index.is_representative(s) or s in batched_intervals + if not deployability_index.is_representative(s) + or s in batched_intervals + or (not s.intervals and deployability_index.is_deployable(s)) ] snapshots_to_create = { s.snapshot_id diff --git a/tests/core/integration/test_cron.py b/tests/core/integration/test_cron.py index fa327ac36f..b8e86af886 100644 --- a/tests/core/integration/test_cron.py +++ b/tests/core/integration/test_cron.py @@ -1,10 +1,15 @@ from __future__ import annotations import typing as t +from contextlib import closing +from pathlib import Path + import pytest import time_machine 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, @@ -140,6 +145,94 @@ def test_cron_not_aligned_with_day_boundary_new_model(init_and_plan_context: t.C ] +@time_machine.travel("2024-01-02 01:49:00 UTC", tick=False) +@pytest.mark.parametrize( + "environment, downstream_kind", + [ + ("dev", "FULL"), + ("prod", "FULL"), + ("prod", "INCREMENTAL_BY_TIME_RANGE (time_column event_date, forward_only true)"), + ], + ids=["dev", "prod-before-promotion", "prod-after-promotion"], +) +def test_plan_creates_new_model_table_before_first_cron_interval( + tmp_path: Path, environment: str, downstream_kind: str +): + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + with closing(Context(paths=tmp_path, config=config)) as context: + context.upsert_model( + load_sql_based_model( + d.parse(""" + MODEL (name test.source, kind FULL, start '2024-01-01'); + SELECT 1 AS id, CAST('2024-01-01' AS DATE) AS event_date; + """) + ) + ) + context.apply(context.plan_builder("prod", skip_tests=True).build()) + + context.upsert_model( + load_sql_based_model( + d.parse(""" + MODEL (name test.upstream, kind FULL, cron '20 8 * * *'); + SELECT id, event_date FROM test.source; + """) + ) + ) + downstream = context.upsert_model( + load_sql_based_model( + d.parse(f""" + MODEL (name test.downstream, kind {downstream_kind}); + SELECT id, event_date FROM test.upstream; + """) + ) + ) + + plan = context.plan_builder(environment, skip_tests=True).build() + assert {intervals.snapshot_id.name for intervals in plan.missing_intervals} == { + downstream.fqn + } + context.apply(plan) + + schema = "test" if environment == "prod" else "test__dev" + assert context.fetchdf(f"SELECT id FROM {schema}.upstream").empty + assert context.fetchdf(f"SELECT id FROM {schema}.downstream").empty + + with time_machine.travel("2024-01-02 09:00:00 UTC", tick=False): + context.run(environment) + assert context.fetchdf(f"SELECT id FROM {schema}.upstream")["id"].tolist() == [1] + + +@time_machine.travel("2023-01-08 00:00:00 UTC", tick=False) +@pytest.mark.parametrize("environment", ["dev", "prod"]) +def test_selected_new_model_with_cron_not_elapsed_is_created( + init_and_plan_context: t.Callable, environment: str +): + context, plan = init_and_plan_context("examples/sushi") + context.apply(plan) + + with time_machine.travel("2023-01-09 00:00:00 UTC", tick=False): + # The first interval of the new model isn't ready until 2023-01-09 08:00, while the + # unselected sushi models have intervals to backfill for 2023-01-08 + new_model = load_sql_based_model( + d.parse( + """ + MODEL (name memory.sushi.new_model, kind FULL, cron '0 8 * * *', start '2023-01-08'); + SELECT 1 AS id; + """ + ) + ) + new_model_name = context.upsert_model(new_model).fqn + + plan = context.plan_builder( + environment, skip_tests=True, select_models=[new_model_name] + ).build() + assert not plan.missing_intervals + context.apply(plan) + + schema = "sushi" if environment == "prod" else f"sushi__{environment}" + assert context.fetchdf(f"SELECT * FROM {schema}.new_model").empty + + @time_machine.travel("2023-01-08 00:00:00 UTC", tick=False) def test_parent_cron_after_child(init_and_plan_context: t.Callable): context, plan = init_and_plan_context("examples/sushi") diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..521b88979c 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -376,6 +376,7 @@ def test_build_plan_stages_select_models( expected_interval = (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) assert len(backfill_stage.snapshot_to_intervals) == 1 assert backfill_stage.snapshot_to_intervals[snapshot_a] == [expected_interval] + assert backfill_stage.selected_snapshot_ids == {snapshot_a.snapshot_id} # Verify EnvironmentRecordUpdateStage assert isinstance(stages[3], EnvironmentRecordUpdateStage) diff --git a/tests/core/test_scheduler.py b/tests/core/test_scheduler.py index cd32d2451d..10c69c1d64 100644 --- a/tests/core/test_scheduler.py +++ b/tests/core/test_scheduler.py @@ -11,6 +11,7 @@ from sqlmesh.core.model import load_sql_based_model from sqlmesh.core.model.definition import AuditResult, SqlModel from sqlmesh.core.model.kind import ( + FullKind, IncrementalByTimeRangeKind, IncrementalByUniqueKeyKind, TimeColumn, @@ -1022,6 +1023,48 @@ def record_execute_environment_statements(*args, **kwargs): assert env_statements_idx < execute_env_idx < snapshots_to_create_idx +def test_run_merged_intervals_considers_unpopulated_deployable_tables_for_creation( + mocker: MockerFixture, make_snapshot +): + def make_full_snapshot(name: str) -> Snapshot: + snapshot = make_snapshot( + SqlModel(name=name, query=parse_one("SELECT 1 AS id"), kind=FullKind()) + ) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + return snapshot + + ready = make_full_snapshot("ready") + waiting = make_full_snapshot("waiting") + populated = make_full_snapshot("populated") + populated.add_interval("2024-01-01", "2024-01-01") + unselected = make_full_snapshot("unselected") + shared_prod = make_full_snapshot("shared_prod") + shared_prod.categorize_as(SnapshotChangeCategory.BREAKING, forward_only=True) + shared_prod.unpaused_ts = to_timestamp("2024-01-01") + + snapshots = [ready, waiting, populated, unselected, shared_prod] + deployability_index = DeployabilityIndex.create(snapshots) + assert deployability_index.is_representative(shared_prod) + assert not deployability_index.is_deployable(shared_prod) + + snapshot_evaluator = mocker.MagicMock() + snapshot_evaluator.get_snapshots_to_create.return_value = [] + snapshot_evaluator.execution_tracker.get_execution_stats.return_value = None + scheduler = Scheduler(snapshots, snapshot_evaluator, mocker.MagicMock(), default_catalog=None) + mocker.patch.object(scheduler, "evaluate", return_value=[]) + + errors, _ = scheduler.run_merged_intervals( + merged_intervals={ready: [(to_timestamp("2024-01-01"), to_timestamp("2024-01-02"))]}, + deployability_index=deployability_index, + environment_naming_info=EnvironmentNamingInfo(name="dev"), + selected_snapshot_ids={s.snapshot_id for s in snapshots if s is not unselected}, + ) + + assert not errors + snapshot_evaluator.get_snapshots_to_create.assert_called_once() + assert set(snapshot_evaluator.get_snapshots_to_create.call_args.args[0]) == {ready, waiting} + + def test_dag_transitive_deps(mocker: MockerFixture, make_snapshot): # Create a simple dependency chain: A <- B <- C snapshot_a = make_snapshot(SqlModel(name="a", query=parse_one("SELECT 1 as id")))