From 2d3e3a5b3b2d5f49c7d3741b2321af2007e25c4e Mon Sep 17 00:00:00 2001 From: Sruthi Date: Wed, 25 Nov 2026 09:06:23 +0000 Subject: [PATCH] fix(plan): pass plan snapshots and deployability index to audit-only stage Signed-off-by: Sruthi --- sqlmesh/core/plan/evaluator.py | 34 +- sqlmesh/core/plan/stages.py | 22 +- sqlmesh/core/scheduler.py | 48 +- tests/core/integration/test_audits.py | 616 ++++++++++++++++++++++++++ tests/core/test_plan_evaluator.py | 160 +++++++ tests/core/test_plan_stages.py | 133 ++++++ tests/core/test_scheduler.py | 163 +++++++ 7 files changed, 1156 insertions(+), 20 deletions(-) diff --git a/sqlmesh/core/plan/evaluator.py b/sqlmesh/core/plan/evaluator.py index 71e5285d63..eaec419017 100644 --- a/sqlmesh/core/plan/evaluator.py +++ b/sqlmesh/core/plan/evaluator.py @@ -273,16 +273,48 @@ def visit_audit_only_run_stage( if not audit_snapshots: return + all_snapshots_by_id = { + **{s.snapshot_id: s for s in stage.all_snapshots.values()}, + **{s.snapshot_id: s for s in audit_snapshots}, + } + relevant_snapshots: t.Dict[SnapshotId, Snapshot] = {} + queue = [s.snapshot_id for s in audit_snapshots] + while queue: + s_id = queue.pop() + if s_id in relevant_snapshots or s_id not in all_snapshots_by_id: + continue + snapshot = all_snapshots_by_id[s_id] + relevant_snapshots[s_id] = snapshot + queue.extend(snapshot.parents) + + # Copy only the audited snapshots and their upstream ancestors so scheduler.audit's state + # refresh cannot mutate shared Snapshot objects held by subsequent stages or + # CachingStateSync, and avoids refreshing unrelated project 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 relevant_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, end_bounded=plan.end_bounded, + ignore_cron=plan.ignore_cron, 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}, + deployability_index=stage.deployability_index, + circuit_breaker=self._circuit_breaker, ) if completion_status.is_failure: diff --git a/sqlmesh/core/plan/stages.py b/sqlmesh/core/plan/stages.py index 3d034cf6a1..b60ed86295 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,9 +348,15 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]: ) ) - audit_only_snapshots = self._get_audit_only_snapshots(new_snapshots) + audit_only_snapshots = self._get_audit_only_snapshots(new_snapshots, deployability_index) if audit_only_snapshots: - stages.append(AuditOnlyRunStage(snapshots=list(audit_only_snapshots.values()))) + stages.append( + AuditOnlyRunStage( + snapshots=list(audit_only_snapshots.values()), + all_snapshots=snapshots_by_name, + deployability_index=deployability_index, + ) + ) if missing_intervals_before_promote: stages.append( @@ -604,7 +614,9 @@ def _missing_intervals( ) def _get_audit_only_snapshots( - self, new_snapshots: t.Dict[SnapshotId, Snapshot] + self, + new_snapshots: t.Dict[SnapshotId, Snapshot], + deployability_index: DeployabilityIndex, ) -> t.Dict[SnapshotId, Snapshot]: metadata_snapshots = [] for snapshot in new_snapshots.values(): @@ -613,6 +625,10 @@ def _get_audit_only_snapshots( or not snapshot.is_model or not snapshot.evaluatable or not snapshot.previous_version + or ( + not deployability_index.is_representative(snapshot) + and not snapshot.dev_intervals + ) ): continue diff --git a/sqlmesh/core/scheduler.py b/sqlmesh/core/scheduler.py index 7345d92888..cc442c4d6e 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -314,6 +314,10 @@ 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 not snapshot.evaluatable or ( + 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 +509,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, @@ -560,11 +567,19 @@ def execute_node(node: SchedulingUnit) -> None: assert deployability_index # mypy if audit_only: + audit_snapshots = { + snapshot.name: snapshot, + **{ + self.snapshots[p_id].name: self.snapshots[p_id] + for p_id in snapshot.parents + if p_id in self.snapshots + }, + } audit_results = self._audit_snapshot( snapshot=snapshot, environment_naming_info=environment_naming_info, deployability_index=deployability_index, - snapshots=self.snapshots_by_name, + snapshots=audit_snapshots, start=start, end=end, execution_time=execution_time, @@ -859,8 +874,9 @@ def _run_or_audit( execution_time = execution_time or now_timestamp() self.state_sync.refresh_snapshot_intervals(self.snapshots.values()) - for s_id, interval in (remove_intervals or {}).items(): - self.snapshots[s_id].remove_interval(interval) + if not audit_only: + for s_id, interval in (remove_intervals or {}).items(): + self.snapshots[s_id].remove_interval(interval) all_auto_restatement_triggers: t.Dict[SnapshotId, t.List[SnapshotId]] = {} if auto_restatement_enabled: diff --git a/tests/core/integration/test_audits.py b/tests/core/integration/test_audits.py index 457974fdac..3853650dd0 100644 --- a/tests/core/integration/test_audits.py +++ b/tests/core/integration/test_audits.py @@ -4,6 +4,7 @@ from textwrap import dedent import pytest from pathlib import Path +from pytest_mock.plugin import MockerFixture import time_machine from sqlglot import exp from IPython.utils.capture import capture_output @@ -13,6 +14,8 @@ ModelDefaultsConfig, ) from sqlmesh.core.context import Context +from sqlmesh.core.plan.evaluator import BuiltInPlanEvaluator +from sqlmesh.core.snapshot.evaluator import SnapshotEvaluator from sqlmesh.utils.errors import ( PlanError, ) @@ -346,3 +349,616 @@ 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" + + +_MATCHES_PARENT_AUDIT = """ + AUDIT ( + name matches_parent + ); + + SELECT a.id + FROM @this_model AS a + LEFT JOIN @parent_model AS b + ON a.id = b.id + WHERE b.id IS NULL +""" + +_EXPECT_VAL_AUDIT = """ + AUDIT ( + name expect_val + ); + + SELECT * + FROM @this_model + WHERE val != @expected +""" + + +def _write_files(root: Path, files: t.Dict[str, str]) -> None: + for rel_path, content in files.items(): + create_temp_file(root, Path(rel_path), dedent(content)) + + +def test_audit_only_resolves_new_parent_after_failed_prod_plan( + tmp_path: Path, mocker: MockerFixture +): + """Issue #6256: Pure metadata audit-only plan resolves a NEW parent whose prod view was not promoted.""" + _write_files( + tmp_path, + { + "audits/matches_parent.sql": _MATCHES_PARENT_AUDIT, + "models/base.sql": """ + MODEL (name test.base, kind FULL); + SELECT 1 AS id + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + with time_machine.travel("2024-01-02 00:00:00 UTC"): + context.plan("prod", no_prompts=True, auto_apply=True) + + # Plan 1: backfills new test.p -> test.c in before_promote, runs + # EnvironmentRecordUpdateStage, then fails in after_promote on new forward-only model + # test.fo before VirtualLayerUpdateStage creates views. + _write_files( + tmp_path, + { + "models/p.sql": """ + MODEL (name test.p, kind FULL); + SELECT id FROM test.base + """, + "models/c.sql": """ + MODEL (name test.c, kind FULL); + SELECT id FROM test.p + """, + "models/fo.sql": """ + MODEL ( + name test.fo, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds, forward_only true), + start '2024-01-01', + cron '@daily', + audits (not_null(columns := [id])) + ); + SELECT NULL AS id, @start_ds::DATE AS ds + """, + }, + ) + context.load() + + with pytest.raises(PlanError): + context.plan("prod", no_prompts=True, auto_apply=True) + + assert not context.engine_adapter.table_exists("test.p") + + # Plan 2: remove failing test.fo and add a metadata-only audit on test.c referencing its + # parent test.p -> pure metadata audit plan with zero backfill. + (tmp_path / "models" / "fo.sql").unlink() + _write_files( + tmp_path, + { + "models/c.sql": """ + MODEL ( + name test.c, + kind FULL, + audits (matches_parent(parent_model := test.p)) + ); + SELECT id FROM test.p + """, + }, + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + backfill_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_backfill_stage") + context.plan("prod", no_prompts=True, auto_apply=True) + + assert audit_stage_spy.call_count == 1 + assert backfill_stage_spy.call_count == 1 + assert not backfill_stage_spy.call_args.args[1].snapshot_to_intervals + assert context.engine_adapter.fetchall("SELECT id FROM test.p") == [(1,)] + + +def test_audit_only_resolves_changed_parent_after_failed_prod_plan( + tmp_path: Path, mocker: MockerFixture +): + """Issue #6256: Pure metadata audit-only plan resolves a CHANGED parent instead of its stale prod view.""" + _write_files( + tmp_path, + { + "audits/matches_parent.sql": _MATCHES_PARENT_AUDIT, + "models/p.sql": """ + MODEL (name test.p, kind FULL); + SELECT 1 AS id + """, + "models/c.sql": """ + MODEL (name test.c, kind FULL); + SELECT id FROM test.p + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + with time_machine.travel("2024-01-02 00:00:00 UTC"): + context.plan("prod", no_prompts=True, auto_apply=True) + + # Plan 1: breaking change to test.p (id=2) backfills test.p and test.c in before_promote, + # promotes environment record, then fails in after_promote on new forward-only model + # test.fo before VirtualLayerUpdateStage updates prod views. + _write_files( + tmp_path, + { + "models/p.sql": """ + MODEL (name test.p, kind FULL); + SELECT 2 AS id + """, + "models/fo.sql": """ + MODEL ( + name test.fo, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds, forward_only true), + start '2024-01-01', + cron '@daily', + audits (not_null(columns := [id])) + ); + SELECT NULL AS id, @start_ds::DATE AS ds + """, + }, + ) + context.load() + + with pytest.raises(PlanError): + context.plan("prod", no_prompts=True, auto_apply=True) + + # Prod view test.p is still stale (id=1) while physical tables for test.p and test.c have id=2. + assert context.engine_adapter.fetchall("SELECT id FROM test.p") == [(1,)] + + # Plan 2: remove failing test.fo and add a metadata-only audit on test.c referencing test.p + # (no backfill). Reading stale view test.p (id=1) would fail against test.c (id=2); + # resolving physical table passes. + (tmp_path / "models" / "fo.sql").unlink() + _write_files( + tmp_path, + { + "models/c.sql": """ + MODEL ( + name test.c, + kind FULL, + audits (matches_parent(parent_model := test.p)) + ); + SELECT id FROM test.p + """, + }, + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + backfill_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_backfill_stage") + context.plan("prod", no_prompts=True, auto_apply=True) + + assert audit_stage_spy.call_count == 1 + assert backfill_stage_spy.call_count == 1 + assert not backfill_stage_spy.call_args.args[1].snapshot_to_intervals + assert context.engine_adapter.fetchall("SELECT id FROM test.p") == [(2,)] + + +@pytest.mark.parametrize("select_models", [None, ["test.target"]]) +def test_audit_only_dev_breaking_parent(tmp_path: Path, select_models: t.Optional[t.List[str]]): + """Audit-only change in dev referencing a parent with a breaking change in dev (with & without --select-model).""" + _write_files( + tmp_path, + { + "audits/matches_parent.sql": _MATCHES_PARENT_AUDIT, + "models/parent.sql": """ + MODEL (name test.parent, kind FULL); + SELECT 1 AS id + """, + "models/target.sql": """ + MODEL (name test.target, kind FULL); + SELECT id FROM test.parent + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + context.plan("prod", no_prompts=True, auto_apply=True) + + # Breaking change to test.parent in dev -> dev tables for test.parent and test.target have id=2, + # while prod view test.parent still has id=1. + _write_files( + tmp_path, + { + "models/parent.sql": """ + MODEL (name test.parent, kind FULL); + SELECT 2 AS id + """, + }, + ) + context.load() + context.plan("dev", no_prompts=True, auto_apply=True) + + # Metadata-only audit on test.target referencing test.parent must resolve dev's physical table (id=2). + _write_files( + tmp_path, + { + "models/target.sql": """ + MODEL ( + name test.target, + kind FULL, + audits (matches_parent(parent_model := test.parent)) + ); + SELECT id FROM test.parent + """, + }, + ) + context.load() + context.plan("dev", select_models=select_models, no_prompts=True, auto_apply=True) + + +def test_audit_only_dev_paused_forward_only_grandparent_preview( + tmp_path: Path, mocker: MockerFixture +): + """Audit-only change in dev when grandparent is a paused forward-only model must audit dev preview tables.""" + _write_files( + tmp_path, + { + "audits/expect_val.sql": _EXPECT_VAL_AUDIT, + "models/grandparent.sql": """ + MODEL (name test.grandparent, kind FULL); + SELECT 1 AS val + """, + "models/parent.sql": """ + MODEL (name test.parent, kind FULL); + SELECT val FROM test.grandparent + """, + "models/child.sql": """ + MODEL (name test.child, kind FULL); + SELECT val FROM test.parent + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + context.plan("prod", no_prompts=True, auto_apply=True) + + # Forward-only change to grandparent in dev populates non-deployable dev preview tables (val=2) + # while prod tables retain val=1. + _write_files( + tmp_path, + { + "models/grandparent.sql": """ + MODEL (name test.grandparent, kind FULL); + SELECT 2 AS val + """, + }, + ) + context.load() + context.plan("dev", forward_only=True, no_prompts=True, auto_apply=True) + assert context.engine_adapter.fetchall("SELECT val FROM test__dev.child") == [(2,)] + assert context.engine_adapter.fetchall("SELECT val FROM test.child") == [(1,)] + + # Metadata-only audit on test.child in dev must audit its populated dev preview table (val=2). + _write_files( + tmp_path, + { + "models/child.sql": """ + MODEL ( + name test.child, + kind FULL, + audits (expect_val(expected := 2, blocking := true)) + ); + SELECT val FROM test.parent + """, + }, + ) + context.load() + + audit_spy = mocker.spy(SnapshotEvaluator, "_audit") + context.plan("dev", forward_only=True, no_prompts=True, auto_apply=True) + + assert audit_spy.call_count == 1 + audit_kwargs = audit_spy.call_args.kwargs + child_snapshot = audit_kwargs["snapshot"] + deployability_index = audit_kwargs["deployability_index"] + assert not deployability_index.is_deployable(child_snapshot) + audit_result = audit_spy.spy_return + assert audit_result.count == 0 + expected_dev_table = exp.to_table( + child_snapshot.table_name(is_deployable=False), dialect="duckdb" + ).sql(dialect="duckdb", identify=True) + assert expected_dev_table in audit_result.query.sql(dialect="duckdb") + + +def test_audit_only_embedded_parent(tmp_path: Path): + """Audit-only change referencing an embedded parent (with transitive embedded parent).""" + _write_files( + tmp_path, + { + "audits/matches_parent.sql": _MATCHES_PARENT_AUDIT, + "models/emb_parent.sql": """ + MODEL (name test.emb_parent, kind EMBEDDED); + SELECT 1 AS id + """, + "models/emb_mid.sql": """ + MODEL (name test.emb_mid, kind EMBEDDED); + SELECT id FROM test.emb_parent + """, + "models/full_child.sql": """ + MODEL (name test.full_child, kind FULL); + SELECT id FROM test.emb_mid + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + context.plan("prod", no_prompts=True, auto_apply=True) + + _write_files( + tmp_path, + { + "models/full_child.sql": """ + MODEL ( + name test.full_child, + kind FULL, + audits (matches_parent(parent_model := test.emb_mid)) + ); + SELECT id FROM test.emb_mid + """, + }, + ) + context.load() + context.plan("prod", no_prompts=True, auto_apply=True) + + +def test_audit_only_external_model(tmp_path: Path): + """Audit-only change on an EXTERNAL model runs its updated audit.""" + _write_files( + tmp_path, + { + "models/ext_source.sql": """ + MODEL ( + name test.ext_source, + kind EXTERNAL, + columns (id INT), + audits (not_null(columns := [id])) + ); + SELECT 1; + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + context.engine_adapter.create_schema("test") + context.engine_adapter.execute("CREATE TABLE test.ext_source AS SELECT 1 AS id") + context.plan("prod", no_prompts=True, auto_apply=True) + + context.engine_adapter.execute("INSERT INTO test.ext_source VALUES (1)") + _write_files( + tmp_path, + { + "models/ext_source.sql": """ + MODEL ( + name test.ext_source, + kind EXTERNAL, + columns (id INT), + audits ( + not_null(columns := [id]), + unique_values(columns := [id]) + ) + ); + SELECT 1; + """, + }, + ) + context.load() + + with pytest.raises(PlanError): + context.plan("prod", no_prompts=True, auto_apply=True) + + +def test_audit_only_preserves_incremental_by_unique_key_historical_rows( + tmp_path: Path, mocker: MockerFixture +): + """Running AuditOnlyRunStage + BackfillStage in the same plan must not wipe historical rows.""" + _write_files( + tmp_path, + { + "models/inc_unique.sql": """ + MODEL ( + name test.inc_unique, + kind INCREMENTAL_BY_UNIQUE_KEY (unique_key id), + start '2024-01-01', + cron '@daily' + ); + SELECT @start_ds::TEXT AS id, @start_ds::DATE AS ds + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + with time_machine.travel("2024-01-02 00:00:00 UTC"): + context.plan("prod", no_prompts=True, auto_apply=True) + + assert sorted(context.engine_adapter.fetchall("SELECT id FROM test.inc_unique")) == [ + ("2024-01-01",) + ] + + _write_files( + tmp_path, + { + "models/inc_unique.sql": """ + MODEL ( + name test.inc_unique, + kind INCREMENTAL_BY_UNIQUE_KEY (unique_key id), + start '2024-01-01', + cron '@daily', + audits (not_null(columns := [id])) + ); + SELECT @start_ds::TEXT AS id, @start_ds::DATE AS ds + """, + }, + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + backfill_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_backfill_stage") + with time_machine.travel("2024-01-03 00:00:00 UTC"): + context.plan("prod", run=True, no_prompts=True, auto_apply=True) + + assert audit_stage_spy.call_count == 1 + assert backfill_stage_spy.call_count == 1 + assert backfill_stage_spy.call_args.args[1].snapshot_to_intervals + assert sorted(context.engine_adapter.fetchall("SELECT id FROM test.inc_unique")) == [ + ("2024-01-01",), + ("2024-01-02",), + ] + + +def test_audit_only_does_not_resolve_uncreated_sibling_table(tmp_path: Path, mocker: MockerFixture): + """AuditOnlyRunStage before BackfillStage must not resolve a non-parent breaking sibling to its uncreated table.""" + _write_files( + tmp_path, + { + "audits/matches_parent.sql": _MATCHES_PARENT_AUDIT, + "models/other.sql": """ + MODEL (name test.other, kind FULL); + SELECT 1 AS id + """, + "models/target.sql": """ + MODEL (name test.target, kind FULL); + SELECT 1 AS id + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + context.plan("prod", no_prompts=True, auto_apply=True) + + # Single plan: breaking change to unrelated sibling test.other (needs backfill, physical table + # not yet created during AuditOnlyRunStage) + metadata audit on test.target referencing test.other. + _write_files( + tmp_path, + { + "models/other.sql": """ + MODEL (name test.other, kind FULL); + SELECT 2 AS id + """, + "models/target.sql": """ + MODEL ( + name test.target, + kind FULL, + audits (matches_parent(parent_model := test.other)) + ); + SELECT 1 AS id + """, + }, + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + backfill_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_backfill_stage") + context.plan("prod", no_prompts=True, auto_apply=True) + + assert audit_stage_spy.call_count == 1 + assert backfill_stage_spy.call_count == 1 + assert backfill_stage_spy.call_args.args[1].snapshot_to_intervals + assert context.engine_adapter.fetchall("SELECT id FROM test.other") == [(2,)] + + +def test_audit_only_dev_non_representative_without_dev_intervals( + tmp_path: Path, mocker: MockerFixture +): + """Non-representative dev METADATA models without dev_intervals skip AuditOnlyRunStage and audit in BackfillStage.""" + _write_files( + tmp_path, + { + "audits/expect_val.sql": _EXPECT_VAL_AUDIT, + "models/p.sql": """ + MODEL ( + name test.p, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds, + auto_restatement_cron '@daily' + ), + start '2024-01-01' + ); + SELECT 1 AS val, '2024-01-01'::DATE AS ds + """, + "models/c_full.sql": """ + MODEL (name test.c_full, kind FULL, start '2024-01-01'); + SELECT val, ds FROM test.p + """, + "models/c_inc.sql": """ + MODEL ( + name test.c_inc, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + start '2024-01-01' + ); + SELECT val, ds FROM test.p WHERE ds BETWEEN @start_ds AND @end_ds + """, + }, + ) + + context = Context(paths=tmp_path, config=Config()) + with time_machine.travel("2024-01-02 00:00:00 UTC"): + context.plan("prod", no_prompts=True, auto_apply=True) + + # Dev plan 1: add metadata-only audits to c_full and c_inc (both non-representative because + # test.p has auto_restatement_cron, and neither has dev_intervals yet). + _write_files( + tmp_path, + { + "models/c_full.sql": """ + MODEL ( + name test.c_full, + kind FULL, + start '2024-01-01', + audits (expect_val(expected := 1, blocking := true)) + ); + SELECT val, ds FROM test.p + """, + "models/c_inc.sql": """ + MODEL ( + name test.c_inc, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + start '2024-01-01', + audits (expect_val(expected := 1, blocking := true)) + ); + SELECT val, ds FROM test.p WHERE ds BETWEEN @start_ds AND @end_ds + """, + }, + ) + context.load() + + audit_stage_spy = mocker.spy(BuiltInPlanEvaluator, "visit_audit_only_run_stage") + audit_spy = mocker.spy(SnapshotEvaluator, "_audit") + context.plan("dev", no_prompts=True, auto_apply=True) + + assert audit_stage_spy.call_count == 0 + assert audit_spy.call_count == 2 + assert context.engine_adapter.fetchall("SELECT val FROM test__dev.c_full") == [(1,)] + assert context.engine_adapter.fetchall("SELECT val FROM test__dev.c_inc") == [(1,)] + + # Dev plan 2: c_full now has populated dev_intervals, so a subsequent audit-only change + # runs in AuditOnlyRunStage against its existing __dev table. + _write_files( + tmp_path, + { + "models/c_full.sql": """ + MODEL ( + name test.c_full, + kind FULL, + start '2024-01-01', + audits ( + expect_val(expected := 1, blocking := true), + not_null(columns := [val]) + ) + ); + SELECT val, ds FROM test.p + """, + }, + ) + context.load() + + audit_stage_spy.reset_mock() + context.plan("dev", no_prompts=True, auto_apply=True) + assert audit_stage_spy.call_count == 1 diff --git a/tests/core/test_plan_evaluator.py b/tests/core/test_plan_evaluator.py index 575f5ae742..53aa94af83 100644 --- a/tests/core/test_plan_evaluator.py +++ b/tests/core/test_plan_evaluator.py @@ -82,3 +82,163 @@ 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(make_snapshot, mocker: MockerFixture): + from datetime import datetime + from sqlmesh.core.environment import Environment + from sqlmesh.core.plan.definition import EvaluatablePlan + from sqlmesh.core.snapshot import DeployabilityIndex + from sqlmesh.utils import CompletionStatus + from sqlmesh.utils.errors import PlanError + + gp_model = SqlModel(name="db.gp", kind=FullKind(), query=parse_one("SELECT 1 AS id")) + parent_model = SqlModel( + name="db.parent", kind=FullKind(), query=parse_one("SELECT id FROM db.gp") + ) + child_model = SqlModel( + name="db.child", + kind=FullKind(), + query=parse_one("SELECT id FROM db.parent"), + audits=[("not_null", {})], + ) + sibling_model = SqlModel(name="db.sibling", kind=FullKind(), query=parse_one("SELECT 1 AS id")) + + gp_snapshot = make_snapshot(gp_model) + gp_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + gp_snapshot.add_interval("2024-01-01", "2024-01-02") + + parent_snapshot = make_snapshot(parent_model, nodes={gp_model.fqn: gp_model}) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + parent_snapshot.add_interval("2024-01-01", "2024-01-02") + + child_snapshot = make_snapshot( + child_model, nodes={gp_model.fqn: gp_model, parent_model.fqn: parent_model} + ) + child_snapshot.categorize_as(SnapshotChangeCategory.METADATA) + child_snapshot.add_interval("2024-01-01", "2024-01-02") + child_snapshot.add_interval("2024-01-01", "2024-01-02", is_dev=True) + + sibling_snapshot = make_snapshot(sibling_model) + sibling_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + sibling_snapshot.add_interval("2024-01-01", "2024-01-02") + + original_child_intervals = child_snapshot.intervals.copy() + original_child_dev_intervals = child_snapshot.dev_intervals.copy() + original_parent_intervals = parent_snapshot.intervals.copy() + + all_snapshots = { + gp_snapshot.name: gp_snapshot, + parent_snapshot.name: parent_snapshot, + child_snapshot.name: child_snapshot, + sibling_snapshot.name: sibling_snapshot, + } + deployability_index = DeployabilityIndex.create(list(all_snapshots.values())) + stage = plan_stages.AuditOnlyRunStage( + snapshots=[child_snapshot], + all_snapshots=all_snapshots, + deployability_index=deployability_index, + ) + + env = Environment( + name="dev", + snapshots=[s.table_info for s in all_snapshots.values()], + start_at="2024-01-01", + end_at="2024-01-02", + plan_id="test_plan", + previous_plan_id=None, + ) + start_override = {child_snapshot.name: datetime(2024, 1, 1)} + end_override = {child_snapshot.name: datetime(2024, 1, 2)} + plan = EvaluatablePlan( + start="2024-01-01", + end="2024-01-02", + new_snapshots=[child_snapshot], + environment=env, + 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=[child_snapshot.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[], + removed_snapshots=[], + requires_backfill=False, + models_to_backfill=None, + execution_time="2024-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + start_override_per_model=start_override, + end_override_per_model=end_override, + ) + + captured_snapshots = [] + mock_scheduler = mocker.Mock() + + def _audit(*args, **kwargs): + # Mutate intervals on snapshots passed to Scheduler to verify stage.all_snapshots is isolated + for s in captured_snapshots: + s.intervals.clear() + s.dev_intervals.clear() + s.pending_restatement_intervals.append((1, 2)) + return CompletionStatus.SUCCESS + + mock_scheduler.audit.side_effect = _audit + + def _create_scheduler(snaps, _snapshot_evaluator): + captured_snapshots.extend(snaps) + return mock_scheduler + + circuit_breaker = lambda: False + evaluator = BuiltInPlanEvaluator( + state_sync=mocker.Mock(), + snapshot_evaluator=mocker.Mock(), + create_scheduler=_create_scheduler, + default_catalog=None, + ) + evaluator._circuit_breaker = circuit_breaker + + evaluator.visit_audit_only_run_stage(stage, plan) + + # Only audited snapshot + upstream ancestors are passed (unrelated sibling excluded) + assert {s.name for s in captured_snapshots} == { + gp_snapshot.name, + parent_snapshot.name, + child_snapshot.name, + } + assert sibling_snapshot.name not in {s.name for s in captured_snapshots} + + # Original snapshots in stage.all_snapshots must not be mutated + assert child_snapshot.intervals == original_child_intervals + assert child_snapshot.dev_intervals == original_child_dev_intervals + assert child_snapshot.pending_restatement_intervals == [] + assert parent_snapshot.intervals == original_parent_intervals + + mock_scheduler.audit.assert_called_once_with( + plan.environment, + plan.start, + plan.end, + execution_time=plan.execution_time, + end_bounded=True, + ignore_cron=True, + start_override_per_model=start_override, + end_override_per_model=end_override, + selected_snapshots={child_snapshot.name}, + deployability_index=deployability_index, + circuit_breaker=circuit_breaker, + ) + + # Failure status raises PlanError + mock_scheduler.audit.side_effect = None + mock_scheduler.audit.return_value = CompletionStatus.FAILURE + with pytest.raises(PlanError): + evaluator.visit_audit_only_run_stage(stage, plan) diff --git a/tests/core/test_plan_stages.py b/tests/core/test_plan_stages.py index 5bfa3e2fc9..dab383bdd3 100644 --- a/tests/core/test_plan_stages.py +++ b/tests/core/test_plan_stages.py @@ -1316,6 +1316,13 @@ def _get_snapshots(snapshot_ids: t.List[SnapshotId]) -> t.Dict[SnapshotId, Snaps 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 + assert audit_only_stage.all_snapshots == { + new_snapshot_a.name: new_snapshot_a, + new_snapshot_b.name: new_snapshot_b, + } + assert audit_only_stage.deployability_index == DeployabilityIndex.create( + [new_snapshot_a, new_snapshot_b] + ) # Verify BackfillStage backfill_stage = stages[4] @@ -1335,6 +1342,132 @@ def _get_snapshots(snapshot_ids: t.List[SnapshotId]) -> t.Dict[SnapshotId, Snaps # Verify FinalizeEnvironmentStage assert isinstance(stages[7], FinalizeEnvironmentStage) + # Verify prod plan passes all_deployable deployability_index and all_snapshots + prod_env = Environment( + name="prod", + snapshots=[new_snapshot_a.table_info, new_snapshot_b.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan_prod", + previous_plan_id=None, + promoted_snapshot_ids=[new_snapshot_a.snapshot_id, new_snapshot_b.snapshot_id], + ) + prod_plan = plan.copy(update={"environment": prod_env, "is_dev": False}) + prod_stages = build_plan_stages(prod_plan, state_reader, None) + prod_audit_stages = [s for s in prod_stages if isinstance(s, AuditOnlyRunStage)] + assert len(prod_audit_stages) == 1 + assert prod_audit_stages[0].snapshots == [new_snapshot_a] + assert prod_audit_stages[0].all_snapshots == { + new_snapshot_a.name: new_snapshot_a, + new_snapshot_b.name: new_snapshot_b, + } + assert prod_audit_stages[0].deployability_index == DeployabilityIndex.all_deployable() + + +def test_build_plan_stages_audit_only_skips_non_representative_without_dev_intervals( + make_snapshot, mocker: MockerFixture +) -> None: + parent_model = SqlModel( + name="p", + query=parse_one("select 1 as id, '2023-01-01'::date as ds"), + kind=dict( + name=ModelKindName.INCREMENTAL_BY_TIME_RANGE, + time_column="ds", + auto_restatement_cron="@daily", + ), + start="2023-01-01", + ) + parent_snapshot = make_snapshot(parent_model) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + parent_snapshot.unpaused_ts = 1 + parent_snapshot.add_interval("2023-01-01", "2023-01-02") + + old_child_model = SqlModel( + name="c", + query=parse_one("select id from p"), + kind=dict(name=ModelKindName.FULL), + start="2023-01-01", + ) + old_child_snapshot = make_snapshot(old_child_model, nodes={'"p"': parent_model}) + old_child_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + old_child_snapshot.unpaused_ts = 1 + old_child_snapshot.add_interval("2023-01-01", "2023-01-02") + + new_child_snapshot = make_snapshot( + old_child_model.copy(update={"audits": [("not_null", {})]}), + nodes={'"p"': parent_model}, + ) + new_child_snapshot.previous_versions = old_child_snapshot.all_versions + new_child_snapshot.categorize_as(SnapshotChangeCategory.METADATA) + new_child_snapshot.add_interval("2023-01-01", "2023-01-02") + + def _get_snapshots(snapshot_ids: t.Iterable[SnapshotIdLike]) -> t.Dict[SnapshotId, Snapshot]: + result: t.Dict[SnapshotId, Snapshot] = {} + for s in snapshot_ids: + sid = s.snapshot_id + if sid == parent_snapshot.snapshot_id: + result[sid] = parent_snapshot + elif sid == old_child_snapshot.snapshot_id: + result[sid] = old_child_snapshot + return result + + 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=[parent_snapshot.table_info, new_child_snapshot.table_info], + start_at="2023-01-01", + end_at="2023-01-02", + plan_id="test_plan", + previous_plan_id=None, + promoted_snapshot_ids=[parent_snapshot.snapshot_id, new_child_snapshot.snapshot_id], + ) + plan = EvaluatablePlan( + start="2023-01-01", + end="2023-01-02", + new_snapshots=[new_child_snapshot], + 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=[new_child_snapshot.snapshot_id], + indirectly_modified_snapshots={}, + metadata_updated_snapshots=[], + removed_snapshots=[], + requires_backfill=True, + models_to_backfill=None, + execution_time="2023-01-02", + disabled_restatement_models=set(), + environment_statements=None, + user_provided_flags=None, + ) + + # Without dev_intervals, non-representative dev child must skip AuditOnlyRunStage and backfill instead. + stages = build_plan_stages(plan, state_reader, None) + assert not any(isinstance(s, AuditOnlyRunStage) for s in stages) + backfill_stages = [s for s in stages if isinstance(s, BackfillStage)] + assert len(backfill_stages) == 1 + assert new_child_snapshot in backfill_stages[0].snapshot_to_intervals + + # Once dev_intervals exist, AuditOnlyRunStage must include the non-representative dev child. + new_child_snapshot.add_interval("2023-01-01", "2023-01-02", is_dev=True) + stages_with_dev = build_plan_stages(plan, state_reader, None) + audit_stages = [s for s in stages_with_dev if isinstance(s, AuditOnlyRunStage)] + assert len(audit_stages) == 1 + assert audit_stages[0].snapshots == [new_child_snapshot] + assert not audit_stages[0].deployability_index.is_representative(new_child_snapshot) + def test_build_plan_stages_forward_only_ensure_finalized_snapshots( snapshot_a: Snapshot, snapshot_b: Snapshot, make_snapshot, mocker: MockerFixture diff --git a/tests/core/test_scheduler.py b/tests/core/test_scheduler.py index cd32d2451d..72b147bf96 100644 --- a/tests/core/test_scheduler.py +++ b/tests/core/test_scheduler.py @@ -1213,3 +1213,166 @@ 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_and_no_interval_mutation( + mocker: MockerFixture, make_snapshot: t.Callable +) -> None: + parent_model = load_sql_based_model( + parse( # type: ignore + """ + MODEL ( + name db.parent, + kind FULL, + start '2023-01-01' + ); + SELECT 1 AS id; + """ + ) + ) + embedded_model = load_sql_based_model( + parse( # type: ignore + """ + MODEL ( + name db.embedded_no_audits, + kind EMBEDDED + ); + SELECT id FROM db.parent; + """ + ) + ) + child_model = load_sql_based_model( + parse( # type: ignore + """ + MODEL ( + name db.child, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column ds + ), + start '2023-01-01', + audits (not_null(columns := [id])) + ); + SELECT id, '2023-01-05'::DATE AS ds FROM db.embedded_no_audits; + """ + ) + ) + + parent_snapshot = make_snapshot(parent_model) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + parent_snapshot.add_interval("2023-01-01", "2023-01-06") + + embedded_snapshot = make_snapshot( + embedded_model, + nodes={parent_model.fqn: parent_model}, + ) + embedded_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + child_snapshot = make_snapshot( + child_model, + nodes={ + parent_model.fqn: parent_model, + embedded_model.fqn: embedded_model, + }, + ) + child_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + child_snapshot.add_interval("2023-01-01", "2023-01-06") + child_snapshot.add_interval("2023-01-01", "2023-01-06", is_dev=True) + + sibling_model = load_sql_based_model( + parse( # type: ignore + """ + MODEL ( + name db.sibling, + kind FULL, + start '2023-01-01' + ); + SELECT 1 AS id; + """ + ) + ) + sibling_snapshot = make_snapshot(sibling_model) + sibling_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + original_parent_intervals = parent_snapshot.intervals.copy() + original_child_intervals = child_snapshot.intervals.copy() + original_child_dev_intervals = child_snapshot.dev_intervals.copy() + + evaluator = mocker.MagicMock() + evaluator.get_snapshots_to_create.return_value = [] + evaluator.audit.return_value = [] + evaluator.execution_tracker.get_execution_stats.return_value = None + + state_sync = mocker.MagicMock() + + scheduler = Scheduler( + snapshots=[parent_snapshot, embedded_snapshot, child_snapshot, sibling_snapshot], + snapshot_evaluator=evaluator, + state_sync=state_sync, + default_catalog=None, + ) + + deployability_index = DeployabilityIndex.create( + [parent_snapshot, embedded_snapshot, child_snapshot, sibling_snapshot] + ) + + # Unselected FULL parent has depends_on_past=True; execution_time < start must not raise ValueError + early_status = scheduler.audit( + EnvironmentNamingInfo(name="dev"), + start="2023-01-05", + end="2023-01-06", + execution_time="2023-01-02", + selected_snapshots={child_snapshot.name}, + deployability_index=deployability_index, + ignore_cron=True, + ) + assert early_status.is_nothing_to_do + + status = scheduler.audit( + EnvironmentNamingInfo(name="dev"), + start="2023-01-05", + end="2023-01-06", + execution_time="2023-01-07", + selected_snapshots={child_snapshot.name}, + deployability_index=deployability_index, + ignore_cron=True, + ) + + assert status.is_success + evaluator.get_snapshots_to_create.assert_not_called() + evaluator.audit.assert_called_once() + audit_kwargs = evaluator.audit.call_args.kwargs + assert audit_kwargs["snapshot"] == child_snapshot + # Only the audited snapshot and its parents (including transitive embedded parents) are passed; + # unrelated sibling snapshots must be excluded. + assert set(audit_kwargs["snapshots"].keys()) == { + parent_snapshot.name, + embedded_snapshot.name, + child_snapshot.name, + } + assert sibling_snapshot.name not in audit_kwargs["snapshots"] + assert audit_kwargs["deployability_index"] == deployability_index + + # Auditing must not mutate in-memory intervals on scheduler.snapshots + assert parent_snapshot.intervals == original_parent_intervals + assert child_snapshot.intervals == original_child_intervals + assert child_snapshot.dev_intervals == original_child_dev_intervals + + # Direct Scheduler.audit() with only a subset of snapshots (missing parents) must not raise KeyError + evaluator.audit.reset_mock() + subset_scheduler = Scheduler( + snapshots=[child_snapshot], + snapshot_evaluator=evaluator, + state_sync=state_sync, + default_catalog=None, + ) + subset_status = subset_scheduler.audit( + EnvironmentNamingInfo(name="dev"), + start="2023-01-05", + end="2023-01-06", + execution_time="2023-01-07", + deployability_index=deployability_index, + ignore_cron=True, + ) + assert subset_status.is_success + evaluator.get_snapshots_to_create.assert_not_called() + assert set(evaluator.audit.call_args.kwargs["snapshots"].keys()) == {child_snapshot.name}