Repository navigation
Description
Summary
BuiltInPlanEvaluator.visit_audit_only_run_stage builds its scheduler from the audited snapshots alone:
https://github.com/SQLMesh/sqlmesh/blob/v0.236.4/sqlmesh/core/plan/evaluator.py#L274
With audit_only=True the scheduler renders the audit with snapshots=self.snapshots_by_name (scheduler.py#L539-L548). That map holds only the audited snapshots, so none of their parents resolve to a physical table. Each parent renders as its environment view instead.
That is fine when the environment's views are current. It breaks after a prod plan that failed partway. A paused forward-only change makes the backfill below it run after EnvironmentRecordUpdateStage. If that backfill fails, the environment record names the new snapshots but their views are never published. The next plan, if it changes only audits, goes to AuditOnlyRunStage and:
- fails with a missing table when a parent is new, even though the parent's physical table exists, or
- reads a changed parent's old rows through the old view, with no error. A wrong audit result is the quiet case.
The backfill stage maps parents to the plan's physical tables, so the same audit gives a different answer depending on which stage runs it.
Seen on 0.231.1. Reproduced unchanged on 0.236.4 (latest), Python 3.11, DuckDB 1.5.6.
Repro
python repro.py new or python repro.py changed. It needs only sqlmesh and uses a temp DuckDB file.
repro.py
import logging
import sys
import tempfile
from pathlib import Path
from sqlmesh import Context
from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig, ModelDefaultsConfig
variant = sys.argv[1] if len(sys.argv) > 1 else "new" # "new" or "changed"
class Show(logging.Handler):
def emit(self, r):
msg = r.getMessage()
if "plan stage" in msg:
print(" ", msg)
elif r.exc_info:
print(" ERROR:", str(r.exc_info[1].__cause__ or r.exc_info[1]).splitlines()[0])
logging.getLogger("sqlmesh").addHandler(Show())
logging.getLogger("sqlmesh").setLevel(logging.INFO)
root = Path(tempfile.mkdtemp())
(root / "models").mkdir()
(root / "audits").mkdir()
cfg = Config(
gateways={"local": GatewayConfig(connection=DuckDBConnectionConfig(database=str(root / "db.duckdb")))},
default_gateway="local",
model_defaults=ModelDefaultsConfig(dialect="duckdb", start="2024-01-01"),
)
def write(name, body):
(root / name).write_text(body)
def plan(label):
print(label)
try:
Context(paths=str(root), config=cfg).plan("prod", auto_apply=True, no_prompts=True)
print(" -> applied")
except Exception as e:
print(f" -> {type(e).__name__}: {e}")
def fo(tag):
write(
"models/fo.sql",
"MODEL (name db.fo, kind INCREMENTAL_BY_UNIQUE_KEY (unique_key id, forward_only true));\n"
f"SELECT 1 AS id, '{tag}' AS tag",
)
write("audits/always_fails.sql", "AUDIT (name always_fails);\nSELECT 1 AS x")
# Plan 0: fo -> p -> c
fo("v0")
write("models/p.sql", "MODEL (name db.p, kind FULL);\nSELECT id, 'p0' AS tag FROM db.fo")
write("models/c.sql", "MODEL (name db.c, kind FULL);\nSELECT id FROM db.p")
plan("plan 0: build prod")
# Plan 1: forward-only change to fo, so the backfill below it runs after the
# environment record is updated. c gets an audit that always fails, so the
# backfill fails and the new views are never published.
fo("v1")
if variant == "changed":
write("models/p.sql", "MODEL (name db.p, kind FULL);\nSELECT id, 'p1' AS tag FROM db.fo")
parent, new_tag = "p", "p1"
else:
write("models/q.sql", "MODEL (name db.q, kind FULL);\nSELECT id, 'q1' AS tag FROM db.fo")
parent, new_tag = "q", "q1"
write("models/c.sql", f"MODEL (name db.c, kind FULL, audits (always_fails));\nSELECT id FROM db.{parent}")
plan("plan 1: forward-only change whose backfill fails")
# Plan 2: only c's audit changes (metadata-only), so it goes to the
# audit-only stage. The audit passes if it reads the plan's version of the parent.
write("audits/reads_parent.sql", f"AUDIT (name reads_parent);\nSELECT * FROM db.{parent} WHERE tag <> '{new_tag}'")
write("models/c.sql", f"MODEL (name db.c, kind FULL, audits (reads_parent));\nSELECT id FROM db.{parent}")
plan("plan 2: audit-only change")Output on 0.236.4, plan 2 only (plans 0 and 1 behave as intended, and plan 1 fails on purpose):
##### new
plan 2: audit-only change
Evaluating plan stage CreateSnapshotRecordsStage
Evaluating plan stage PhysicalLayerSchemaCreationStage
Evaluating plan stage AuditOnlyRunStage
ERROR: Catalog Error: Table with name q does not exist!
-> PlanError: Plan application failed.
##### changed
plan 2: audit-only change
Evaluating plan stage CreateSnapshotRecordsStage
Evaluating plan stage PhysicalLayerSchemaCreationStage
Evaluating plan stage AuditOnlyRunStage
ERROR: Audits failed: reads_parent
-> PlanError: Plan application failed.
Expected: in both cases the audit reads the parent version the plan's environment record names (q / p at tag q1 / p1) and passes. In new, q exists only as a physical table. In changed, the audit reads p's old view and sees p0.
In a dev environment the same stage reads the prod view of the parent, while the backfill stage reads the dev table.
Suggested fix
Give the audit-only stage the same parent mapping the backfill stage uses. A local patch along these lines fixes both cases above and the dev case for us:
- Build the scheduler from the audited snapshots plus their direct parents, loaded from the plan environment's snapshots.
- Call
scheduler.audit(..., selected_snapshots={audited names}, deployability_index=...)so only the audited snapshots are audited. UseDeployabilityIndex.create(...)for dev plans andDeployabilityIndex.all_deployable()for prod, as the stage builder does for the backfill. - Pass copies of the parent snapshots.
CachingStateSync.get_snapshotsreturns the same objects the backfill stage holds, andScheduler.auditrewrites the in-memory intervals of every snapshot it is given.
A cleaner route may be to put all_snapshots and a deployability_index on AuditOnlyRunStage when the stage builder creates it (stages.py#L334-L336), the way BackfillStage gets them.
Activity
fix(plan): resolve audit-only parents to the plan's physical tables