Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion sqlmesh/core/context_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}
Expand Down
7 changes: 5 additions & 2 deletions sqlmesh/core/plan/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions sqlmesh/core/snapshot/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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
16 changes: 12 additions & 4 deletions tests/core/integration/test_change_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
Expand All @@ -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
Expand Down
29 changes: 22 additions & 7 deletions tests/core/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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
)
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions tests/core/test_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down