From 6cdfcca8dbff4b26727f101eb2e325768b90f7dd Mon Sep 17 00:00:00 2001 From: Vamsi-klu Date: Wed, 25 Nov 2026 11:02:35 +0100 Subject: [PATCH] fix(plan): resolve physical parent tables in AuditOnlyRunStage BuiltInPlanEvaluator.visit_audit_only_run_stage() previously built its Scheduler using only stage.snapshots (the audited snapshots) and no deployability_index. As a result, parent references rendered as environment views rather than the plan's physical tables, causing missing-table errors or silent reads of stale parent rows after a failed prod plan, misrouting dev parents and non-representative @this_model targets to prod views, and preventing parent start-date inheritance and EMBEDDED parent expansion. - Add all_snapshots and deployability_index to AuditOnlyRunStage, schedule audit-only snapshots after BackfillStage (partitioning snapshots that depend on after-promote backfills or non-metadata schema migrations into a post-after-promote AuditOnlyRunStage before VirtualLayerUpdateStage), and skip unselected/unpromoted snapshots whose dev tables are not created. - Shallow-copy snapshots (and their interval lists) in visit_audit_only_run_stage() before passing them to Scheduler.audit() so in-place interval refresh/removal never mutates shared Snapshot instances held by other stages or CachingStateSync, and forward ignore_cron, selected_snapshots, circuit_breaker, and deployability_index. - Scope interval refresh, removal-interval calculation, and missing_intervals() computation to selected_snapshots during audit-only runs, and skip get_snapshots_to_create() / CreateNode DDL when audit_only=True. Fixes #6256 Signed-off-by: Vamsi-klu --- sqlmesh/core/plan/evaluator.py | 20 +- sqlmesh/core/plan/stages.py | 75 +- sqlmesh/core/scheduler.py | 56 +- sqlmesh/core/snapshot/definition.py | 6 + tests/core/integration/test_audits.py | 1130 +++++++++++++++++++++++++ tests/core/test_plan_evaluator.py | 150 +++- tests/core/test_plan_stages.py | 379 ++++++++- tests/core/test_scheduler.py | 225 ++++- 8 files changed, 2004 insertions(+), 37 deletions(-) diff --git a/sqlmesh/core/plan/evaluator.py b/sqlmesh/core/plan/evaluator.py index 71e5285d63..6ae5083b93 100644 --- a/sqlmesh/core/plan/evaluator.py +++ b/sqlmesh/core/plan/evaluator.py @@ -273,16 +273,34 @@ def visit_audit_only_run_stage( if not audit_snapshots: return + # Copy snapshots so Scheduler.audit()'s in-place interval refresh/removal + # does not mutate shared instances held by other stages or CachingStateSync. + all_snapshots = stage.all_snapshots | {s.name: s for s in audit_snapshots} + snapshots = [ + s.copy( + update={ + "intervals": s.intervals.copy(), + "dev_intervals": s.dev_intervals.copy(), + "pending_restatement_intervals": s.pending_restatement_intervals.copy(), + } + ) + for s in all_snapshots.values() + ] + # If there are any snapshots to be audited, we'll reuse the scheduler's internals to audit them - scheduler = self.create_scheduler(audit_snapshots, self.snapshot_evaluator) + scheduler = self.create_scheduler(snapshots, self.snapshot_evaluator) completion_status = scheduler.audit( plan.environment, plan.start, plan.end, execution_time=plan.execution_time, + ignore_cron=plan.ignore_cron, end_bounded=plan.end_bounded, start_override_per_model=plan.start_override_per_model, end_override_per_model=plan.end_override_per_model, + selected_snapshots={s.name for s in audit_snapshots}, + circuit_breaker=self._circuit_breaker, + deployability_index=stage.deployability_index, ) if completion_status.is_failure: diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..9447732a0d 100644 --- a/sqlmesh/core/plan/stages.py +++ b/sqlmesh/core/plan/stages.py @@ -92,9 +92,13 @@ class AuditOnlyRunStage: Args: snapshots: Snapshots to run audits for. + all_snapshots: All snapshots in the plan by name. + deployability_index: Deployability index for this stage. """ snapshots: t.List[Snapshot] + all_snapshots: t.Dict[str, Snapshot] + deployability_index: DeployabilityIndex @dataclass @@ -344,10 +348,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: ) ) - audit_only_snapshots = self._get_audit_only_snapshots(new_snapshots) - if audit_only_snapshots: - stages.append(AuditOnlyRunStage(snapshots=list(audit_only_snapshots.values()))) - if missing_intervals_before_promote: stages.append( BackfillStage( @@ -372,6 +372,35 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: ) ) + audit_only_snapshots = self._get_audit_only_snapshots( + plan, new_snapshots, deployability_index, needs_backfill + ) + audit_only_before_promote: t.List[Snapshot] = [] + audit_only_after_promote: t.List[Snapshot] = [] + if audit_only_snapshots: + after_promote_work_ids = {s.snapshot_id for s in missing_intervals_after_promote} | { + s.snapshot_id + for s in snapshots_with_schema_migration + if s.requires_schema_migration_in_prod and not s.is_metadata + } + for s_id in list(after_promote_work_ids): + after_promote_work_ids.update(dag.downstream(s_id)) + + audit_only_before_promote = [ + s for s_id, s in audit_only_snapshots.items() if s_id not in after_promote_work_ids + ] + audit_only_after_promote = [ + s for s_id, s in audit_only_snapshots.items() if s_id in after_promote_work_ids + ] + if audit_only_before_promote: + stages.append( + AuditOnlyRunStage( + snapshots=audit_only_before_promote, + all_snapshots=snapshots_by_name, + deployability_index=deployability_index, + ) + ) + # note: "restatement stage" (which is clearing intervals in state - not actually performing the restatements, that's the backfill stage) # needs to come *after* the backfill stage so that at no time do other plans / runs see empty prod intervals and compete with this plan to try to fill them. # in addition, when we update intervals in state, we only clear intervals from dev snapshots to force dev models to be backfilled based on the new prod data. @@ -416,6 +445,15 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: ) ) + if audit_only_after_promote: + stages.append( + AuditOnlyRunStage( + snapshots=audit_only_after_promote, + all_snapshots=snapshots_by_name, + deployability_index=deployability_index, + ) + ) + if not plan.is_dev and plan.ensure_finalized_snapshots and promoted_snapshots: # Unpause right before updating the virtual layer and finalizing the environment in case when # we need to use the finalized snapshots for subsequent plan applications. @@ -604,8 +642,18 @@ def _missing_intervals( ) def _get_audit_only_snapshots( - self, new_snapshots: t.Dict[SnapshotId, Snapshot] + self, + plan: EvaluatablePlan, + new_snapshots: t.Dict[SnapshotId, Snapshot], + deployability_index: DeployabilityIndex, + needs_backfill: bool, ) -> t.Dict[SnapshotId, Snapshot]: + promoted_snapshot_ids = ( + set(plan.environment.promoted_snapshot_ids) + if plan.environment.promoted_snapshot_ids is not None + else None + ) + metadata_snapshots = [] for snapshot in new_snapshots.values(): if ( @@ -616,6 +664,23 @@ def _get_audit_only_snapshots( ): continue + if not ( + plan.is_selected_for_backfill(snapshot.name) + or promoted_snapshot_ids is None + or snapshot.snapshot_id in promoted_snapshot_ids + ): + continue + + if ( + plan.is_dev + and needs_backfill + and not snapshot.is_symbolic + and not deployability_index.is_deployable(snapshot) + and not plan.is_selected_for_backfill(snapshot.name) + and not snapshot.dev_intervals + ): + continue + metadata_snapshots.append(snapshot) # Bulk load all the previous snapshots diff --git a/sqlmesh/core/scheduler.py b/sqlmesh/core/scheduler.py index 7345d92888..852702b322 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -173,7 +173,7 @@ def merged_missing_intervals( allow_partials, and other attributes that could cause the intervals to exceed the target end date. selected_snapshots: A set of snapshot names to run. If not provided, all snapshots will be run. """ - snapshots_to_intervals = merged_missing_intervals( + return merged_missing_intervals( snapshots=self.snapshot_per_version.values(), start=start, end=end, @@ -184,14 +184,8 @@ def merged_missing_intervals( end_override_per_model=end_override_per_model, ignore_cron=ignore_cron, end_bounded=end_bounded, + selected_snapshots=selected_snapshots, ) - # Filtering snapshots after computing missing intervals because we need all snapshots in order - # to correctly infer start dates. - if selected_snapshots is not None: - snapshots_to_intervals = { - s: i for s, i in snapshots_to_intervals.items() if s.name in selected_snapshots - } - return snapshots_to_intervals def evaluate( self, @@ -314,6 +308,8 @@ def audit( # by _run_or_audit as "missing intervals" to reuse the rest of it's logic remove_intervals = {} for snapshot in self.snapshots.values(): + if selected_snapshots is not None and snapshot.name not in selected_snapshots: + continue removal_intervals = snapshot.get_removal_interval( start, end, execution_time, is_preview=True ) @@ -505,19 +501,22 @@ 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 - snapshots_to_create_candidates = [ - s - for s in selected_snapshots - if not deployability_index.is_representative(s) or s in batched_intervals - ] - snapshots_to_create = { - s.snapshot_id - for s in self.snapshot_evaluator.get_snapshots_to_create( - snapshots_to_create_candidates, deployability_index - ) - } + if audit_only: + snapshots_to_create: t.Set[SnapshotId] = set() + else: + # We only need to create physical tables if the snapshot is not representative or if it + # needs backfill + snapshots_to_create_candidates = [ + s + for s in selected_snapshots + if not deployability_index.is_representative(s) or s in batched_intervals + ] + snapshots_to_create = { + s.snapshot_id + for s in self.snapshot_evaluator.get_snapshots_to_create( + snapshots_to_create_candidates, deployability_index + ) + } dag = self._dag( batched_intervals, @@ -858,7 +857,12 @@ def _run_or_audit( ) execution_time = execution_time or now_timestamp() - self.state_sync.refresh_snapshot_intervals(self.snapshots.values()) + snapshots_to_refresh = ( + [s for s in self.snapshots.values() if s.name in selected_snapshots] + if audit_only and selected_snapshots is not None + else self.snapshots.values() + ) + self.state_sync.refresh_snapshot_intervals(snapshots_to_refresh) for s_id, interval in (remove_intervals or {}).items(): self.snapshots[s_id].remove_interval(interval) @@ -1059,6 +1063,7 @@ def merged_missing_intervals( end_override_per_model: t.Optional[t.Dict[str, datetime]] = None, ignore_cron: bool = False, end_bounded: bool = False, + selected_snapshots: t.Optional[t.Collection[str]] = None, ) -> SnapshotToIntervals: """Find the largest contiguous date interval parameters based only on what is missing. @@ -1079,6 +1084,8 @@ 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. + selected_snapshots: Optional collection of snapshot names to compute intervals for while still using all snapshots + to infer start dates. """ restatements = restatements or {} validate_date_range(start, end) @@ -1094,6 +1101,7 @@ def merged_missing_intervals( end_override_per_model=end_override_per_model, ignore_cron=ignore_cron, end_bounded=end_bounded, + selected_snapshots=selected_snapshots, ) @@ -1109,6 +1117,7 @@ def compute_interval_params( end_override_per_model: t.Optional[t.Dict[str, datetime]] = None, ignore_cron: bool = False, end_bounded: bool = False, + selected_snapshots: t.Optional[t.Collection[str]] = None, ) -> SnapshotToIntervals: """Find the largest contiguous date interval parameters based only on what is missing. @@ -1129,6 +1138,8 @@ 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. + selected_snapshots: Optional collection of snapshot names to compute intervals for while still using all snapshots + to infer start dates. Returns: A dict containing all snapshots needing to be run with their associated interval params. @@ -1146,6 +1157,7 @@ def compute_interval_params( end_override_per_model=end_override_per_model, ignore_cron=ignore_cron, end_bounded=end_bounded, + selected_snapshots=selected_snapshots, ).items(): contiguous_batch = [] next_batch: Intervals = [] diff --git a/sqlmesh/core/snapshot/definition.py b/sqlmesh/core/snapshot/definition.py index 2d813a06b1..7a687bb7d4 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, + selected_snapshots: t.Optional[t.Collection[str]] = None, ) -> t.Dict[Snapshot, Intervals]: """Returns all missing intervals given a collection of snapshots.""" if not isinstance(snapshots, dict): @@ -2063,7 +2064,12 @@ def missing_intervals( end_override_per_model = end_override_per_model or {} deployability_index = deployability_index or DeployabilityIndex.all_deployable() + if selected_snapshots is not None and not isinstance(selected_snapshots, (set, frozenset)): + selected_snapshots = set(selected_snapshots) + for snapshot in snapshots.values(): + if selected_snapshots is not None and snapshot.name not in selected_snapshots: + continue if not snapshot.evaluatable: continue diff --git a/tests/core/integration/test_audits.py b/tests/core/integration/test_audits.py index 457974fdac..ebfb98a7a4 100644 --- a/tests/core/integration/test_audits.py +++ b/tests/core/integration/test_audits.py @@ -3,6 +3,7 @@ import typing as t from textwrap import dedent import pytest +from pytest_mock.plugin import MockerFixture from pathlib import Path import time_machine from sqlglot import exp @@ -13,6 +14,9 @@ ModelDefaultsConfig, ) from sqlmesh.core.context import Context +from sqlmesh.core.plan.evaluator import BuiltInPlanEvaluator +from sqlmesh.core.snapshot import SnapshotChangeCategory, SnapshotEvaluator +from sqlmesh.utils.date import to_timestamp from sqlmesh.utils.errors import ( PlanError, ) @@ -346,3 +350,1129 @@ def test_default_audits_with_custom_audit_definitions(tmp_path: Path): if audit_name == "positive_amount": assert "column" in audit_args assert audit_args["column"].name == "amount" + + +def test_audit_only_reads_new_parent_physical_table_after_failed_prod_plan( + tmp_path: Path, mocker: MockerFixture +): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "always_fail.sql", + dedent(""" + AUDIT (name always_fail); + SELECT 1 AS bad_row + """), + ) + create_temp_file( + tmp_path, + audits_dir / "check_parent_q.sql", + dedent(""" + AUDIT (name check_parent_q); + SELECT * + FROM db.q + WHERE val != @expected + """), + ) + create_temp_file( + tmp_path, + models_dir / "p.sql", + dedent(""" + MODEL ( + name db.p, + kind FULL + ); + SELECT 'p0' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '2023-01-01' + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.p + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod cleanly (backfills 2023-01-01) + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + + # Plan 1: add new parent db.q (before_promote) and forward-only change to db.c + # with a failing audit (after_promote) so EnvironmentRecordUpdateStage succeeds + # while VirtualLayerUpdateStage never publishes view db.q. + create_temp_file( + tmp_path, + models_dir / "q.sql", + dedent(""" + MODEL ( + name db.q, + kind FULL + ); + SELECT 'q1' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '2023-01-01', + audits (always_fail) + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.q + """), + ) + context.load() + + with pytest.raises(PlanError): + context.plan( + "prod", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + # Confirm the failure left prod state updated without publishing view db.q + assert not context.engine_adapter.table_exists("db.q") + prod_env = context.state_sync.get_environment("prod") + assert prod_env is not None + q_table_info = next(s for s in prod_env.snapshots if s.name == '"memory"."db"."q"') + assert context.engine_adapter.table_exists(q_table_info.table_name()) + + # Plan 2: metadata-only audit change on db.c reading db.q + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '2023-01-01', + audits (check_parent_q(expected := 'q1')) + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.q + """), + ) + context.load() + + plan2 = context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=False, + ) + c_new = [s for s in plan2.new_snapshots if s.name == '"memory"."db"."c"'] + assert len(c_new) == 1 + assert c_new[0].change_category == SnapshotChangeCategory.METADATA + assert not plan2.missing_intervals + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + recorded_results = [] + orig_audit = SnapshotEvaluator._audit + + def _capture_audit(self, *args, **kwargs): + res = orig_audit(self, *args, **kwargs) + recorded_results.append(res) + return res + + mocker.patch.object(SnapshotEvaluator, "_audit", _capture_audit) + + context.apply(plan2) + assert audit_stage_spy.call_count == 1 + assert len(recorded_results) == 1 + assert recorded_results[0].count == 0 + assert exp.to_table(q_table_info.table_name(), dialect="duckdb").sql( + dialect="duckdb", identify=True + ) in recorded_results[0].query.sql(dialect="duckdb") + + +@pytest.mark.parametrize("c_has_intervals", [False, True]) +def test_audit_only_reads_changed_parent_physical_table_not_stale_view_after_failed_prod_plan( + tmp_path: Path, mocker: MockerFixture, c_has_intervals: bool +): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "always_fail.sql", + dedent(""" + AUDIT (name always_fail); + SELECT 1 AS bad_row + """), + ) + create_temp_file( + tmp_path, + audits_dir / "check_parent_p.sql", + dedent(""" + AUDIT (name check_parent_p); + SELECT * + FROM db.p + WHERE val != @expected + """), + ) + c_start = "2023-01-01" if c_has_intervals else "2023-01-02" + create_temp_file( + tmp_path, + models_dir / "p.sql", + dedent(""" + MODEL ( + name db.p, + kind FULL, + start '2023-01-01' + ); + SELECT 'p0' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(f""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '{c_start}' + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.p + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod with p='p0'. + # If c_has_intervals=True, c gets [2023-01-01, 2023-01-02); if False, c starts on 2023-01-02 so c.intervals == []. + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + assert context.engine_adapter.fetchone("SELECT val FROM db.p") == ("p0",) + + # Plan 1: breaking change to db.p ('p0' -> 'p1', built in before_promote) + # + forward-only change on db.c with a failing audit (fails in after_promote on 2023-01-02). + # VirtualLayerUpdateStage never runs, leaving view db.p pointing to stale 'p0'. + create_temp_file( + tmp_path, + models_dir / "p.sql", + dedent(""" + MODEL ( + name db.p, + kind FULL, + start '2023-01-01' + ); + SELECT 'p1' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(f""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '{c_start}', + audits (always_fail) + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.p + """), + ) + context.load() + + with pytest.raises(PlanError): + context.plan( + "prod", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + # Confirm prod view db.p STILL points to stale 'p0', while p's physical table holds 'p1' + assert context.engine_adapter.fetchone("SELECT val FROM db.p") == ("p0",) + prod_env = context.state_sync.get_environment("prod") + assert prod_env is not None + p_table_info = next(s for s in prod_env.snapshots if s.name == '"memory"."db"."p"') + assert context.engine_adapter.fetchone(f"SELECT val FROM {p_table_info.table_name()}") == ( + "p1", + ) + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + plan2_execution_time = "2023-01-02" if c_has_intervals else "2023-01-03" + + # Plan 2a (negative): metadata-only audit expecting stale 'p0' MUST fail with PlanError + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(f""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '{c_start}', + audits (check_parent_p(expected := 'p0')) + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.p + """), + ) + context.load() + + plan2_stale = context.plan( + "prod", + execution_time=plan2_execution_time, + no_prompts=True, + auto_apply=False, + ) + if c_has_intervals: + assert not plan2_stale.missing_intervals + else: + assert plan2_stale.missing_intervals + + with pytest.raises(PlanError): + context.apply(plan2_stale) + + # Plan 2b (positive): metadata-only audit expecting physical 'p1' MUST succeed + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(f""" + MODEL ( + name db.c, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + forward_only true + ), + start '{c_start}', + audits (check_parent_p(expected := 'p1')) + ); + SELECT val, CAST(@start_ds AS DATE) AS ds + FROM db.p + """), + ) + context.load() + + plan2_fresh = context.plan( + "prod", + execution_time=plan2_execution_time, + no_prompts=True, + auto_apply=False, + ) + if c_has_intervals: + assert not plan2_fresh.missing_intervals + else: + assert plan2_fresh.missing_intervals + + audit_stage_spy.reset_mock() + context.apply(plan2_fresh) + assert audit_stage_spy.call_count == 1 + assert context.engine_adapter.fetchone("SELECT val FROM db.p") == ("p1",) + + +def test_audit_only_in_dev_reads_dev_parent_tables(tmp_path: Path, mocker: MockerFixture): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "check_parent_and_self.sql", + dedent(""" + AUDIT (name check_parent_and_self); + SELECT c.val AS c_val, p.val AS p_val + FROM @this_model AS c + CROSS JOIN @parent_table AS p + WHERE c.val != @expected OR p.val != @expected + """), + ) + create_temp_file( + tmp_path, + models_dir / "p.sql", + dedent(""" + MODEL ( + name db.p, + kind FULL, + start '2023-01-01' + ); + SELECT 'prod_val' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind FULL, + start '2023-01-01' + ); + SELECT val FROM db.p + """), + ) + create_temp_file( + tmp_path, + models_dir / "p_fo.sql", + dedent(""" + MODEL ( + name db.p_fo, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + start '2023-01-01' + ); + SELECT 'prod_fo' AS val, CAST(@start_ds AS DATE) AS ds + """), + ) + create_temp_file( + tmp_path, + models_dir / "c_fo.sql", + dedent(""" + MODEL ( + name db.c_fo, + kind FULL + ); + SELECT val FROM db.p_fo + """), + ) + create_temp_file( + tmp_path, + models_dir / "p_auto.sql", + dedent(""" + MODEL ( + name db.p_auto, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + auto_restatement_cron '@daily' + ), + start '2023-01-01' + ); + SELECT 'auto_val' AS val, CAST(@start_ds AS DATE) AS ds + """), + ) + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL + ); + SELECT val FROM db.p_auto + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + + # --- Subcase A: breaking parent change in dev --- + create_temp_file( + tmp_path, + models_dir / "p.sql", + dedent(""" + MODEL ( + name db.p, + kind FULL, + start '2023-01-01' + ); + SELECT 'dev_val' AS val + """), + ) + context.load() + context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + # Negative check: audit expecting prod view value 'prod_val' must FAIL in dev + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind FULL, + start '2023-01-01', + audits (check_parent_and_self(parent_table := db.p, expected := 'prod_val')) + ); + SELECT val FROM db.p + """), + ) + context.load() + with pytest.raises(PlanError): + context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + # Positive check: audit expecting dev table value 'dev_val' succeeds + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind FULL, + start '2023-01-01', + audits (check_parent_and_self(parent_table := db.p, expected := 'dev_val')) + ); + SELECT val FROM db.p + """), + ) + context.load() + context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + # --- Subcase B: forward-only non-deployable parent in dev --- + create_temp_file( + tmp_path, + models_dir / "p_fo.sql", + dedent(""" + MODEL ( + name db.p_fo, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + start '2023-01-01' + ); + SELECT 'dev_fo' AS val, CAST(@start_ds AS DATE) AS ds + """), + ) + context.load() + context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + forward_only=True, + no_prompts=True, + auto_apply=True, + ) + + # Now add a metadata-only audit to db.c_fo checking BOTH @this_model and db.p_fo + create_temp_file( + tmp_path, + models_dir / "c_fo.sql", + dedent(""" + MODEL ( + name db.c_fo, + kind FULL, + audits (check_parent_and_self(parent_table := db.p_fo, expected := 'dev_fo')) + ); + SELECT val FROM db.p_fo + """), + ) + context.load() + + recorded_results = [] + orig_audit = SnapshotEvaluator._audit + + def _capture_audit(self, *args, **kwargs): + res = orig_audit(self, *args, **kwargs) + recorded_results.append(res) + return res + + mocker.patch.object(SnapshotEvaluator, "_audit", _capture_audit) + + plan_fo = context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=False, + ) + assert not plan_fo.missing_intervals + context.apply(plan_fo) + + assert len(recorded_results) == 1 + fo_result = recorded_results[0] + assert fo_result.count == 0 + fo_sql = fo_result.query.sql(dialect="duckdb") + dev_env = context.state_sync.get_environment("dev") + assert dev_env is not None + p_fo_info = next(s for s in dev_env.snapshots if s.name == '"memory"."db"."p_fo"') + c_fo_info = next(s for s in dev_env.snapshots if s.name == '"memory"."db"."c_fo"') + # Both parent p_fo and @this_model c_fo must resolve to their __dev preview tables + assert ( + exp.to_table(p_fo_info.table_name(is_deployable=False), dialect="duckdb").sql( + dialect="duckdb", identify=True + ) + in fo_sql + ) + assert ( + exp.to_table(c_fo_info.table_name(is_deployable=False), dialect="duckdb").sql( + dialect="duckdb", identify=True + ) + in fo_sql + ) + + # --- Subcase C: non-representative C first-dev-build case --- + # db.p_auto has auto_restatement_cron -> db.c_auto is non-representative in a brand new dev env, + # so db.c_auto's __dev table does NOT exist until BackfillStage runs. + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL, + audits (check_parent_and_self(parent_table := db.p_auto, expected := 'auto_val')) + ); + SELECT val FROM db.p_auto + """), + ) + context.load() + + recorded_results.clear() + context.plan( + "dev_first_build", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=True, + ) + + dev_first_env = context.state_sync.get_environment("dev_first_build") + assert dev_first_env is not None + c_auto_info = next(s for s in dev_first_env.snapshots if s.name == '"memory"."db"."c_auto"') + c_auto_dev_table = exp.to_table( + c_auto_info.table_name(is_deployable=False), dialect="duckdb" + ).sql(dialect="duckdb", identify=True) + c_auto_results = [ + r for r in recorded_results if r.model and r.model.fqn == '"memory"."db"."c_auto"' + ] + assert len(c_auto_results) == 2 + assert all(r.count == 0 for r in c_auto_results) + assert all(c_auto_dev_table in r.query.sql(dialect="duckdb") for r in c_auto_results) + + +def test_audit_only_referencing_grandparent_sibling_changed_in_same_plan_and_embedded( + tmp_path: Path, mocker: MockerFixture +): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "check_cross_model.sql", + dedent(""" + AUDIT (name check_cross_model); + SELECT c.val AS c_val, a.val AS a_val, e.val AS e_val, s.val AS s_val + FROM @this_model AS c + CROSS JOIN db.a AS a + CROSS JOIN db.e AS e + CROSS JOIN db.s AS s + WHERE c.val != 'a_val' + OR a.val != 'a_val' + OR e.val != 'a_val' + OR s.val != 's_v2' + """), + ) + create_temp_file( + tmp_path, + models_dir / "a.sql", + dedent(""" + MODEL (name db.a, kind FULL, start '2023-01-01'); + SELECT 'a_val' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "e.sql", + dedent(""" + MODEL (name db.e, kind EMBEDDED); + SELECT val FROM db.a + """), + ) + create_temp_file( + tmp_path, + models_dir / "b.sql", + dedent(""" + MODEL (name db.b, kind FULL); + SELECT val FROM db.e + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL (name db.c, kind FULL); + SELECT val FROM db.b + """), + ) + create_temp_file( + tmp_path, + models_dir / "s.sql", + dedent(""" + MODEL (name db.s, kind FULL, start '2023-01-01'); + SELECT 's_v1' AS val + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + + # Plan 1: breaking change to sibling db.s ('s_v1' -> 's_v2') in the SAME plan + # + metadata-only audit on db.c querying grandparent db.a, embedded db.e, and sibling db.s + create_temp_file( + tmp_path, + models_dir / "s.sql", + dedent(""" + MODEL (name db.s, kind FULL, start '2023-01-01'); + SELECT 's_v2' AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind FULL, + audits (check_cross_model) + ); + SELECT val FROM db.b + """), + ) + context.load() + + recorded_results = [] + orig_audit = SnapshotEvaluator._audit + + def _capture_audit(self, *args, **kwargs): + res = orig_audit(self, *args, **kwargs) + recorded_results.append(res) + return res + + mocker.patch.object(SnapshotEvaluator, "_audit", _capture_audit) + + plan = context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=False, + ) + c_new = [s for s in plan.new_snapshots if s.name == '"memory"."db"."c"'] + assert len(c_new) == 1 + assert c_new[0].change_category == SnapshotChangeCategory.METADATA + + context.apply(plan) + + assert len(recorded_results) == 1 + res = recorded_results[0] + assert res.count == 0 + rendered_sql = res.query.sql(dialect="duckdb") + prod_env = context.state_sync.get_environment("prod") + assert prod_env is not None + a_info = next(s for s in prod_env.snapshots if s.name == '"memory"."db"."a"') + s_info = next(s for s in prod_env.snapshots if s.name == '"memory"."db"."s"') + assert ( + exp.to_table(a_info.table_name(), dialect="duckdb").sql(dialect="duckdb", identify=True) + in rendered_sql + ) + assert ( + exp.to_table(s_info.table_name(), dialect="duckdb").sql(dialect="duckdb", identify=True) + in rendered_sql + ) + assert '"db"."e"' not in rendered_sql + + +def test_audit_only_combined_with_incremental_restatement_preserves_history( + tmp_path: Path, mocker: MockerFixture +): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "check_inc_history.sql", + dedent(""" + AUDIT (name check_inc_history); + SELECT 1 AS bad_row + WHERE (SELECT COUNT(*) FROM db.inc) != 5 + OR (SELECT val FROM db.inc WHERE ds = DATE '2023-01-03') != 'v2' + """), + ) + create_temp_file( + tmp_path, + models_dir / "inc.sql", + dedent(""" + MODEL ( + name db.inc, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + start '2023-01-01' + ); + SELECT ds, val + FROM raw_inc + WHERE ds BETWEEN CAST(@start_ds AS DATE) AND CAST(@end_ds AS DATE) + """), + ) + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL (name db.c, kind FULL, start '2023-01-01'); + SELECT 1 AS id + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + context.engine_adapter.execute( + """ + CREATE TABLE raw_inc AS + SELECT DATE '2023-01-01' AS ds, 'v1' AS val UNION ALL + SELECT DATE '2023-01-02' AS ds, 'v1' AS val UNION ALL + SELECT DATE '2023-01-03' AS ds, 'v1' AS val UNION ALL + SELECT DATE '2023-01-04' AS ds, 'v1' AS val UNION ALL + SELECT DATE '2023-01-05' AS ds, 'v1' AS val + """ + ) + + # Plan 0: build 5 days of db.inc and db.c + context.plan( + "prod", + execution_time="2023-01-06", + no_prompts=True, + auto_apply=True, + ) + rows_before = context.engine_adapter.fetchall( + "SELECT CAST(ds AS VARCHAR), val FROM db.inc ORDER BY ds" + ) + assert rows_before == [ + ("2023-01-01", "v1"), + ("2023-01-02", "v1"), + ("2023-01-03", "v1"), + ("2023-01-04", "v1"), + ("2023-01-05", "v1"), + ] + + # Update only 2023-01-03 in raw source + context.engine_adapter.execute("UPDATE raw_inc SET val = 'v2' WHERE ds = DATE '2023-01-03'") + + # Plan 1: add metadata-only audit to db.c AND restate ONLY 1 day on db.inc + create_temp_file( + tmp_path, + models_dir / "c.sql", + dedent(""" + MODEL ( + name db.c, + kind FULL, + start '2023-01-01', + audits (check_inc_history) + ); + SELECT 1 AS id + """), + ) + context.load() + + recorded_results = [] + orig_audit = SnapshotEvaluator._audit + + def _capture_audit(self, *args, **kwargs): + res = orig_audit(self, *args, **kwargs) + recorded_results.append(res) + return res + + mocker.patch.object(SnapshotEvaluator, "_audit", _capture_audit) + + plan_builder = context.plan_builder( + "prod", + start="2023-01-03", + end="2023-01-03", + execution_time="2023-01-06", + restate_models=["db.inc"], + always_include_local_changes=True, + ) + plan = plan_builder.build() + c_new = [s for s in plan.new_snapshots if s.name == '"memory"."db"."c"'] + assert len(c_new) == 1 + assert c_new[0].change_category == SnapshotChangeCategory.METADATA + context.apply(plan) + + # Confirm the metadata-only audit actually ran and passed after day 3 was restated + assert len(recorded_results) == 1 + assert recorded_results[0].count == 0 + + # All 5 days must remain intact (no is_first_insert=True wipe) with only day 3 updated + rows_after = context.engine_adapter.fetchall( + "SELECT CAST(ds AS VARCHAR), val FROM db.inc ORDER BY ds" + ) + assert rows_after == [ + ("2023-01-01", "v1"), + ("2023-01-02", "v1"), + ("2023-01-03", "v2"), + ("2023-01-04", "v1"), + ("2023-01-05", "v1"), + ] + + inc_snap = context.get_snapshot("db.inc", raise_if_missing=True) + refreshed = context.state_sync.refresh_snapshot_intervals([inc_snap])[0] + assert refreshed.intervals == [(to_timestamp("2023-01-01"), to_timestamp("2023-01-06"))] + + +def test_audit_only_prod_after_promote_backfill_split(tmp_path: Path, mocker: MockerFixture): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "check_row_count_parity.sql", + dedent(""" + AUDIT (name check_row_count_parity); + SELECT 1 AS bad_row + WHERE (SELECT COUNT(*) FROM @this_model) != (SELECT COUNT(*) FROM db.p_auto) + """), + ) + create_temp_file( + tmp_path, + models_dir / "p_auto.sql", + dedent(""" + MODEL ( + name db.p_auto, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + auto_restatement_cron '@daily' + ), + start '2023-01-01' + ); + SELECT CAST(@start_ds AS DATE) AS ds, 1 AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL + ); + SELECT ds, val FROM db.p_auto + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod on 2023-01-02 (1 row in p_auto and c_auto) + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + assert context.engine_adapter.fetchone("SELECT COUNT(*) FROM db.p_auto") == (1,) + assert context.engine_adapter.fetchone("SELECT COUNT(*) FROM db.c_auto") == (1,) + + # Plan 1 on 2023-01-03: add metadata-only parity audit to db.c_auto. + # p_auto is backfilled in before_promote (2 rows) while c_auto is backfilled + # in after_promote, so AuditOnlyRunStage(c_auto) must run after BackfillStage(after_promote). + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL, + audits (check_row_count_parity) + ); + SELECT ds, val FROM db.p_auto + """), + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + recorded_results = [] + orig_audit = SnapshotEvaluator._audit + + def _capture_audit(self, *args, **kwargs): + res = orig_audit(self, *args, **kwargs) + recorded_results.append(res) + return res + + mocker.patch.object(SnapshotEvaluator, "_audit", _capture_audit) + + plan1 = context.plan( + "prod", + execution_time="2023-01-03", + no_prompts=True, + auto_apply=False, + ) + c_new = [s for s in plan1.new_snapshots if s.name == '"memory"."db"."c_auto"'] + assert len(c_new) == 1 + assert c_new[0].change_category == SnapshotChangeCategory.METADATA + + context.apply(plan1) + assert audit_stage_spy.call_count == 1 + assert len(recorded_results) == 2 + assert all(r.count == 0 for r in recorded_results) + assert context.engine_adapter.fetchone("SELECT COUNT(*) FROM db.p_auto") == (2,) + assert context.engine_adapter.fetchone("SELECT COUNT(*) FROM db.c_auto") == (2,) + + +def test_audit_only_dev_backfill_models_skips_unselected_non_representative(tmp_path: Path): + models_dir = tmp_path / "models" + audits_dir = tmp_path / "audits" + + create_temp_file( + tmp_path, + audits_dir / "check_c_auto.sql", + dedent(""" + AUDIT (name check_c_auto); + SELECT * FROM @this_model WHERE val != 1 + """), + ) + create_temp_file( + tmp_path, + models_dir / "x.sql", + dedent(""" + MODEL ( + name db.x, + kind FULL, + start '2023-01-01' + ); + SELECT 1 AS id + """), + ) + create_temp_file( + tmp_path, + models_dir / "p_auto.sql", + dedent(""" + MODEL ( + name db.p_auto, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + auto_restatement_cron '@daily' + ), + start '2023-01-01' + ); + SELECT CAST(@start_ds AS DATE) AS ds, 1 AS val + """), + ) + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL + ); + SELECT ds, val FROM db.p_auto + """), + ) + + config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb")) + context = Context(paths=tmp_path, config=config) + + # Plan 0: build prod + context.plan( + "prod", + execution_time="2023-01-02", + no_prompts=True, + auto_apply=True, + ) + + # Locally modify db.x (BREAKING) and add an audit to db.c_auto (METADATA) + create_temp_file( + tmp_path, + models_dir / "x.sql", + dedent(""" + MODEL ( + name db.x, + kind FULL, + start '2023-01-01' + ); + SELECT 2 AS id + """), + ) + create_temp_file( + tmp_path, + models_dir / "c_auto.sql", + dedent(""" + MODEL ( + name db.c_auto, + kind FULL, + audits (check_c_auto) + ); + SELECT ds, val FROM db.p_auto + """), + ) + context.load() + + # Apply a fresh dev plan backfilling ONLY db.x; db.c_auto is unselected and unpromoted, + # so its __dev table is never created and AuditOnlyRunStage must skip it instead of crashing. + context.plan( + "dev", + start="2023-01-01", + end="2023-01-01", + execution_time="2023-01-02", + backfill_models=["db.x"], + no_prompts=True, + auto_apply=True, + ) + assert context.engine_adapter.fetchone("SELECT id FROM db__dev.x") == (2,) diff --git a/tests/core/test_plan_evaluator.py b/tests/core/test_plan_evaluator.py index 575f5ae742..75e5213d4f 100644 --- a/tests/core/test_plan_evaluator.py +++ b/tests/core/test_plan_evaluator.py @@ -1,16 +1,22 @@ +import typing as t + import pytest from pytest_mock.plugin import MockerFixture from sqlglot import parse_one from sqlmesh.core.context import Context +from sqlmesh.core.environment import Environment from sqlmesh.core.model import FullKind, SqlModel, ViewKind from sqlmesh.core.plan import ( BuiltInPlanEvaluator, + EvaluatablePlan, Plan, PlanBuilder, stages as plan_stages, ) -from sqlmesh.core.snapshot import SnapshotChangeCategory +from sqlmesh.core.snapshot import DeployabilityIndex, Snapshot, SnapshotChangeCategory +from sqlmesh.utils import CompletionStatus +from sqlmesh.utils.date import to_timestamp @pytest.fixture @@ -82,3 +88,145 @@ def test_builtin_evaluator_push(sushi_context: Context, make_snapshot): ) assert sushi_context.engine_adapter.table_exists(new_model_snapshot.table_name()) assert sushi_context.engine_adapter.table_exists(new_view_model_snapshot.table_name()) + + +def test_visit_audit_only_run_stage_copies_snapshots_and_passes_deployability_index( + make_snapshot, mocker: MockerFixture +) -> None: + model_a = SqlModel( + name="a", + kind=FullKind(), + query=parse_one("SELECT 1 AS id"), + ) + model_b = SqlModel( + name="b", + kind=FullKind(), + query=parse_one("SELECT id FROM a"), + audits=[("not_null", {})], + ) + snapshot_a: Snapshot = make_snapshot(model_a) + snapshot_a.categorize_as(SnapshotChangeCategory.BREAKING) + snapshot_a.add_interval("2023-01-01", "2023-01-02") + snapshot_a.add_interval("2023-01-01", "2023-01-02", is_dev=True) + snapshot_a.pending_restatement_intervals = [ + (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + ] + + snapshot_b: Snapshot = make_snapshot(model_b, nodes={'"a"': model_a}) + snapshot_b.categorize_as(SnapshotChangeCategory.METADATA) + snapshot_b.add_interval("2023-01-01", "2023-01-02") + snapshot_b.add_interval("2023-01-01", "2023-01-02", is_dev=True) + snapshot_b.pending_restatement_intervals = [ + (to_timestamp("2023-01-01"), to_timestamp("2023-01-02")) + ] + + orig_a_intervals = list(snapshot_a.intervals) + orig_a_dev_intervals = list(snapshot_a.dev_intervals) + orig_a_pending = list(snapshot_a.pending_restatement_intervals) + orig_b_intervals = list(snapshot_b.intervals) + orig_b_dev_intervals = list(snapshot_b.dev_intervals) + orig_b_pending = list(snapshot_b.pending_restatement_intervals) + + deployability_index = DeployabilityIndex.create([snapshot_a, snapshot_b]) + stage = plan_stages.AuditOnlyRunStage( + snapshots=[snapshot_b], + all_snapshots={snapshot_a.name: snapshot_a, snapshot_b.name: snapshot_b}, + deployability_index=deployability_index, + ) + + environment = Environment( + name="dev", + snapshots=[snapshot_a.table_info, snapshot_b.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id=None, + ) + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=[snapshot_b], + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=True, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=True, + ensure_finalized_snapshots=False, + ignore_cron=True, + directly_modified_snapshots=[snapshot_b.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[snapshot_b.snapshot_id], + removed_snapshots=[], + requires_backfill=False, + models_to_backfill=None, + execution_time="2023-01-03", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + passed_snapshots: t.List[Snapshot] = [] + mock_scheduler = mocker.Mock() + + def _mutate_copied_snapshots(*args, **kwargs) -> CompletionStatus: + for s in passed_snapshots: + s.intervals.clear() + s.dev_intervals.clear() + s.pending_restatement_intervals.clear() + return CompletionStatus.SUCCESS + + mock_scheduler.audit.side_effect = _mutate_copied_snapshots + + def _create_scheduler(snapshots, snapshot_evaluator): + passed_snapshots.extend(snapshots) + return mock_scheduler + + evaluator = BuiltInPlanEvaluator( + state_sync=mocker.Mock(), + snapshot_evaluator=mocker.Mock(), + create_scheduler=_create_scheduler, + default_catalog=None, + console=mocker.Mock(), + ) + circuit_breaker = lambda: False + evaluator._circuit_breaker = circuit_breaker + + evaluator.visit_audit_only_run_stage(stage, plan) + + passed_by_name = {s.name: s for s in passed_snapshots} + assert set(passed_by_name) == {snapshot_a.name, snapshot_b.name} + + for name, orig in stage.all_snapshots.items(): + copied = passed_by_name[name] + assert copied is not orig + assert copied.intervals is not orig.intervals + assert copied.dev_intervals is not orig.dev_intervals + assert copied.pending_restatement_intervals is not orig.pending_restatement_intervals + + mock_scheduler.audit.assert_called_once_with( + plan.environment, + plan.start, + plan.end, + execution_time=plan.execution_time, + ignore_cron=True, + end_bounded=True, + start_override_per_model=plan.start_override_per_model, + end_override_per_model=plan.end_override_per_model, + selected_snapshots={snapshot_b.name}, + circuit_breaker=circuit_breaker, + deployability_index=deployability_index, + ) + + # Original snapshot intervals in stage.all_snapshots must remain completely unmutated + assert snapshot_a.intervals == orig_a_intervals + assert snapshot_a.dev_intervals == orig_a_dev_intervals + assert snapshot_a.pending_restatement_intervals == orig_a_pending + assert snapshot_b.intervals == orig_b_intervals + assert snapshot_b.dev_intervals == orig_b_dev_intervals + assert snapshot_b.pending_restatement_intervals == orig_b_pending diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..0baae098e7 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -24,7 +24,7 @@ FinalizeEnvironmentStage, UnpauseStage, ) -from sqlmesh.core.plan.explainer import ExplainableRestatementStage +from sqlmesh.core.plan.explainer import ExplainableRestatementStage, RichExplainerConsole from sqlmesh.core.snapshot.definition import ( SnapshotChangeCategory, DeployabilityIndex, @@ -1311,16 +1311,23 @@ def _get_snapshots(snapshot_ids: t.List[SnapshotId]) -> t.Dict[SnapshotId, Snaps [new_snapshot_a, new_snapshot_b] ) + # Verify BackfillStage + backfill_stage = stages[3] + assert isinstance(backfill_stage, BackfillStage) + assert len(backfill_stage.snapshot_to_intervals) == 0 + # Verify AuditOnlyRunStage - audit_only_stage = stages[3] + audit_only_stage = stages[4] assert isinstance(audit_only_stage, AuditOnlyRunStage) assert len(audit_only_stage.snapshots) == 1 assert audit_only_stage.snapshots[0].snapshot_id == new_snapshot_a.snapshot_id - - # Verify BackfillStage - backfill_stage = stages[4] - assert isinstance(backfill_stage, BackfillStage) - assert len(backfill_stage.snapshot_to_intervals) == 0 + assert audit_only_stage.all_snapshots == { + '"a"': new_snapshot_a, + '"b"': new_snapshot_b, + } + assert audit_only_stage.deployability_index == DeployabilityIndex.create( + [new_snapshot_a, new_snapshot_b] + ) # Verify EnvironmentRecordUpdateStage assert isinstance(stages[5], EnvironmentRecordUpdateStage) @@ -1336,6 +1343,364 @@ def _get_snapshots(snapshot_ids: t.List[SnapshotId]) -> t.Dict[SnapshotId, Snaps assert isinstance(stages[7], FinalizeEnvironmentStage) +def test_build_plan_stages_audit_only_prod( + snapshot_a: Snapshot, snapshot_b: Snapshot, make_snapshot, mocker: MockerFixture +) -> None: + snapshot_a.add_interval("2023-01-01", "2023-01-02") + + new_snapshot_b = make_snapshot( + snapshot_b.model.copy(update={"audits": [("not_null", {})]}), + nodes={'"a"': snapshot_a.model}, + ) + new_snapshot_b.previous_versions = snapshot_b.all_versions + new_snapshot_b.categorize_as(SnapshotChangeCategory.METADATA) + new_snapshot_b.add_interval("2023-01-01", "2023-01-02") + + stored = { + snapshot_a.snapshot_id: snapshot_a, + snapshot_b.snapshot_id: snapshot_b, + } + + def _get_snapshots(snapshot_ids: t.Iterable[SnapshotIdLike]) -> t.Dict[SnapshotId, Snapshot]: + requested = {s.snapshot_id for s in snapshot_ids} + return {sid: s for sid, s in stored.items() if sid in requested} + + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.side_effect = _get_snapshots + state_reader.get_environment.return_value = None + + environment = Environment( + name="prod", + snapshots=[snapshot_a.table_info, new_snapshot_b.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id=None, + promoted_snapshot_ids=[snapshot_a.snapshot_id, new_snapshot_b.snapshot_id], + ) + + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=[new_snapshot_b], + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=False, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=False, + ensure_finalized_snapshots=False, + ignore_cron=False, + directly_modified_snapshots=[new_snapshot_b.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[new_snapshot_b.snapshot_id], + removed_snapshots=[], + requires_backfill=False, + models_to_backfill=None, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + stages = build_plan_stages(plan, state_reader, None) + + backfill_idx = next(i for i, s in enumerate(stages) if isinstance(s, BackfillStage)) + audit_only_idx = next(i for i, s in enumerate(stages) if isinstance(s, AuditOnlyRunStage)) + env_update_idx = next( + i for i, s in enumerate(stages) if isinstance(s, EnvironmentRecordUpdateStage) + ) + assert backfill_idx < audit_only_idx < env_update_idx + + audit_only_stage = stages[audit_only_idx] + assert isinstance(audit_only_stage, AuditOnlyRunStage) + assert audit_only_stage.snapshots == [new_snapshot_b] + assert audit_only_stage.all_snapshots == { + '"a"': snapshot_a, + '"b"': new_snapshot_b, + } + assert audit_only_stage.deployability_index == DeployabilityIndex.all_deployable() + + +def test_build_plan_stages_audit_only_prod_before_and_after_promote_split( + make_snapshot, mocker: MockerFixture +) -> None: + p_auto = make_snapshot( + SqlModel( + name="p_auto", + query=parse_one("SELECT 1 AS val, ds"), + start="2023-01-01", + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, + time_column="ds", + auto_restatement_cron="@daily", + ), + ) + ) + p_auto.categorize_as(SnapshotChangeCategory.BREAKING) + p_auto.unpaused_ts = to_timestamp("2023-01-01") + p_auto.add_interval("2023-01-01", "2023-01-01") + + old_c_auto = make_snapshot( + SqlModel( + name="c_auto", + query=parse_one("SELECT val, ds FROM p_auto"), + kind=dict(name=ModelKindName.FULL), + ), + nodes={'"p_auto"': p_auto.model}, + ) + old_c_auto.categorize_as(SnapshotChangeCategory.BREAKING) + old_c_auto.unpaused_ts = to_timestamp("2023-01-01") + old_c_auto.add_interval("2023-01-01", "2023-01-01") + + new_c_auto = make_snapshot( + old_c_auto.model.copy(update={"audits": [("not_null", {})]}), + nodes={'"p_auto"': p_auto.model}, + ) + new_c_auto.previous_versions = old_c_auto.all_versions + new_c_auto.categorize_as(SnapshotChangeCategory.METADATA) + new_c_auto.add_interval("2023-01-01", "2023-01-01") + + old_other = make_snapshot( + SqlModel( + name="other", + query=parse_one("SELECT 1 AS val"), + start="2023-01-01", + kind=dict(name=ModelKindName.FULL), + ) + ) + old_other.categorize_as(SnapshotChangeCategory.BREAKING) + old_other.unpaused_ts = to_timestamp("2023-01-01") + old_other.add_interval("2023-01-01", "2023-01-02") + + new_other = make_snapshot( + old_other.model.copy(update={"audits": [("not_null", {})]}), + ) + new_other.previous_versions = old_other.all_versions + new_other.categorize_as(SnapshotChangeCategory.METADATA) + new_other.add_interval("2023-01-01", "2023-01-02") + + stored = { + p_auto.snapshot_id: p_auto, + old_c_auto.snapshot_id: old_c_auto, + old_other.snapshot_id: old_other, + } + + def _get_snapshots(snapshot_ids: t.Iterable[SnapshotIdLike]) -> t.Dict[SnapshotId, Snapshot]: + requested = {s.snapshot_id for s in snapshot_ids} + return {sid: s for sid, s in stored.items() if sid in requested} + + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.side_effect = _get_snapshots + state_reader.get_environment.return_value = Environment( + name="prod", + snapshots=[p_auto.table_info, old_c_auto.table_info, old_other.table_info], + start_at="2023-01-01", + end_at="2023-01-01", + plan_id="prev_plan", + previous_plan_id=None, + ) + + environment = Environment( + name="prod", + snapshots=[p_auto.table_info, new_c_auto.table_info, new_other.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id="prev_plan", + ) + + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=[new_c_auto, new_other], + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=False, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=False, + ensure_finalized_snapshots=False, + ignore_cron=False, + directly_modified_snapshots=[new_c_auto.snapshot_id, new_other.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[new_c_auto.snapshot_id, new_other.snapshot_id], + removed_snapshots=[], + requires_backfill=True, + models_to_backfill=None, + execution_time="2023-01-03", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + stages = build_plan_stages(plan, state_reader, None) + + backfill_indices = [i for i, s in enumerate(stages) if isinstance(s, BackfillStage)] + audit_indices = [i for i, s in enumerate(stages) if isinstance(s, AuditOnlyRunStage)] + env_update_idx = next( + i for i, s in enumerate(stages) if isinstance(s, EnvironmentRecordUpdateStage) + ) + virtual_idx = next(i for i, s in enumerate(stages) if isinstance(s, VirtualLayerUpdateStage)) + + assert len(backfill_indices) == 2 + assert len(audit_indices) == 2 + + before_bf_idx, after_bf_idx = backfill_indices + before_audit_idx, after_audit_idx = audit_indices + assert ( + before_bf_idx + < before_audit_idx + < env_update_idx + < after_bf_idx + < after_audit_idx + < virtual_idx + ) + + expected_all = { + '"p_auto"': p_auto, + '"c_auto"': new_c_auto, + '"other"': new_other, + } + before_audit = stages[before_audit_idx] + after_audit = stages[after_audit_idx] + assert isinstance(before_audit, AuditOnlyRunStage) + assert isinstance(after_audit, AuditOnlyRunStage) + assert before_audit.snapshots == [new_other] + assert after_audit.snapshots == [new_c_auto] + assert before_audit.all_snapshots == expected_all + assert after_audit.all_snapshots == expected_all + assert before_audit.deployability_index == DeployabilityIndex.all_deployable() + assert after_audit.deployability_index == DeployabilityIndex.all_deployable() + + # Verify PlanExplainer handles multiple AuditOnlyRunStage instances cleanly + mock_console = mocker.Mock() + explainer_console = RichExplainerConsole( + environment_naming_info=environment.naming_info, + dialect="duckdb", + default_catalog=None, + console=mock_console, + ) + explainer_console.explain(stages) + mock_console.print.assert_called_once() + + +@pytest.mark.parametrize("promoted_ids_none", [False, True]) +def test_build_plan_stages_audit_only_dev_skips_unselected_unpromoted( + make_snapshot, mocker: MockerFixture, promoted_ids_none: bool +) -> None: + x_snap = make_snapshot( + SqlModel( + name="x", + query=parse_one("SELECT 2 AS id"), + start="2023-01-01", + kind=dict(name=ModelKindName.FULL), + ) + ) + x_snap.categorize_as(SnapshotChangeCategory.BREAKING) + + p_auto = make_snapshot( + SqlModel( + name="p_auto", + query=parse_one("SELECT 1 AS val, ds"), + start="2023-01-01", + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, + time_column="ds", + auto_restatement_cron="@daily", + ), + ) + ) + p_auto.categorize_as(SnapshotChangeCategory.BREAKING) + p_auto.unpaused_ts = to_timestamp("2023-01-01") + p_auto.add_interval("2023-01-01", "2023-01-01") + + old_c_auto = make_snapshot( + SqlModel( + name="c_auto", + query=parse_one("SELECT val, ds FROM p_auto"), + kind=dict(name=ModelKindName.FULL), + ), + nodes={'"p_auto"': p_auto.model}, + ) + old_c_auto.categorize_as(SnapshotChangeCategory.BREAKING) + old_c_auto.unpaused_ts = to_timestamp("2023-01-01") + old_c_auto.add_interval("2023-01-01", "2023-01-01") + + new_c_auto = make_snapshot( + old_c_auto.model.copy(update={"audits": [("not_null", {})]}), + nodes={'"p_auto"': p_auto.model}, + ) + new_c_auto.previous_versions = old_c_auto.all_versions + new_c_auto.categorize_as(SnapshotChangeCategory.METADATA) + new_c_auto.add_interval("2023-01-01", "2023-01-01") + + stored = { + p_auto.snapshot_id: p_auto, + old_c_auto.snapshot_id: old_c_auto, + } + + def _get_snapshots(snapshot_ids: t.Iterable[SnapshotIdLike]) -> t.Dict[SnapshotId, Snapshot]: + requested = {s.snapshot_id for s in snapshot_ids} + return {sid: s for sid, s in stored.items() if sid in requested} + + state_reader = mocker.Mock(spec=StateReader) + state_reader.get_snapshots.side_effect = _get_snapshots + state_reader.get_environment.return_value = None + + environment = Environment( + name="dev", + snapshots=[x_snap.table_info, p_auto.table_info, new_c_auto.table_info], + start_at="2023-01-01", + end_at="2023-01-01", + plan_id="test_plan", + previous_plan_id=None, + promoted_snapshot_ids=None if promoted_ids_none else [x_snap.snapshot_id], + ) + + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-01", + new_snapshots=[x_snap, new_c_auto], + environment=environment, + no_gaps=False, + skip_backfill=False, + empty_backfill=False, + restatements={}, + restate_all_snapshots=False, + is_dev=True, + allow_destructive_models=set(), + allow_additive_models=set(), + forward_only=False, + end_bounded=False, + ensure_finalized_snapshots=False, + ignore_cron=False, + directly_modified_snapshots=[x_snap.snapshot_id, new_c_auto.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[new_c_auto.snapshot_id], + removed_snapshots=[], + requires_backfill=True, + models_to_backfill={x_snap.name}, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + stages = build_plan_stages(plan, state_reader, None) + assert not any(isinstance(s, AuditOnlyRunStage) for s in stages) + + def test_build_plan_stages_forward_only_ensure_finalized_snapshots( snapshot_a: Snapshot, snapshot_b: Snapshot, make_snapshot, mocker: MockerFixture ) -> None: diff --git a/tests/core/test_scheduler.py b/tests/core/test_scheduler.py index cd32d2451d..3698ccbfc1 100644 --- a/tests/core/test_scheduler.py +++ b/tests/core/test_scheduler.py @@ -2,15 +2,17 @@ import pytest from pytest_mock.plugin import MockerFixture -from sqlglot import parse_one, parse +from sqlglot import exp, parse_one, parse from sqlglot.helper import first +from sqlmesh.core.audit import ModelAudit from sqlmesh.core.context import Context, ExecutionContext from sqlmesh.core.environment import EnvironmentNamingInfo from sqlmesh.core.macros import RuntimeStage 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, @@ -34,6 +36,7 @@ DeployabilityIndex, snapshots_to_dag, ) +from sqlmesh.utils import CompletionStatus from sqlmesh.utils.date import to_datetime, to_timestamp, DatetimeRanges, TimeLike from sqlmesh.utils.errors import CircuitBreakerError, NodeAuditsErrors @@ -1213,3 +1216,223 @@ def test_dag_upstream_dependency_caching_with_complex_diamond(mocker: MockerFixt expected_g_node: {expected_a_node}, expected_h_node: {expected_a_node}, } + + +def test_scheduler_audit_selected_snapshots_resolves_all_without_auditing_parents( + mocker: MockerFixture, make_snapshot +) -> None: + custom_audit = ModelAudit( + name="check_all_tables", + query=( + "SELECT * FROM @this_model AS c " + "JOIN db.a AS a ON c.id = a.id " + "JOIN db.b AS b ON c.id = b.id " + "JOIN db.d AS d ON c.id = d.id " + "WHERE 1 = 0" + ), + ) + + model_a = SqlModel( + name="db.a", + kind=FullKind(), + cron="@daily", + start="2023-01-01", + query=parse_one("SELECT 1 AS id"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + model_b = SqlModel( + name="db.b", + kind=FullKind(), + cron="@daily", + query=parse_one("SELECT id FROM db.a"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + model_c = SqlModel( + name="db.c", + kind=IncrementalByTimeRangeKind(time_column=TimeColumn(column="ds")), + cron="@daily", + query=parse_one("SELECT id, ds FROM db.b"), + audits=[("check_all_tables", {})], + audit_definitions={custom_audit.name: custom_audit}, + ) + model_d = SqlModel( + name="db.d", + kind=IncrementalByTimeRangeKind(time_column=TimeColumn(column="ds")), + cron="@daily", + start="2023-01-01", + query=parse_one("SELECT id, ds FROM db.d"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + + nodes = { + model_a.fqn: model_a, + model_b.fqn: model_b, + model_c.fqn: model_c, + model_d.fqn: model_d, + } + snapshot_a: Snapshot = make_snapshot(model_a, nodes=nodes) + snapshot_b: Snapshot = make_snapshot(model_b, nodes=nodes) + snapshot_c: Snapshot = make_snapshot(model_c, nodes=nodes) + snapshot_d: Snapshot = make_snapshot(model_d, nodes=nodes) + assert not snapshot_c.depends_on_past + assert snapshot_d.depends_on_past + for snap in (snapshot_a, snapshot_b, snapshot_c, snapshot_d): + snap.categorize_as(SnapshotChangeCategory.BREAKING) + snap.add_interval("2023-01-01", "2023-01-03") + + audited_calls: t.List[t.Tuple[Snapshot, str, t.Optional[TimeLike], t.Optional[TimeLike]]] = [] + + mock_snapshot_evaluator = mocker.MagicMock() + + def _mock_audit( + snapshot: Snapshot, + *, + snapshots: t.Dict[str, Snapshot], + start: t.Optional[TimeLike] = None, + end: t.Optional[TimeLike] = None, + execution_time: t.Optional[TimeLike] = None, + deployability_index: t.Optional[DeployabilityIndex] = None, + **kwargs: t.Any, + ) -> t.List[AuditResult]: + audit, audit_args = snapshot.node.audits_with_args[0] + rendered = snapshot.model.render_audit_query( + audit, + start=start, + end=end, + execution_time=execution_time, + snapshots=snapshots, + deployability_index=deployability_index, + **audit_args, + ) + audited_calls.append((snapshot, rendered.sql(), start, end)) + return [ + AuditResult( + audit=audit, + audit_args=audit_args, + model=snapshot.model, + count=0, + query=rendered, + ) + ] + + mock_snapshot_evaluator.audit.side_effect = _mock_audit + + mock_state_sync = mocker.MagicMock() + scheduler = Scheduler( + snapshots=[snapshot_a, snapshot_b, snapshot_c, snapshot_d], + snapshot_evaluator=mock_snapshot_evaluator, + state_sync=mock_state_sync, + default_catalog=None, + ) + + deployability_index = DeployabilityIndex.all_deployable() + status = scheduler.audit( + EnvironmentNamingInfo(name="prod"), + start="2023-01-01", + end="2023-01-03", + execution_time="2023-01-04", + selected_snapshots={snapshot_c.name}, + deployability_index=deployability_index, + ) + + assert status == CompletionStatus.SUCCESS + assert len(audited_calls) == 1 + audited_snapshot, rendered_sql, audit_start, audit_end = audited_calls[0] + assert audited_snapshot.name == snapshot_c.name + # C inherits A's start date even though A and B are not selected + assert audit_start == to_timestamp("2023-01-01") + assert audit_end == to_timestamp("2023-01-04") + # Rendered audit query resolves C, A, B, and sibling D to physical tables + assert exp.to_table(snapshot_a.table_name()).sql(identify=True) in rendered_sql + assert exp.to_table(snapshot_b.table_name()).sql(identify=True) in rendered_sql + assert exp.to_table(snapshot_c.table_name()).sql(identify=True) in rendered_sql + assert exp.to_table(snapshot_d.table_name()).sql(identify=True) in rendered_sql + + # Only selected snapshot C had its intervals refreshed + mock_state_sync.refresh_snapshot_intervals.assert_called_once() + refreshed = list(mock_state_sync.refresh_snapshot_intervals.call_args[0][0]) + assert [s.name for s in refreshed] == [snapshot_c.name] + + # audit_only=True must NEVER invoke get_snapshots_to_create or emit CreateNode DDL + mock_snapshot_evaluator.get_snapshots_to_create.assert_not_called() + mock_snapshot_evaluator.create_snapshot.assert_not_called() + + # Unselected depends_on_past=True sibling D must NOT raise ValueError when execution_time < start + status_future = scheduler.audit( + EnvironmentNamingInfo(name="prod"), + start="2023-01-05", + end="2023-01-06", + execution_time="2023-01-03", + selected_snapshots={snapshot_c.name}, + deployability_index=deployability_index, + ) + assert not status_future.is_failure + assert all(call[0].name == snapshot_c.name for call in audited_calls) + mock_snapshot_evaluator.get_snapshots_to_create.assert_not_called() + + +def test_scheduler_audit_selected_snapshots_preserves_transitive_order( + mocker: MockerFixture, make_snapshot +) -> None: + model_a = SqlModel( + name="db.a", + kind=FullKind(), + cron="@daily", + start="2023-01-01", + query=parse_one("SELECT 1 AS id"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + model_b = SqlModel( + name="db.b", + kind=FullKind(), + cron="@daily", + query=parse_one("SELECT id FROM db.a"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + model_c = SqlModel( + name="db.c", + kind=FullKind(), + cron="@daily", + query=parse_one("SELECT id FROM db.b"), + audits=[("not_null", {"columns": parse_one("(id)")})], + ) + nodes = {model_a.fqn: model_a, model_b.fqn: model_b, model_c.fqn: model_c} + snapshot_a: Snapshot = make_snapshot(model_a, nodes=nodes) + snapshot_b: Snapshot = make_snapshot(model_b, nodes=nodes) + snapshot_c: Snapshot = make_snapshot(model_c, nodes=nodes) + for snap in (snapshot_a, snapshot_b, snapshot_c): + snap.categorize_as(SnapshotChangeCategory.BREAKING) + snap.add_interval("2023-01-01", "2023-01-02") + + audit_order: t.List[str] = [] + mock_snapshot_evaluator = mocker.MagicMock() + + def _record_audit(snapshot: Snapshot, **kwargs: t.Any) -> t.List[AuditResult]: + audit_order.append(snapshot.name) + return [] + + mock_snapshot_evaluator.audit.side_effect = _record_audit + mock_state_sync = mocker.MagicMock() + + scheduler = Scheduler( + snapshots=[snapshot_a, snapshot_b, snapshot_c], + snapshot_evaluator=mock_snapshot_evaluator, + state_sync=mock_state_sync, + default_catalog=None, + max_workers=2, + ) + + status = scheduler.audit( + EnvironmentNamingInfo(name="prod"), + start="2023-01-01", + end="2023-01-02", + execution_time="2023-01-03", + selected_snapshots={snapshot_a.name, snapshot_c.name}, + deployability_index=DeployabilityIndex.all_deployable(), + ) + + assert status == CompletionStatus.SUCCESS + assert audit_order == [snapshot_a.name, snapshot_c.name] + mock_snapshot_evaluator.get_snapshots_to_create.assert_not_called() + refreshed = list(mock_state_sync.refresh_snapshot_intervals.call_args[0][0]) + assert {s.name for s in refreshed} == {snapshot_a.name, snapshot_c.name}