3535 SnapshotChangeCategory ,
3636)
3737from 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
3939from sqlmesh .utils import columns_to_types_all_known , random_id
4040from sqlmesh .utils .dag import DAG
4141from sqlmesh .utils .date import (
5252logger = 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+
5563class 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