From 4e550f1c8bce8485c8a7396da3488812bfae1da6 Mon Sep 17 00:00:00 2001 From: Ky Le Date: Sun, 6 Dec 2026 10:56:57 +0700 Subject: [PATCH] fix(plan): avoid rebuilding children after forward-only parent history expires Signed-off-by: Ky Le --- sqlmesh/core/context_diff.py | 6 +++- sqlmesh/core/plan/builder.py | 7 +++-- sqlmesh/core/snapshot/definition.py | 3 ++ ...dd_forward_only_data_version_provenance.py | 15 ++++++++++ .../core/integration/test_change_scenarios.py | 16 +++++++--- tests/core/test_plan.py | 29 ++++++++++++++----- tests/core/test_snapshot.py | 16 ++++++++++ 7 files changed, 78 insertions(+), 14 deletions(-) create mode 100644 sqlmesh/migrations/v0103_add_forward_only_data_version_provenance.py diff --git a/sqlmesh/core/context_diff.py b/sqlmesh/core/context_diff.py index 048ab3612b..dc37ca3c4f 100644 --- a/sqlmesh/core/context_diff.py +++ b/sqlmesh/core/context_diff.py @@ -539,7 +539,11 @@ def _get_stored_parent_forward_only( if version_id == previous_parent_id: version_ids.update(parent_version_ids) break - parent_version_ids.append(version_id) + # Current versions persist their forward-only provenance in the data version. + # Fetch only legacy entries that predate that field, and always test the history + # boundary first so it is never mistaken for a missing intermediate entry. + if version.forward_only is None: + parent_version_ids.append(version_id) if not version_ids: return {} diff --git a/sqlmesh/core/plan/builder.py b/sqlmesh/core/plan/builder.py index 89b7fdabcd..16d5df7985 100644 --- a/sqlmesh/core/plan/builder.py +++ b/sqlmesh/core/plan/builder.py @@ -839,9 +839,12 @@ def _get_known_category(version: SnapshotDataVersion) -> SnapshotChangeCategory: def _was_applied_forward_only(self, parent: Snapshot, version: SnapshotDataVersion) -> bool: """Returns True if the given version of the parent was applied forward-only. - A past version doesn't record this, so it is read from the snapshot stored for that version. - If that snapshot can't be found, we can't tell, so the version is not considered forward-only. + The version history records this when available. For older versions without that provenance, + read it from the snapshot stored for that version. If neither is available, the version is not + considered forward-only. """ + if version.forward_only is not None: + return version.forward_only version_id = version.snapshot_id(parent.name) if version_id == parent.snapshot_id: return parent.is_forward_only diff --git a/sqlmesh/core/snapshot/definition.py b/sqlmesh/core/snapshot/definition.py index 0cdb033be0..8e67a882be 100644 --- a/sqlmesh/core/snapshot/definition.py +++ b/sqlmesh/core/snapshot/definition.py @@ -251,6 +251,7 @@ class SnapshotDataVersion(PydanticModel, frozen=True): version: str dev_version_: t.Optional[str] = Field(default=None, alias="dev_version") change_category: t.Optional[SnapshotChangeCategory] = None + forward_only: t.Optional[bool] = None physical_schema_: t.Optional[str] = Field(default=None, alias="physical_schema") dev_table_suffix: str table_naming_convention: TableNamingConvention = Field(default=TableNamingConvention.default) @@ -579,6 +580,7 @@ def data_version(self) -> SnapshotDataVersion: version=self.version, dev_version=self.dev_version, change_category=self.change_category, + forward_only=self.is_forward_only, physical_schema=self.physical_schema, dev_table_suffix=self.dev_table_suffix, table_naming_convention=self.table_naming_convention, @@ -1380,6 +1382,7 @@ def data_version(self) -> SnapshotDataVersion: version=self.version, dev_version=self.dev_version, change_category=self.change_category, + forward_only=self.is_forward_only, physical_schema=self.physical_schema, dev_table_suffix=self.dev_table_suffix, table_naming_convention=self.table_naming_convention, diff --git a/sqlmesh/migrations/v0103_add_forward_only_data_version_provenance.py b/sqlmesh/migrations/v0103_add_forward_only_data_version_provenance.py new file mode 100644 index 0000000000..18473b3b21 --- /dev/null +++ b/sqlmesh/migrations/v0103_add_forward_only_data_version_provenance.py @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Gate state reads for persisted forward-only data-version provenance. + +Snapshot data versions now serialize whether a version was applied forward-only. This no-op +migration advances the schema version so older SQLMesh clients cannot read records containing the +new field with a model that does not recognize it. +""" + + +def migrate_schemas(engine_adapter, schema, **kwargs): # type: ignore + pass + + +def migrate_rows(engine_adapter, schema, **kwargs): # type: ignore + pass diff --git a/tests/core/integration/test_change_scenarios.py b/tests/core/integration/test_change_scenarios.py index 08e5aaef84..5f3630ff58 100644 --- a/tests/core/integration/test_change_scenarios.py +++ b/tests/core/integration/test_change_scenarios.py @@ -1682,8 +1682,7 @@ def test_stored_breaking_parent_with_new_forward_only_parent(init_and_plan_conte @time_machine.travel("2023-01-08 15:00:00 UTC") def test_stored_parent_history_with_two_forward_only_changes(init_and_plan_context: t.Callable): """Both breaking versions of the stored parent were applied forward-only, so the child is - forward-only and keeps its previous version. Only the latest version's flag is on the parent - itself, the earlier one has to be read from state: if it can't be found, the child is rebuilt.""" + forward-only and keeps its previous version even if janitor removes the intermediate snapshot.""" context, plan = init_and_plan_context("examples/sushi") context.apply(plan) @@ -1701,8 +1700,17 @@ def test_stored_parent_history_with_two_forward_only_changes(init_and_plan_conte ) context.apply(plan_builder.build()) assert context.get_snapshot("sushi.orders", raise_if_missing=True).is_forward_only + if stamp == "1": + intermediate_parent_id = context.get_snapshot( + "sushi.orders", raise_if_missing=True + ).snapshot_id parent_a = context.get_snapshot("sushi.orders", raise_if_missing=True) + # The intermediate snapshot record is gone, but its provenance remains in the latest snapshot's + # serialized version history. + context.run_janitor(ignore_ttl=True) + assert intermediate_parent_id not in context.state_sync.get_snapshots({intermediate_parent_id}) + # The prod plan only creates a metadata change to the other parent. context.upsert_model("sushi.items", stamp="1") plan_builder = context.plan_builder("prod", skip_tests=True, enable_preview=False) @@ -1712,8 +1720,8 @@ def test_stored_parent_history_with_two_forward_only_changes(init_and_plan_conte plan = plan_builder.build() assert parent_a.snapshot_id not in plan.context_diff.new_snapshots - # The earlier forward-only version was read from state. - assert set(plan.context_diff.stored_parent_forward_only.values()) == {True} + # The earlier forward-only version is recovered from snapshot version provenance. + assert intermediate_parent_id not in plan.context_diff.stored_parent_forward_only child_after = plan.snapshots[context.get_snapshot("sushi.order_items").snapshot_id] assert child_after.change_category == SnapshotChangeCategory.INDIRECT_BREAKING assert child_after.is_forward_only diff --git a/tests/core/test_plan.py b/tests/core/test_plan.py index f412e63eb1..a6f3781820 100644 --- a/tests/core/test_plan.py +++ b/tests/core/test_plan.py @@ -14,7 +14,7 @@ from sqlmesh.core import dialect as d from sqlmesh.core.context import Context -from sqlmesh.core.context_diff import ContextDiff +from sqlmesh.core.context_diff import ContextDiff, _get_stored_parent_forward_only from sqlmesh.core.environment import EnvironmentNamingInfo, EnvironmentStatements from sqlmesh.core.model import ( ExternalModel, @@ -4652,6 +4652,7 @@ def parent_snapshot(value: int, category: SnapshotChangeCategory): ) def test_indirect_change_forward_only_with_stored_parent_history( make_snapshot, + mocker: MockerFixture, earlier_version_flag: t.Optional[bool], earlier_version_category: SnapshotChangeCategory, latest_version_forward_only: bool, @@ -4668,9 +4669,15 @@ def parent_snapshot(value: int): parent_earlier.previous_versions = parent_baseline.all_versions parent_earlier.categorize_as(SnapshotChangeCategory.BREAKING, forward_only=True) parent_earlier.change_category = earlier_version_category + parent_earlier.forward_only = earlier_version_flag is True stored_parent = parent_snapshot(2) - stored_parent.previous_versions = parent_earlier.all_versions + # Simulate a legacy version record with no forward-only provenance. The state lookup below + # provides True, False, or no value, which must remain conservative in the last case. + stored_parent.previous_versions = ( + *parent_earlier.previous_versions, + parent_earlier.data_version.model_copy(update={"forward_only": None}), + ) stored_parent.categorize_as( SnapshotChangeCategory.BREAKING, forward_only=latest_version_forward_only ) @@ -4724,13 +4731,21 @@ def parent_snapshot(value: int): previous_gateway_managed_virtual_layer=False, gateway_managed_virtual_layer=False, environment_statements=[], - stored_parent_forward_only=( - {} - if earlier_version_flag is None - else {parent_earlier.snapshot_id: earlier_version_flag} - ), ) + state_reader = mocker.Mock() + state_reader.get_snapshots.return_value = ( + {} if earlier_version_flag is None else {parent_earlier.snapshot_id: parent_earlier} + ) + context_diff.stored_parent_forward_only = _get_stored_parent_forward_only( + state_reader, + context_diff.snapshots, + context_diff.new_snapshots, + context_diff.modified_snapshots, + ) + requested_version_ids = state_reader.get_snapshots.call_args.args[0] + assert set(requested_version_ids) == {parent_earlier.snapshot_id} + PlanBuilder(context_diff, forward_only=False).build() assert child_new.change_category == SnapshotChangeCategory.INDIRECT_BREAKING diff --git a/tests/core/test_snapshot.py b/tests/core/test_snapshot.py index d92f7dcc18..73cf8d1511 100644 --- a/tests/core/test_snapshot.py +++ b/tests/core/test_snapshot.py @@ -57,6 +57,7 @@ from sqlmesh.core.snapshot.cache import SnapshotCache from sqlmesh.core.snapshot.categorizer import categorize_change from sqlmesh.core.snapshot.definition import ( + SnapshotDataVersion, apply_auto_restatements, display_name, get_next_model_interval_start, @@ -1330,6 +1331,21 @@ def test_snapshot_table_name(snapshot: Snapshot, make_snapshot: t.Callable): ) +@pytest.mark.parametrize("forward_only", [True, False]) +def test_snapshot_data_version_forward_only_provenance(make_snapshot, forward_only: bool): + snapshot = make_snapshot(SqlModel(name="a", query=parse_one("select 1"))) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING, forward_only=forward_only) + + data_version = snapshot.data_version + assert data_version.forward_only is forward_only + assert data_version.dict()["forward_only"] is forward_only + + # Records written before this field was introduced remain valid and carry unknown provenance. + legacy_data = data_version.dict() + legacy_data.pop("forward_only") + assert SnapshotDataVersion(**legacy_data).forward_only is None + + def test_table_name_naming_convention_table_only(make_snapshot: t.Callable[..., Snapshot]): # 3-part naming snapshot = make_snapshot(