Skip to content

Commit 596e114

Browse files
dcohen24claudemday-io
authored
fix(plan): account for stored parent changes when categorizing indirect snapshots (#6214)
Signed-off-by: David Cohen <16311507+dcohen24@users.noreply.github.com> Co-authored-by: David Cohen <16311507+dcohen24@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Michael Day <mdaytn@gmail.com>
1 parent dd16a0f commit 596e114

4 files changed

Lines changed: 1090 additions & 14 deletions

File tree

‎sqlmesh/core/context_diff.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ class ContextDiff(PydanticModel):
8888
"""Environment statements."""
8989
diff_rendered: bool = False
9090
"""Whether the diff should compare raw vs rendered models"""
91+
stored_parent_forward_only: t.Dict[SnapshotId, bool] = {}
92+
"""Whether the earlier versions of the stored parents of new indirectly modified snapshots were
93+
forward-only. A past version doesn't record this, so it is read from the snapshot stored for that
94+
version."""
9195

9296
@classmethod
9397
def create(
@@ -233,6 +237,9 @@ def create(
233237

234238
return ContextDiff(
235239
environment=environment,
240+
stored_parent_forward_only=_get_stored_parent_forward_only(
241+
state_reader, merged_snapshots, new_snapshots, modified_snapshots
242+
),
236243
is_new_environment=is_new_environment,
237244
is_unfinalized_environment=bool(env and not env.finalized_ts),
238245
normalize_environment_name=is_new_environment or bool(env and env.normalize_name),
@@ -491,6 +498,57 @@ def text_diff(self, name: str) -> str:
491498
return ""
492499

493500

501+
def _get_stored_parent_forward_only(
502+
state_reader: StateReader,
503+
snapshots: t.Dict[SnapshotId, Snapshot],
504+
new_snapshots: t.Dict[SnapshotId, Snapshot],
505+
modified_snapshots: t.Dict[str, t.Tuple[Snapshot, Snapshot]],
506+
) -> t.Dict[SnapshotId, bool]:
507+
"""Returns whether the past versions of stored parents were forward-only.
508+
509+
A stored parent already exists in state and is a direct parent of a new indirectly modified snapshot
510+
that also has a new direct parent, but it has changed since that snapshot's previous version. These
511+
are the only snapshots for which the plan builder reads the flags. For each such parent, the earlier
512+
versions in its history (`all_versions`, as used by the plan builder) created after the version the
513+
previous snapshot was built from are returned. Nothing is returned for a parent whose history doesn't
514+
reach back to that version, and versions that can't be found in state are left out.
515+
"""
516+
version_ids: t.Set[SnapshotId] = set()
517+
for snapshot, previous_snapshot in modified_snapshots.values():
518+
if (
519+
snapshot.snapshot_id not in new_snapshots
520+
or not any(parent_id in new_snapshots for parent_id in snapshot.parents)
521+
or not snapshot.is_indirectly_modified(previous_snapshot)
522+
):
523+
continue
524+
previous_parent_ids = {p.name: p for p in previous_snapshot.parents}
525+
for parent_id in snapshot.parents:
526+
parent = snapshots.get(parent_id)
527+
previous_parent_id = previous_parent_ids.get(parent_id.name)
528+
if (
529+
not parent
530+
or parent_id in new_snapshots
531+
or previous_parent_id is None
532+
or previous_parent_id == parent_id
533+
):
534+
continue
535+
# The latest version is the parent itself, whose flag is known.
536+
parent_version_ids: t.List[SnapshotId] = []
537+
for version in reversed(parent.all_versions[:-1]):
538+
version_id = version.snapshot_id(parent.name)
539+
if version_id == previous_parent_id:
540+
version_ids.update(parent_version_ids)
541+
break
542+
parent_version_ids.append(version_id)
543+
544+
if not version_ids:
545+
return {}
546+
return {
547+
snapshot_id: snapshot.is_forward_only
548+
for snapshot_id, snapshot in state_reader.get_snapshots(version_ids).items()
549+
}
550+
551+
494552
def _build_requirements(
495553
provided_requirements: t.Dict[str, str],
496554
excluded_requirements: t.Set[str],

‎sqlmesh/core/plan/builder.py‎

Lines changed: 154 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
SnapshotChangeCategory,
3636
)
3737
from sqlmesh.core.snapshot.categorizer import categorize_change
38-
from sqlmesh.core.snapshot.definition import Interval, SnapshotId
38+
from sqlmesh.core.snapshot.definition import Interval, SnapshotDataVersion, SnapshotId
3939
from sqlmesh.utils import columns_to_types_all_known, random_id
4040
from sqlmesh.utils.dag import DAG
4141
from sqlmesh.utils.date import (
@@ -52,6 +52,14 @@
5252
logger = logging.getLogger(__name__)
5353

5454

55+
# Changes in these categories don't require the history of downstream snapshots to be recomputed.
56+
DOWNSTREAM_REBUILD_NOT_REQUIRED_CATEGORIES = {
57+
SnapshotChangeCategory.METADATA,
58+
SnapshotChangeCategory.NON_BREAKING,
59+
SnapshotChangeCategory.INDIRECT_NON_BREAKING,
60+
}
61+
62+
5563
class PlanBuilder:
5664
"""Plan Builder constructs a Plan based on user choices for how they want to backfill, preview, etc. their changes.
5765
@@ -726,6 +734,7 @@ def _categorize_snapshot(
726734
return
727735

728736
all_upstream_forward_only = set()
737+
new_upstream_requires_rebuild = False
729738
all_upstream_categories = set()
730739
direct_parent_categories = set()
731740

@@ -735,30 +744,168 @@ def _categorize_snapshot(
735744
if parent and self._is_new_snapshot(parent):
736745
all_upstream_categories.add(parent.change_category)
737746
all_upstream_forward_only.add(parent.is_forward_only)
747+
if parent.change_category not in DOWNSTREAM_REBUILD_NOT_REQUIRED_CATEGORIES:
748+
new_upstream_requires_rebuild = True
738749
if p_id in snapshot.parents:
739750
direct_parent_categories.add(parent.change_category)
740751

752+
# Direct parents that already exist in state but changed relative to the previous version
753+
# of this snapshot (eg. they were categorized in another plan) don't show up above.
754+
stored_parent_categories: t.Set[SnapshotChangeCategory] = set()
755+
stored_parent_forward_only: t.Set[bool] = set()
756+
if direct_parent_categories:
757+
stored_parent_categories, stored_parent_forward_only = (
758+
self._get_stored_direct_parent_changes(snapshot)
759+
)
760+
761+
if stored_parent_forward_only:
762+
# A stored parent has a breaking version since the previous version of this snapshot (or
763+
# its history can't be traced back that far), so that change is part of this one too and
764+
# its forward-only flags are added to the vote. The new parents keep the rule used when
765+
# only new parents changed, so the same changes to them give the same result. The only
766+
# exception is when none of the new upstream changes require downstream history to be
767+
# recomputed (metadata or non-breaking changes only): then they don't vote, so they can't
768+
# undo a forward-only change to the stored parent. Without such a stored parent the
769+
# decision is the same as when only new parents changed.
770+
all_upstream_forward_only = (
771+
all_upstream_forward_only if new_upstream_requires_rebuild else set()
772+
) | stored_parent_forward_only
773+
741774
if all_upstream_forward_only == {True} or (
742775
snapshot.is_model and snapshot.model.forward_only
743776
):
744777
forward_only = True
745778

746-
if direct_parent_categories.intersection(
779+
if (direct_parent_categories | stored_parent_categories).intersection(
747780
{SnapshotChangeCategory.BREAKING, SnapshotChangeCategory.INDIRECT_BREAKING}
748781
):
749782
snapshot.categorize_as(SnapshotChangeCategory.INDIRECT_BREAKING, forward_only)
750783
elif not direct_parent_categories:
751784
snapshot.categorize_as(
752785
self._get_orphaned_indirect_change_category(snapshot), forward_only
753786
)
754-
elif all_upstream_categories == {SnapshotChangeCategory.METADATA}:
787+
elif (all_upstream_categories | stored_parent_categories) == {
788+
SnapshotChangeCategory.METADATA
789+
}:
755790
snapshot.categorize_as(SnapshotChangeCategory.METADATA, forward_only)
756791
else:
757792
snapshot.categorize_as(SnapshotChangeCategory.INDIRECT_NON_BREAKING, forward_only)
758793
else:
759794
# Metadata updated.
760795
snapshot.categorize_as(SnapshotChangeCategory.METADATA, forward_only)
761796

797+
def _get_parent_versions_since(
798+
self, parent: Snapshot, previous_parent_id: SnapshotId
799+
) -> t.Optional[t.List[SnapshotDataVersion]]:
800+
"""Returns all versions of the parent created after the previous parent, including the current
801+
version. The previous parent itself is excluded.
802+
803+
Returns None if the previous parent is not found in the parent's version history.
804+
"""
805+
versions: t.List[SnapshotDataVersion] = []
806+
for pv in reversed(parent.all_versions):
807+
if pv.snapshot_id(parent.name) == previous_parent_id:
808+
return versions
809+
versions.append(pv)
810+
return None
811+
812+
def _get_parent_categories_since(
813+
self, parent: Snapshot, previous_parent_id: SnapshotId
814+
) -> t.Optional[t.Set[SnapshotChangeCategory]]:
815+
"""Returns the categories of the versions returned by `_get_parent_versions_since`."""
816+
versions = self._get_parent_versions_since(parent, previous_parent_id)
817+
if versions is None:
818+
return None
819+
return {t.cast(SnapshotChangeCategory, v.change_category) for v in versions}
820+
821+
@staticmethod
822+
def _get_known_category(version: SnapshotDataVersion) -> SnapshotChangeCategory:
823+
"""Returns the category of the version, or BREAKING if it isn't one that is assigned today.
824+
825+
A missing category or the deprecated FORWARD_ONLY category may still be found in older state. Both
826+
changed data, so they are treated as breaking, and whether they were forward-only is read from the
827+
stored snapshot like for any other breaking version.
828+
"""
829+
if version.change_category in (
830+
SnapshotChangeCategory.BREAKING,
831+
SnapshotChangeCategory.INDIRECT_BREAKING,
832+
SnapshotChangeCategory.NON_BREAKING,
833+
SnapshotChangeCategory.INDIRECT_NON_BREAKING,
834+
SnapshotChangeCategory.METADATA,
835+
):
836+
return version.change_category
837+
return SnapshotChangeCategory.BREAKING
838+
839+
def _was_applied_forward_only(self, parent: Snapshot, version: SnapshotDataVersion) -> bool:
840+
"""Returns True if the given version of the parent was applied forward-only.
841+
842+
A past version doesn't record this, so it is read from the snapshot stored for that version.
843+
If that snapshot can't be found, we can't tell, so the version is not considered forward-only.
844+
"""
845+
version_id = version.snapshot_id(parent.name)
846+
if version_id == parent.snapshot_id:
847+
return parent.is_forward_only
848+
return self._context_diff.stored_parent_forward_only.get(version_id, False)
849+
850+
def _get_stored_direct_parent_changes(
851+
self, snapshot: Snapshot
852+
) -> t.Tuple[t.Set[SnapshotChangeCategory], t.Set[bool]]:
853+
"""Returns the change categories and forward-only flags of direct parents that already exist in
854+
state (they are not new in this plan) but changed since the previous version of the snapshot
855+
was built.
856+
857+
A forward-only flag is only returned for a parent with a breaking version since then (True if
858+
every such version was applied forward-only), or False for a parent whose history can't be traced
859+
back that far. Metadata and non-breaking changes don't contribute a flag. The flags are added to
860+
the forward-only vote of the new parents, which otherwise follows the same rule as when only new
861+
parents changed.
862+
863+
For example, a parent was changed in a dev plan and is now combined with another parent
864+
that is changed in the current plan. The change to the first parent is not visible to the
865+
categorization of new parents, so it is recovered from the parent's version history.
866+
"""
867+
previous_snapshot = self._context_diff.modified_snapshots[snapshot.name][1]
868+
previous_parent_ids = {p.name: p for p in previous_snapshot.parents}
869+
870+
categories: t.Set[SnapshotChangeCategory] = set()
871+
forward_only: t.Set[bool] = set()
872+
for p_id in snapshot.parents:
873+
parent = self._context_diff.snapshots.get(p_id)
874+
previous_parent_id = previous_parent_ids.get(p_id.name)
875+
if not parent or self._is_new_snapshot(parent):
876+
# Not stored, or categorized as part of this plan.
877+
continue
878+
if previous_parent_id is None or previous_parent_id == p_id:
879+
# Not a parent of the previous version, or unchanged since then.
880+
continue
881+
882+
parent_versions = self._get_parent_versions_since(parent, previous_parent_id)
883+
if parent_versions is None:
884+
# The history doesn't reach back to the previous parent (it only keeps the latest
885+
# versions), so we can't rule out a breaking change. A rebuild is safer than silently
886+
# reusing stale data.
887+
categories.add(SnapshotChangeCategory.INDIRECT_BREAKING)
888+
forward_only.add(False)
889+
continue
890+
891+
version_categories = [(v, self._get_known_category(v)) for v in parent_versions]
892+
categories.update(category for _, category in version_categories)
893+
894+
# Every breaking version of the parent since the previous child requires downstream history to
895+
# be recomputed, unless it was applied forward-only. The parent's latest version being
896+
# forward-only is not enough, an earlier version may not have been.
897+
breaking_versions = [
898+
v
899+
for v, category in version_categories
900+
if category
901+
in (SnapshotChangeCategory.BREAKING, SnapshotChangeCategory.INDIRECT_BREAKING)
902+
]
903+
if breaking_versions:
904+
forward_only.add(
905+
all(self._was_applied_forward_only(parent, v) for v in breaking_versions)
906+
)
907+
return categories, forward_only
908+
762909
def _get_orphaned_indirect_change_category(
763910
self, indirect_snapshot: Snapshot
764911
) -> SnapshotChangeCategory:
@@ -790,17 +937,10 @@ def _get_orphaned_indirect_change_category(
790937
# so we can skip it
791938
continue
792939

793-
# Find the previous snapshot ID of the same parent in the historical chain
794-
previous_parent_found = False
795-
previous_parent_categories = set()
796-
for pv in reversed(current_parent_snapshot.all_versions):
797-
pv_snapshot_id = pv.snapshot_id(current_parent_snapshot.name)
798-
if pv_snapshot_id == pevious_parent_snapshot_id:
799-
previous_parent_found = True
800-
break
801-
previous_parent_categories.add(pv.change_category)
802-
803-
if not previous_parent_found:
940+
previous_parent_categories = self._get_parent_categories_since(
941+
current_parent_snapshot, pevious_parent_snapshot_id
942+
)
943+
if previous_parent_categories is None:
804944
# The previous parent is not in the historical chain so falling back to INDIRECT_BREAKING
805945
return SnapshotChangeCategory.INDIRECT_BREAKING
806946

0 commit comments

Comments
 (0)