Skip to content

Commit 6cdfcca

Browse files
committed
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 <nrvamsi13@gmail.com>
1 parent 1f96a72 commit 6cdfcca

8 files changed

Lines changed: 2004 additions & 37 deletions

File tree

‎sqlmesh/core/plan/evaluator.py‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,16 +273,34 @@ def visit_audit_only_run_stage(
273273
if not audit_snapshots:
274274
return
275275

276+
# Copy snapshots so Scheduler.audit()'s in-place interval refresh/removal
277+
# does not mutate shared instances held by other stages or CachingStateSync.
278+
all_snapshots = stage.all_snapshots | {s.name: s for s in audit_snapshots}
279+
snapshots = [
280+
s.copy(
281+
update={
282+
"intervals": s.intervals.copy(),
283+
"dev_intervals": s.dev_intervals.copy(),
284+
"pending_restatement_intervals": s.pending_restatement_intervals.copy(),
285+
}
286+
)
287+
for s in all_snapshots.values()
288+
]
289+
276290
# 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)
291+
scheduler = self.create_scheduler(snapshots, self.snapshot_evaluator)
278292
completion_status = scheduler.audit(
279293
plan.environment,
280294
plan.start,
281295
plan.end,
282296
execution_time=plan.execution_time,
297+
ignore_cron=plan.ignore_cron,
283298
end_bounded=plan.end_bounded,
284299
start_override_per_model=plan.start_override_per_model,
285300
end_override_per_model=plan.end_override_per_model,
301+
selected_snapshots={s.name for s in audit_snapshots},
302+
circuit_breaker=self._circuit_breaker,
303+
deployability_index=stage.deployability_index,
286304
)
287305

288306
if completion_status.is_failure:

‎sqlmesh/core/plan/stages.py‎

Lines changed: 70 additions & 5 deletions
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
@@ -344,10 +348,6 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
344348
)
345349
)
346350

347-
audit_only_snapshots = self._get_audit_only_snapshots(new_snapshots)
348-
if audit_only_snapshots:
349-
stages.append(AuditOnlyRunStage(snapshots=list(audit_only_snapshots.values())))
350-
351351
if missing_intervals_before_promote:
352352
stages.append(
353353
BackfillStage(
@@ -372,6 +372,35 @@ def build(self, plan: EvaluatablePlan) -> t.List[PlanStage]:
372372
)
373373
)
374374

375+
audit_only_snapshots = self._get_audit_only_snapshots(
376+
plan, new_snapshots, deployability_index, needs_backfill
377+
)
378+
audit_only_before_promote: t.List[Snapshot] = []
379+
audit_only_after_promote: t.List[Snapshot] = []
380+
if audit_only_snapshots:
381+
after_promote_work_ids = {s.snapshot_id for s in missing_intervals_after_promote} | {
382+
s.snapshot_id
383+
for s in snapshots_with_schema_migration
384+
if s.requires_schema_migration_in_prod and not s.is_metadata
385+
}
386+
for s_id in list(after_promote_work_ids):
387+
after_promote_work_ids.update(dag.downstream(s_id))
388+
389+
audit_only_before_promote = [
390+
s for s_id, s in audit_only_snapshots.items() if s_id not in after_promote_work_ids
391+
]
392+
audit_only_after_promote = [
393+
s for s_id, s in audit_only_snapshots.items() if s_id in after_promote_work_ids
394+
]
395+
if audit_only_before_promote:
396+
stages.append(
397+
AuditOnlyRunStage(
398+
snapshots=audit_only_before_promote,
399+
all_snapshots=snapshots_by_name,
400+
deployability_index=deployability_index,
401+
)
402+
)
403+
375404
# note: "restatement stage" (which is clearing intervals in state - not actually performing the restatements, that's the backfill stage)
376405
# 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.
377406
# 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]:
416445
)
417446
)
418447

448+
if audit_only_after_promote:
449+
stages.append(
450+
AuditOnlyRunStage(
451+
snapshots=audit_only_after_promote,
452+
all_snapshots=snapshots_by_name,
453+
deployability_index=deployability_index,
454+
)
455+
)
456+
419457
if not plan.is_dev and plan.ensure_finalized_snapshots and promoted_snapshots:
420458
# Unpause right before updating the virtual layer and finalizing the environment in case when
421459
# we need to use the finalized snapshots for subsequent plan applications.
@@ -604,8 +642,18 @@ def _missing_intervals(
604642
)
605643

