Skip to content

Commit a40585d

Browse files
Vamsi-kluclaude
andcommitted
fix(plan): resolve audit-only parents to the plan's physical tables
The audit-only stage built its scheduler from the audited snapshots alone, so audit queries read parents through the prod views: in dev, after a partially failed prod plan (missing table or stale rows), and for embedded parents. Give the stage the plan's snapshots and deployability index, and audit only the selected snapshots against copies of them and their direct parents, so parents resolve to the plan's physical tables. The scheduler overwrites the intervals of the snapshots it receives, so pass copies. Before, the stage stripped the shared snapshots' intervals, and a backfill of the same model later in the plan replaced its whole table. Fixes #6256 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Vamsi-klu <nrvamsi13@gmail.com>
1 parent 54ebf04 commit a40585d

4 files changed

Lines changed: 196 additions & 3 deletions

File tree

‎sqlmesh/core/plan/evaluator.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,8 +273,15 @@ def visit_audit_only_run_stage(
273273
if not audit_snapshots:
274274
return
275275

276-
# If there are any snapshots to be audited, we'll reuse the scheduler's internals to audit them
277-
scheduler = self.create_scheduler(audit_snapshots, self.snapshot_evaluator)
276+
# If there are any snapshots to be audited, we'll reuse the scheduler's internals to audit them.
277+
# Like the backfill, the audits read the plan's physical tables of the audited snapshots' parents.
278+
# The scheduler gets copies because it overwrites the intervals of the snapshots it's given, and
279+
# later stages still use the original intervals.
280+
audit_names = {s.name for s in audit_snapshots}
281+
names = audit_names | {p.name for s in audit_snapshots for p in s.parents}
282+
scheduler = self.create_scheduler(
283+
[stage.all_snapshots[name].copy() for name in names], self.snapshot_evaluator
284+
)
278285
completion_status = scheduler.audit(
279286
plan.environment,
280287
plan.start,
@@ -283,6 +290,8 @@ def visit_audit_only_run_stage(
283290
end_bounded=plan.end_bounded,
284291
start_override_per_model=plan.start_override_per_model,
285292
end_override_per_model=plan.end_override_per_model,
293+
selected_snapshots=audit_names,
294+
deployability_index=stage.deployability_index,
286295
)
287296

288297
if completion_status.is_failure:

‎sqlmesh/core/plan/stages.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,13 @@ class AuditOnlyRunStage:
9292
9393
Args:
9494
snapshots: Snapshots to run audits for.
95+
all_snapshots: All snapshots in the plan by name.
96+
deployability_index: Deployability index for this stage.
9597
"""
9698

9799
snapshots: t.List[Snapshot]
100+
all_snapshots: t.Dict[str, Snapshot]
101+
deployability_index: DeployabilityIndex
98102

99103

100104
@dataclass
@@ -346,7 +350,13 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
346350

347351
audit_only_snapshots = self._get_audit_only_snapshots(new_snapshots)
348352
if audit_only_snapshots:
349-
stages.append(AuditOnlyRunStage(snapshots=list(audit_only_snapshots.values())))
353+
stages.append(
354+
AuditOnlyRunStage(
355+
snapshots=list(audit_only_snapshots.values()),
356+
all_snapshots=snapshots_by_name,
357+
deployability_index=deployability_index,
358+
)
359+
)
350360

351361
if missing_intervals_before_promote:
352362
stages.append(

‎tests/core/integration/test_audits.py‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@
77
import time_machine
88
from sqlglot import exp
99
from IPython.utils.capture import capture_output
10+
from pytest_mock.plugin import MockerFixture
1011

1112
from sqlmesh.core.config import (
1213
Config,
1314
ModelDefaultsConfig,
1415
)
1516
from sqlmesh.core.context import Context
17+
from sqlmesh.core.snapshot import SnapshotEvaluator
1618
from sqlmesh.utils.errors import (
1719
PlanError,
1820
)
@@ -346,3 +348,171 @@ def test_default_audits_with_custom_audit_definitions(tmp_path: Path):
346348
if audit_name == "positive_amount":
347349
assert "column" in audit_args
348350
assert audit_args["column"].name == "amount"
351+
352+
353+
@pytest.mark.parametrize("forward_only", [False, True])
354+
def test_audit_only_change_reads_parent_tables_of_dev_environment(
355+
tmp_path: Path, mocker: MockerFixture, forward_only: bool
356+
):
357+
def write(path: str, contents: str) -> None:
358+
create_temp_file(tmp_path, Path(path), contents)
359+
360+
def write_parent(tag: str) -> None:
361+
kind = "INCREMENTAL_BY_UNIQUE_KEY (unique_key id)"
362+
write("models/p.sql", f"MODEL (name db.p, kind {kind}); SELECT 1 AS id, '{tag}' AS tag")
363+
364+
write_parent("p0")
365+
write("models/c.sql", "MODEL (name db.c, kind FULL); SELECT id FROM db.p")
366+
context = Context(
367+
paths=tmp_path, config=Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
368+
)
369+
context.plan("prod", no_prompts=True, auto_apply=True)
370+
371+
write_parent("p1")
372+
context.load()
373+
context.plan("dev", no_prompts=True, auto_apply=True, forward_only=forward_only)
374+
375+
# An audit-only change to the child, whose audit reads the parent
376+
write(
377+
"audits/reads_parent.sql", "AUDIT (name reads_parent); SELECT * FROM db.p WHERE tag <> 'p1'"
378+
)
379+
write(
380+
"models/c.sql", "MODEL (name db.c, kind FULL, audits (reads_parent)); SELECT id FROM db.p"
381+
)
382+
context.load()
383+
plan = context.plan_builder("dev").build()
384+
assert [s.name for s in plan.new_snapshots] == ['"memory"."db"."c"']
385+
assert plan.new_snapshots[0].is_metadata
386+
387+
audit_spy = mocker.spy(SnapshotEvaluator, "audit")
388+
evaluate_spy = mocker.spy(SnapshotEvaluator, "evaluate")
389+
context.apply(plan)
390+
391+
# Only the child is audited, and it reads the parent's dev snapshot rather than the prod view
392+
assert [call.kwargs["snapshot"].name for call in audit_spy.call_args_list] == [
393+
'"memory"."db"."c"'
394+
]
395+
assert not evaluate_spy.call_args_list
396+
assert not any(result.count for result in audit_spy.spy_return)
397+
dev_p = context.get_snapshot("db.p", raise_if_missing=True)
398+
audit_kwargs = audit_spy.call_args.kwargs
399+
assert audit_kwargs["snapshots"]['"memory"."db"."p"'].snapshot_id == dev_p.snapshot_id
400+
assert audit_kwargs["deployability_index"].is_deployable(dev_p) is not forward_only
401+
402+
403+
def test_audit_only_change_with_non_parent_changed_in_same_plan(
404+
tmp_path: Path, mocker: MockerFixture
405+
):
406+
def write(path: str, contents: str) -> None:
407+
create_temp_file(tmp_path, Path(path), contents)
408+
409+
write("models/p.sql", "MODEL (name db.p, kind FULL); SELECT 1 AS id")
410+
write("models/s.sql", "MODEL (name db.s, kind FULL); SELECT 1 AS id, 's0' AS tag")
411+
write("models/c.sql", "MODEL (name db.c, kind FULL); SELECT id FROM db.p")
412+
context = Context(
413+
paths=tmp_path, config=Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
414+
)
415+
context.plan("prod", no_prompts=True, auto_apply=True)
416+
417+
# The audit reads s, which isn't a parent of c, so s's new table doesn't exist until the backfill
418+
write("models/s.sql", "MODEL (name db.s, kind FULL); SELECT 1 AS id, 's1' AS tag")
419+
write("audits/reads_s.sql", "AUDIT (name reads_s); SELECT * FROM db.s WHERE id IS NULL")
420+
write("models/c.sql", "MODEL (name db.c, kind FULL, audits (reads_s)); SELECT id FROM db.p")
421+
context.load()
422+
plan = context.plan_builder("dev").build()
423+
assert {s.name: s.is_metadata for s in plan.new_snapshots}['"memory"."db"."c"']
424+
425+
audit_spy = mocker.spy(SnapshotEvaluator, "audit")
426+
context.apply(plan)
427+
428+
# c is audited once and its audit finds nothing. spy_return would be s's, from the backfill
429+
c_results = [
430+
results
431+
for call, results in zip(audit_spy.call_args_list, audit_spy.spy_return_list)
432+
if call.kwargs["snapshot"].name == '"memory"."db"."c"'
433+
]
434+
assert [[result.count for result in results] for results in c_results] == [[0]]
435+
436+
437+
@pytest.mark.parametrize("variant", ["new_parent", "changed_parent"])
438+
def test_audit_only_change_after_failed_prod_plan(tmp_path: Path, variant: str):
439+
def write(path: str, contents: str) -> None:
440+
create_temp_file(tmp_path, Path(path), contents)
441+
442+
def fo(tag: str) -> None:
443+
write(
444+
"models/fo.sql",
445+
"MODEL (name db.fo, kind INCREMENTAL_BY_UNIQUE_KEY (unique_key id, forward_only true));"
446+
f" SELECT 1 AS id, '{tag}' AS tag",
447+
)
448+
449+
config = Config(model_defaults=ModelDefaultsConfig(dialect="duckdb", start="2024-01-01"))
450+
write("audits/always_fails.sql", "AUDIT (name always_fails); SELECT 1 AS x")
451+
fo("v0")
452+
write("models/p.sql", "MODEL (name db.p, kind FULL); SELECT id, 'p0' AS tag FROM db.fo")
453+
write("models/c.sql", "MODEL (name db.c, kind FULL); SELECT id FROM db.p")
454+
context = Context(paths=tmp_path, config=config)
455+
context.plan("prod", no_prompts=True, auto_apply=True)
456+
457+
# The forward-only change makes the backfill run after the environment record is updated, and
458+
# the failing audit stops the plan before the virtual layer is updated
459+
fo("v1")
460+
parent, new_tag = ("q", "q1") if variant == "new_parent" else ("p", "p1")
461+
write(
462+
f"models/{parent}.sql",
463+
f"MODEL (name db.{parent}, kind FULL); SELECT id, '{new_tag}' AS tag FROM db.fo",
464+
)
465+
write(
466+
"models/c.sql",
467+
f"MODEL (name db.c, kind FULL, audits (always_fails)); SELECT id FROM db.{parent}",
468+
)
469+
context.load()
470+
with pytest.raises(PlanError):
471+
context.plan("prod", no_prompts=True, auto_apply=True)
472+
473+
# The audit must read the parent version named by the environment record
474+
write(
475+
"audits/reads_parent.sql",
476+
f"AUDIT (name reads_parent); SELECT * FROM db.{parent} WHERE tag <> '{new_tag}'",
477+
)
478+
write(
479+
"models/c.sql",
480+
f"MODEL (name db.c, kind FULL, audits (reads_parent)); SELECT id FROM db.{parent}",
481+
)
482+
context.load()
483+
context.plan("prod", no_prompts=True, auto_apply=True)
484+
485+
assert context.engine_adapter.fetchall(f"SELECT tag FROM db.{parent}") == [(new_tag,)]
486+
487+
488+
def test_audit_only_change_keeps_intervals_of_snapshots_backfilled_in_same_plan(tmp_path: Path):
489+
def write_models(start: str, audits: str = "") -> None:
490+
# Both models replace their whole table when they think it's their first insert
491+
kind = f"INCREMENTAL_BY_UNIQUE_KEY (unique_key ds), start '{start}', cron '@daily'"
492+
create_temp_file(
493+
tmp_path,
494+
Path("models/p.sql"),
495+
f"MODEL (name db.p, kind {kind}); SELECT @start_ds AS ds",
496+
)
497+
create_temp_file(
498+
tmp_path,
499+
Path("models/c.sql"),
500+
f"MODEL (name db.c, kind {kind}{audits}); SELECT DISTINCT @start_ds AS ds FROM db.p",
501+
)
502+
503+
write_models(start="2023-01-02")
504+
context = Context(
505+
paths=tmp_path, config=Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))
506+
)
507+
with time_machine.travel("2023-01-03 00:00:00 UTC"):
508+
context.plan("prod", no_prompts=True, auto_apply=True)
509+
510+
# Moving the start back is a metadata change that backfills the earlier day in the same
511+
# plan that audits the child
512+
write_models(start="2023-01-01", audits=", audits (not_null(columns := (ds)))")
513+
context.load()
514+
context.plan("prod", no_prompts=True, auto_apply=True)
515+
516+
expected = [("2023-01-01",), ("2023-01-02",)]
517+
assert sorted(context.engine_adapter.fetchall("SELECT ds FROM db.p")) == expected
518+
assert sorted(context.engine_adapter.fetchall("SELECT ds FROM db.c")) == expected

‎tests/core/test_plan_stages.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,6 +1316,10 @@ def _get_snapshots(snapshot_ids: t.List[SnapshotId]) -> t.Dict[SnapshotId, Snaps
13161316
assert isinstance(audit_only_stage, AuditOnlyRunStage)
13171317
assert len(audit_only_stage.snapshots) == 1
13181318
assert audit_only_stage.snapshots[0].snapshot_id == new_snapshot_a.snapshot_id
1319+
assert audit_only_stage.all_snapshots == {'"a"': new_snapshot_a, '"b"': new_snapshot_b}
1320+
assert audit_only_stage.deployability_index == DeployabilityIndex.create(
1321+
[new_snapshot_a, new_snapshot_b]
1322+
)
13191323

13201324
# Verify BackfillStage
13211325
backfill_stage = stages[4]

0 commit comments

Comments
 (0)