606644
def _get_audit_only_snapshots(
607-
self, new_snapshots: t.Dict[SnapshotId, Snapshot]
645+
self,
646+
plan: EvaluatablePlan,
647+
new_snapshots: t.Dict[SnapshotId, Snapshot],
648+
deployability_index: DeployabilityIndex,
649+
needs_backfill: bool,
608650
) -> t.Dict[SnapshotId, Snapshot]:
651+
promoted_snapshot_ids = (
652+
set(plan.environment.promoted_snapshot_ids)
653+
if plan.environment.promoted_snapshot_ids is not None
654+
else None
655+
)
656+
609657
metadata_snapshots = []
610658
for snapshot in new_snapshots.values():
611659
if (
@@ -616,6 +664,23 @@ def _get_audit_only_snapshots(
616664
):
617665
continue
618666

667+
if not (
668+
plan.is_selected_for_backfill(snapshot.name)
669+
or promoted_snapshot_ids is None
670+
or snapshot.snapshot_id in promoted_snapshot_ids
671+
):
672+
continue
673+
674+
if (
675+
plan.is_dev
676+
and needs_backfill
677+
and not snapshot.is_symbolic
678+
and not deployability_index.is_deployable(snapshot)
679+
and not plan.is_selected_for_backfill(snapshot.name)
680+
and not snapshot.dev_intervals
681+
):
682+
continue
683+
619684
metadata_snapshots.append(snapshot)
620685

621686
# Bulk load all the previous snapshots

‎sqlmesh/core/scheduler.py‎

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def merged_missing_intervals(
173173
allow_partials, and other attributes that could cause the intervals to exceed the target end date.
174174
selected_snapshots: A set of snapshot names to run. If not provided, all snapshots will be run.
175175
"""
176-
snapshots_to_intervals = merged_missing_intervals(
176+
return merged_missing_intervals(
177177
snapshots=self.snapshot_per_version.values(),
178178
start=start,
179179
end=end,
@@ -184,14 +184,8 @@ def merged_missing_intervals(
184184
end_override_per_model=end_override_per_model,
185185
ignore_cron=ignore_cron,
186186
end_bounded=end_bounded,
187+
selected_snapshots=selected_snapshots,
187188
)
188-
# Filtering snapshots after computing missing intervals because we need all snapshots in order
189-
# to correctly infer start dates.
190-
if selected_snapshots is not None:
191-
snapshots_to_intervals = {
192-
s: i for s, i in snapshots_to_intervals.items() if s.name in selected_snapshots
193-
}
194-
return snapshots_to_intervals
195189

196190
def evaluate(
197191
self,
@@ -314,6 +308,8 @@ def audit(
314308
# by _run_or_audit as "missing intervals" to reuse the rest of it's logic
315309
remove_intervals = {}
316310
for snapshot in self.snapshots.values():
311+
if selected_snapshots is not None and snapshot.name not in selected_snapshots:
312+
continue
317313
removal_intervals = snapshot.get_removal_interval(
318314
start, end, execution_time, is_preview=True
319315
)
@@ -505,19 +501,22 @@ def run_merged_intervals(
505501
selected_models=selected_models,
506502
)
507503

508-
# We only need to create physical tables if the snapshot is not representative or if it
509-
# needs backfill
510-
snapshots_to_create_candidates = [
511-
s
512-
for s in selected_snapshots
513-
if not deployability_index.is_representative(s) or s in batched_intervals
514-
]
515-
snapshots_to_create = {
516-
s.snapshot_id
517-
for s in self.snapshot_evaluator.get_snapshots_to_create(
518-
snapshots_to_create_candidates, deployability_index
519-
)
520-
}
504+
if audit_only:
505+
snapshots_to_create: t.Set[SnapshotId] = set()
506+
else:
507+
# We only need to create physical tables if the snapshot is not representative or if it
508+
# needs backfill
509+
snapshots_to_create_candidates = [
510+
s
511+
for s in selected_snapshots
512+
if not deployability_index.is_representative(s) or s in batched_intervals
513+
]
514+
snapshots_to_create = {
515+
s.snapshot_id
516+
for s in self.snapshot_evaluator.get_snapshots_to_create(
517+
snapshots_to_create_candidates, deployability_index
518+
)
519+
}
521520

522521
dag = self._dag(
523522
batched_intervals,
@@ -858,7 +857,12 @@ def _run_or_audit(
858857
)
859858
execution_time = execution_time or now_timestamp()
860859

861-
self.state_sync.refresh_snapshot_intervals(self.snapshots.values())
860+
snapshots_to_refresh = (
861+
[s for s in self.snapshots.values() if s.name in selected_snapshots]
862+
if audit_only and selected_snapshots is not None
863+
else self.snapshots.values()
864+
)
865+
self.state_sync.refresh_snapshot_intervals(snapshots_to_refresh)
862866
for s_id, interval in (remove_intervals or {}).items():
863867
self.snapshots[s_id].remove_interval(interval)
864868

@@ -1059,6 +1063,7 @@ def merged_missing_intervals(
10591063
end_override_per_model: t.Optional[t.Dict[str, datetime]] = None,
10601064
ignore_cron: bool = False,
10611065
end_bounded: bool = False,
1066+
selected_snapshots: t.Optional[t.Collection[str]] = None,
10621067
) -> SnapshotToIntervals:
10631068
"""Find the largest contiguous date interval parameters based only on what is missing.
10641069
@@ -1079,6 +1084,8 @@ def merged_missing_intervals(
10791084
ignore_cron: Whether to ignore the node's cron schedule.
10801085
end_bounded: If set to true, the returned intervals will be bounded by the target end date, disregarding lookback,
10811086
allow_partials, and other attributes that could cause the intervals to exceed the target end date.
1087+
selected_snapshots: Optional collection of snapshot names to compute intervals for while still using all snapshots
1088+
to infer start dates.
10821089
"""
10831090
restatements = restatements or {}
10841091
validate_date_range(start, end)
@@ -1094,6 +1101,7 @@ def merged_missing_intervals(
10941101
end_override_per_model=end_override_per_model,
10951102
ignore_cron=ignore_cron,
10961103
end_bounded=end_bounded,
1104+
selected_snapshots=selected_snapshots,
10971105
)
10981106

10991107

@@ -1109,6 +1117,7 @@ def compute_interval_params(
11091117
end_override_per_model: t.Optional[t.Dict[str, datetime]] = None,
11101118
ignore_cron: bool = False,
11111119
end_bounded: bool = False,
1120+
selected_snapshots: t.Optional[t.Collection[str]] = None,
11121121
) -> SnapshotToIntervals:
11131122
"""Find the largest contiguous date interval parameters based only on what is missing.
11141123
@@ -1129,6 +1138,8 @@ def compute_interval_params(
11291138
ignore_cron: Whether to ignore the node's cron schedule.
11301139
end_bounded: If set to true, the returned intervals will be bounded by the target end date, disregarding lookback,
11311140
allow_partials, and other attributes that could cause the intervals to exceed the target end date.
1141+
selected_snapshots: Optional collection of snapshot names to compute intervals for while still using all snapshots
1142+
to infer start dates.
11321143
11331144
Returns:
11341145
A dict containing all snapshots needing to be run with their associated interval params.
@@ -1146,6 +1157,7 @@ def compute_interval_params(
11461157
end_override_per_model=end_override_per_model,
11471158
ignore_cron=ignore_cron,
11481159
end_bounded=end_bounded,
1160+
selected_snapshots=selected_snapshots,
11491161
).items():
11501162
contiguous_batch = []
11511163
next_batch: Intervals = []

‎sqlmesh/core/snapshot/definition.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2045,6 +2045,7 @@ def missing_intervals(
20452045
end_override_per_model: t.Optional[t.Dict[str, datetime]] = None,
20462046
ignore_cron: bool = False,
20472047
end_bounded: bool = False,
2048+
selected_snapshots: t.Optional[t.Collection[str]] = None,
20482049
) -> t.Dict[Snapshot, Intervals]:
20492050
"""Returns all missing intervals given a collection of snapshots."""
20502051
if not isinstance(snapshots, dict):
@@ -2063,7 +2064,12 @@ def missing_intervals(
20632064
end_override_per_model = end_override_per_model or {}
20642065
deployability_index = deployability_index or DeployabilityIndex.all_deployable()
20652066

2067+
if selected_snapshots is not None and not isinstance(selected_snapshots, (set, frozenset)):
2068+
selected_snapshots = set(selected_snapshots)
2069+
20662070
for snapshot in snapshots.values():
2071+
if selected_snapshots is not None and snapshot.name not in selected_snapshots:
2072+
continue
20672073
if not snapshot.evaluatable:
20682074
continue
20692075

0 commit comments

Comments
 (0)