Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): resume Snowflake scans instead of restarting from row zero (#103240)

jake sciotto2b4e55f03d28
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
index ead5bb02aa1f..d22781c8bf3b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py
@@ -139,6 +139,23 @@ async def trim_source_job_inputs(source: "ExternalDataSource") -> None:
await database_sync_to_async_pool(source.save)()
+def _source_type_for_death_event(inputs: "ImportDataActivityInputs") -> str | None:
+ """The source type behind a dying run, so a death event is diagnosable per connector without
+ joining against the source table. Best-effort: the death event must survive a failed lookup."""
+ try:
+ from products.warehouse_sources.backend.models.external_data_source import ( # noqa: PLC0415 — Django models must not be imported at this activity module's load time
+ ExternalDataSource,
+ )
+
+ return (
+ ExternalDataSource.objects.filter(id=inputs.source_id, team_id=inputs.team_id)
+ .values_list("source_type", flat=True)
+ .first()
+ )
+ except Exception:
+ return None
+
+
def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: FilteringBoundLogger) -> None:
logger.debug("Checking for heartbeat timeout reporting...")
@@ -213,6 +230,7 @@ def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: Filteri
"workflow_run_id": info.workflow_run_id,
"workflow_type": info.workflow_type,
"attempt": info.attempt,
+ "source_type": _source_type_for_death_event(inputs),
}
# What the dead attempt said it was doing, and what its pod neighbours said, at the moment
# of death — the per-activity context this event otherwise cannot carry. Adds nothing when
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
index 8262b30c6882..4b3754eb3d63 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/snowflake.py
@@ -13,14 +13,18 @@ from __future__ import annotations
import collections
from collections.abc import Iterator
from contextlib import contextmanager
+from datetime import date, datetime
+from decimal import Decimal
from typing import Any, Optional
import structlog
+import pyarrow.compute
import snowflake.connector
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from structlog.types import FilteringBoundLogger
+from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import (
@@ -28,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers
incremental_type_to_operator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import log_connection_open
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql import (
AnsiIdentifierQuoter,
ValidatedRowFilter,
@@ -54,10 +59,42 @@ from products.warehouse_sources.backend.types import IncrementalFieldType
__all__ = [
"SnowflakeImplementation",
+ "SnowflakeResumeState",
"filter_snowflake_incremental_fields",
]
+@frozen
+class SnowflakeResumeState:
+ """Keyset checkpoint for a mid-job retry: the scan's ORDER BY column and the largest value of
+ that column in the last batch the pipeline persisted. A retry restarts the scan past it instead
+ of re-reading the whole table from row zero."""
+
+ order_column: str
+ last_value: Any
+
+
+def _batch_checkpoint(batch: Any, order_column: str) -> SnowflakeResumeState | None:
+ """The resume checkpoint a persisted batch earns: the largest ``order_column`` value it carries,
+ coerced to a JSON-safe scalar (the state crosses Redis as JSON, and Snowflake casts the string
+ form back in the resume comparison). None when the column is absent from the batch, empty, or of
+ a type a JSON round-trip cannot carry — the source then just doesn't checkpoint, which degrades
+ to today's restart-from-zero rather than resuming from a corrupt value."""
+ index = batch.schema.get_field_index(order_column)
+ if index < 0:
+ return None
+ value = pyarrow.compute.max(batch.column(index)).as_py()
+ if value is None:
+ return None
+ if isinstance(value, datetime | date):
+ value = value.isoformat()
+ elif isinstance(value, Decimal):
+ value = str(value)
+ elif not isinstance(value, str | int | float):
+ return None
+ return SnowflakeResumeState(order_column=order_column, last_value=value)
+
+
def filter_snowflake_incremental_fields(
columns: list[tuple[str, str, bool]],
) -> list[tuple[str, IncrementalFieldType, bool]]:
@@ -138,21 +175,35 @@ def _build_query(
enabled_columns: list[str] | None = None,
primary_keys: list[str] | None = None,
row_filters: list[ValidatedRowFilter] | None = None,
+ order_by_key: str | None = None,
+ resume_value: Any | None = None,
) -> tuple[str, tuple[Any, ...]]:
projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)
select_clause = format_projected_select_clause(projected, _SNOWFLAKE_IDENTIFIER_QUOTER)
table_ref = f"{database}.{schema}.{table_name}"
- # Positional param order: IDENTIFIER(%s), then any incremental value, then row-filter values.
+ # Positional param order: IDENTIFIER(%s), then the keyset/incremental bound, then row-filter values.
filter_conditions, filter_values = render_positional_conditions(row_filters or [], _SNOWFLAKE_IDENTIFIER_QUOTER)
if not should_use_incremental_field:
- if filter_conditions:
+ conditions = list(filter_conditions)
+ values: tuple[Any, ...] = (table_ref, *filter_values)
+ order_clause = ""
+ if order_by_key is not None:
+ # Ordering by the (unique) key is what makes a per-batch checkpoint meaningful: every
+ # row at or below it is persisted, so a resume with a strict `>` is exact — no
+ # duplicates and no skipped rows.
+ quoted_key = _SNOWFLAKE_IDENTIFIER_QUOTER.quote(order_by_key)
+ order_clause = f" ORDER BY {quoted_key} ASC"
+ if resume_value is not None:
+ conditions.insert(0, f"{quoted_key} > %s")
+ values = (table_ref, resume_value, *filter_values)
+ if conditions:
return (
- f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {' AND '.join(filter_conditions)}",
- (table_ref, *filter_values),
+ f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {' AND '.join(conditions)}{order_clause}",
+ values,
)
- return f"SELECT {select_clause} FROM IDENTIFIER(%s)", (table_ref,)
+ return f"SELECT {select_clause} FROM IDENTIFIER(%s){order_clause}", values
if incremental_field is None or incremental_field_type is None:
raise ValueError("incremental_field and incremental_field_type can't be None")
@@ -162,6 +213,12 @@ def _build_query(
operator = incremental_type_to_operator(incremental_field_type)
quoted_field = _SNOWFLAKE_IDENTIFIER_QUOTER.quote(incremental_field)
+ if resume_value is not None:
+ # A checkpoint is the max of a persisted batch, and rows sharing that value can sit in the
+ # next, unpersisted batch — so the resume bound is inclusive and the primary-key merge
+ # dedups the re-read overlap (resume is only enabled when the table merges on a key).
+ db_incremental_field_last_value = resume_value
+ operator = ">="
conditions = [f"{quoted_field} {operator} %s", *filter_conditions]
return (
f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE {' AND '.join(conditions)} ORDER BY {quoted_field} ASC",
@@ -587,7 +644,12 @@ class SnowflakeImplementation(
# Pipeline build — the dlt `SourceResponse` for a single table
# ------------------------------------------------------------------
- def build_pipeline(self, config: SnowflakeSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ def build_pipeline(
+ self,
+ config: SnowflakeSourceConfig,
+ inputs: SourceInputs,
+ resumable_source_manager: ResumableSourceManager[SnowflakeResumeState] | None = None,
+ ) -> SourceResponse:
# Per-row routing: a multi-schema row pins its own namespace via `schema_metadata`,
# a legacy single-schema row falls back to `config.schema`. The database is fixed
# per connection. `response_name` preserves the legacy Delta subdir (`dwh_storage_key`).
@@ -613,6 +675,36 @@ class SnowflakeImplementation(
if cursor is None:
raise Exception("Can't create cursor to Snowflake")
primary_keys = self.get_primary_keys_for_table(cursor, database, schema, table_name)
+
+ # The keyset column checkpoints and resumes a mid-job retry. Both shapes need the
+ # merge-on-primary-key dedup downstream, so neither activates without a key: an
+ # incremental scan checkpoints its (already ordered) incremental field, a full
+ # refresh orders by a single-column primary key. Snowflake declares but does not
+ # enforce primary keys, and the full refresh resumes with a strict `>` — duplicate
+ # boundary values spanning batches would be skipped — so the full-refresh shape
+ # additionally requires the key a full probe proved unique. The incremental resume
+ # is inclusive and needs only the merge, so the declared key is enough there. A
+ # multi-column, unverified, or missing key keeps today's restart-from-zero behavior.
+ order_column: str | None = None
+ if resumable_source_manager is not None and primary_keys:
+ if should_use_incremental_field:
+ order_column = incremental_field
+ elif len(primary_keys) == 1 and inputs.verified_primary_keys == primary_keys:
+ order_column = primary_keys[0]
+ order_by_key = order_column if not should_use_incremental_field else None
+
+ resume_value: Any | None = None
+ if (
+ order_column is not None
+ and resumable_source_manager is not None
+ and resumable_source_manager.can_resume()
+ ):
+ resume_state = resumable_source_manager.load_state()
+ # A checkpoint written against a different column (the schema's key or
+ # incremental config changed between attempts) must not bound this scan.
+ if resume_state is not None and resume_state.order_column == order_column:
+ resume_value = resume_state.last_value
+
inner_query, inner_query_params = _build_query(
database,
schema,
@@ -624,8 +716,19 @@ class SnowflakeImplementation(
enabled_columns=enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
+ order_by_key=order_by_key,
+ resume_value=resume_value,
)
- rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_params, logger)
+ if resume_value is not None:
+ # The count is a progress estimate; re-counting the full table is the other
+ # half of the "every retry re-issues the same queries" cost, so a resumed
+ # attempt skips it.
+ # The checkpoint value is customer data (it can be an email or an id), so only
+ # the column and the resume decision are logged.
+ logger.debug(f"Resuming Snowflake scan from a checkpoint on {order_column}, skipping COUNT(*)")
+ rows_to_sync = None
+ else:
+ rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_params, logger)
def get_rows() -> Iterator[Any]:
with self.connect(config) as streaming_connection:
@@ -643,6 +746,8 @@ class SnowflakeImplementation(
enabled_columns=enabled_columns,
primary_keys=primary_keys,
row_filters=row_filters,
+ order_by_key=order_by_key,
+ resume_value=resume_value,
)
logger.debug(f"Snowflake query: {query.format(params)}")
streaming_cursor.execute(query, params, timeout=_SNOWFLAKE_QUERY_TIMEOUT_SECONDS)
@@ -656,7 +761,18 @@ class SnowflakeImplementation(
# (e.g. a `0001-01-01`/`9999-12-31` sentinel) — and the mixed units make
# pyarrow fail to assemble the batches ("Schema at index N was different").
# The pipeline normalizes timestamps to `us` downstream regardless.
- yield from streaming_cursor.fetch_arrow_batches(force_microsecond_precision=True)
+ pending_checkpoint: SnowflakeResumeState | None = None
+ for batch in streaming_cursor.fetch_arrow_batches(force_microsecond_precision=True):
+ if resumable_source_manager is not None and order_column is not None:
+ # Control re-entering the loop means the previously yielded batch was
+ # persisted (the pipeline's batcher guarantees yield => persisted), so
+ # its checkpoint is now safe to save. The final batch's checkpoint is
+ # deliberately never saved: a retry after full extraction re-reads only
+ # that batch, and the merge dedups it.
+ if pending_checkpoint is not None:
+ resumable_source_manager.save_state(pending_checkpoint)
+ pending_checkpoint = _batch_checkpoint(batch, order_column) or pending_checkpoint
+ yield batch
return SourceResponse(
name=location.response_name, items=get_rows, primary_keys=primary_keys, rows_to_sync=rows_to_sync
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py
index 366ef1713263..b714111ab030 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/source.py
@@ -16,15 +16,18 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldSelectConfig,
SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.base import SQLSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.snowflake import (
SnowflakeSourceConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.snowflake import (
SnowflakeImplementation,
+ SnowflakeResumeState,
get_connection_metadata as get_connection_metadata_snowflake,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -99,11 +102,24 @@ SnowflakeErrors = {
@SourceRegistry.register
-class SnowflakeSource(SQLSource[SnowflakeSourceConfig]):
+class SnowflakeSource(SQLSource[SnowflakeSourceConfig], ResumableSource[SnowflakeSourceConfig, SnowflakeResumeState]):
@property
def get_implementation(self) -> SnowflakeImplementation:
return _SNOWFLAKE_IMPLEMENTATION
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SnowflakeResumeState]:
+ return ResumableSourceManager[SnowflakeResumeState](inputs, SnowflakeResumeState)
+
+ # The activity dispatch checks ResumableSource before SimpleSource, so the three-argument
+ # resumable signature is the one that runs; the SQLSource two-argument form is unreachable here.
+ def source_for_pipeline( # type: ignore[override]
+ self,
+ config: SnowflakeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SnowflakeResumeState],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return self.get_implementation.build_pipeline(config, inputs, resumable_source_manager=resumable_source_manager)
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SNOWFLAKE
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index 6ac9cf72959e..d23314525756 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -1,14 +1,18 @@
+from collections.abc import Iterable
from datetime import UTC, datetime
+from typing import Any, cast
import pytest
from unittest.mock import MagicMock, patch
+import pyarrow as pa
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from snowflake.connector.errors import DatabaseError, HttpError, OperationalError
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql.predicates import (
ColumnTypeCategory,
ValidatedRowFilter,
@@ -22,6 +26,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.snowflake.
_SNOWFLAKE_NETWORK_TIMEOUT_SECONDS,
_SNOWFLAKE_QUERY_TIMEOUT_SECONDS,
SnowflakeImplementation,
+ SnowflakeResumeState,
+ _batch_checkpoint,
_build_query,
_parse_clustering_key_leading_column,
_split_display_name,
@@ -183,6 +189,65 @@ class TestBuildQuery:
assert 'ORDER BY "Date Established" ASC' in sql
+class TestBuildQueryResume:
+ def test_full_refresh_orders_by_key_without_resume(self):
+ sql, params = _build_query("DB", "PUBLIC", "t", False, None, None, None, order_by_key="ID")
+ assert sql.endswith('ORDER BY "ID" ASC')
+ assert "WHERE" not in sql
+ assert params == ("DB.PUBLIC.t",)
+
+ def test_full_refresh_resume_bounds_scan_before_filters(self):
+ sql, params = _build_query(
+ "DB",
+ "PUBLIC",
+ "t",
+ False,
+ None,
+ None,
+ None,
+ row_filters=[ValidatedRowFilter(column="AGE", operator=">", value=21, category=ColumnTypeCategory.INTEGER)],
+ order_by_key="ID",
+ resume_value=500,
+ )
+ assert 'WHERE "ID" > %s AND "AGE" > %s ORDER BY "ID" ASC' in sql
+ assert params == ("DB.PUBLIC.t", 500, 21)
+
+ def test_incremental_resume_is_inclusive(self):
+ # The checkpoint is a persisted batch's max, and rows sharing it can sit in the next batch —
+ # a strict bound would skip them, so the resume re-reads the boundary and the merge dedups.
+ sql, params = _build_query(
+ "DB",
+ "PUBLIC",
+ "t",
+ True,
+ "created_at",
+ IncrementalFieldType.DateTime,
+ "2025-01-01",
+ resume_value="2025-06-01",
+ )
+ assert 'WHERE "created_at" >= %s' in sql
+ assert params == ("DB.PUBLIC.t", "2025-06-01")
+
+
+class TestBatchCheckpoint:
+ def test_takes_max_of_order_column(self):
+ batch = pa.RecordBatch.from_pydict({"ID": [3, 9, 5], "V": ["a", "b", "c"]})
+ assert _batch_checkpoint(batch, "ID") == SnowflakeResumeState(order_column="ID", last_value=9)
+
+ def test_coerces_timestamps_to_iso_for_json_state(self):
+ # The state crosses Redis as JSON; a raw datetime would fail the dump and lose the checkpoint.
+ batch = pa.RecordBatch.from_pydict({"created_at": [datetime(2026, 1, 2, 3, 4, 5)]})
+ state = _batch_checkpoint(batch, "created_at")
+ assert state is not None
+ assert state.last_value == "2026-01-02T03:04:05"
+
+ def test_missing_or_empty_column_yields_no_checkpoint(self):
+ batch = pa.RecordBatch.from_pydict({"ID": [1]})
+ assert _batch_checkpoint(batch, "OTHER") is None
+ empty = pa.RecordBatch.from_pydict({"ID": pa.array([None], type=pa.int64())})
+ assert _batch_checkpoint(empty, "ID") is None
+
+
class TestBuildQueryRowFilters:
def _filter(self, column, operator, value, category=ColumnTypeCategory.INTEGER):
return ValidatedRowFilter(column=column, operator=operator, value=value, category=category)
@@ -683,6 +748,122 @@ class TestBuildPipeline:
assert stream_param == ("DB.analytics.users",)
+class TestResumableStreaming:
+ def _metadata_cursor(self):
+ metadata_cursor = MagicMock()
+ metadata_cursor.__enter__.return_value = metadata_cursor
+ desc = MagicMock()
+ desc.name = "column_name"
+ metadata_cursor.description = [desc]
+ metadata_cursor.__iter__.return_value = iter([("ID",)])
+ metadata_cursor.fetchone.return_value = (5,)
+ return metadata_cursor
+
+ def _connection(self, metadata_cursor, streaming_cursor):
+ cursors = iter([metadata_cursor, streaming_cursor])
+ mock_connection = MagicMock()
+ mock_connection.__enter__.return_value = mock_connection
+ mock_connection.cursor.side_effect = lambda: next(cursors)
+ return mock_connection
+
+ def _streaming_cursor(self, batches):
+ streaming_cursor = MagicMock()
+ streaming_cursor.__enter__.return_value = streaming_cursor
+ streaming_cursor.fetch_arrow_batches.return_value = iter(batches)
+ return streaming_cursor
+
+ def test_checkpoints_only_batches_the_pipeline_has_persisted(self, impl):
+ batches = [
+ pa.RecordBatch.from_pydict({"ID": [1, 2]}),
+ pa.RecordBatch.from_pydict({"ID": [3, 4]}),
+ pa.RecordBatch.from_pydict({"ID": [5]}),
+ ]
+ streaming_cursor = self._streaming_cursor(batches)
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+ connection = self._connection(self._metadata_cursor(), streaming_cursor)
+ with patch("snowflake.connector.connect", return_value=connection):
+ response = impl.build_pipeline(
+ _make_config(), _make_inputs(verified_primary_keys=["ID"]), resumable_source_manager=manager
+ )
+ iterator = iter(response.items())
+ next(iterator)
+ # The first batch was yielded but not yet persisted, so nothing may be checkpointed.
+ manager.save_state.assert_not_called()
+ next(iterator)
+ assert manager.save_state.call_args.args[0] == SnowflakeResumeState(order_column="ID", last_value=2)
+ next(iterator)
+ assert manager.save_state.call_args.args[0] == SnowflakeResumeState(order_column="ID", last_value=4)
+ with pytest.raises(StopIteration):
+ next(iterator)
+ # The final batch's checkpoint is never saved, so a post-extraction retry re-reads only it.
+ assert manager.save_state.call_count == 2
+
+ def test_resume_bounds_the_scan_and_skips_the_count(self, impl):
+ metadata_cursor = self._metadata_cursor()
+ streaming_cursor = self._streaming_cursor([pa.RecordBatch.from_pydict({"ID": [5]})])
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SnowflakeResumeState(order_column="ID", last_value=4)
+ with patch("snowflake.connector.connect", return_value=self._connection(metadata_cursor, streaming_cursor)):
+ response = impl.build_pipeline(
+ _make_config(), _make_inputs(verified_primary_keys=["ID"]), resumable_source_manager=manager
+ )
+ list(response.items())
+ # No COUNT(*) re-issued on a resumed attempt: the metadata cursor only ran SHOW PRIMARY KEYS.
+ assert response.rows_to_sync is None
+ assert metadata_cursor.execute.call_count == 1
+ query = streaming_cursor.execute.call_args.args[0]
+ params = streaming_cursor.execute.call_args.args[1]
+ assert '"ID" > %s' in query
+ assert 'ORDER BY "ID" ASC' in query
+ assert params == ("DB.PUBLIC.messages", 4)
+
+ def test_checkpoint_for_a_different_column_is_ignored(self, impl):
+ # The schema's key changed between attempts; resuming past another column's value would
+ # skip arbitrary rows, so the stale checkpoint must not bound the scan.
+ metadata_cursor = self._metadata_cursor()
+ streaming_cursor = self._streaming_cursor([])
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SnowflakeResumeState(order_column="OLD_ID", last_value=4)
+ with patch("snowflake.connector.connect", return_value=self._connection(metadata_cursor, streaming_cursor)):
+ response = impl.build_pipeline(
+ _make_config(), _make_inputs(verified_primary_keys=["ID"]), resumable_source_manager=manager
+ )
+ list(response.items())
+ assert response.rows_to_sync == 5
+ assert streaming_cursor.execute.call_args.args[1] == ("DB.PUBLIC.messages",)
+
+ def test_unverified_key_keeps_restart_from_zero(self):
+ # Snowflake declares but does not enforce primary keys. A strict `>` resume on a key with
+ # duplicate boundary values spanning batches would skip rows, so an unverified key must not
+ # order the scan, checkpoint, or bound a resume.
+ impl = SnowflakeImplementation()
+ metadata_cursor = self._metadata_cursor()
+ streaming_cursor = self._streaming_cursor([pa.RecordBatch.from_pydict({"ID": [1, 2]})])
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SnowflakeResumeState(order_column="ID", last_value=4)
+ with patch("snowflake.connector.connect", return_value=self._connection(metadata_cursor, streaming_cursor)):
+ response = impl.build_pipeline(_make_config(), _make_inputs(), resumable_source_manager=manager)
+ list(cast("Iterable[Any]", response.items()))
+ assert response.rows_to_sync == 5
+ query = streaming_cursor.execute.call_args.args[0]
+ assert "ORDER BY" not in query
+ assert streaming_cursor.execute.call_args.args[1] == ("DB.PUBLIC.messages",)
+ manager.save_state.assert_not_called()
+
+
+def test_snowflake_source_is_resumable():
+ # Resumable registration is what routes the import through the resumable retry policy and
+ # hands build_pipeline a state manager — without it every mid-job retry restarts from row zero.
+ source = SnowflakeSource()
+ assert isinstance(source, ResumableSource)
+ manager = source.get_resumable_source_manager(_make_inputs())
+ assert manager._data_class is SnowflakeResumeState
+
+
class TestSnowflakeSourceNonRetryableErrors:
@pytest.fixture
def source(self):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
index 60594fe1fe95..c9d7d9edd6ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_import_data.py
@@ -623,8 +623,15 @@ def test_report_heartbeat_timeout_heartbeat_within_timeout(team):
def test_report_heartbeat_timeout_heartbeat_not_within_timeout(team):
logger = mock.MagicMock()
+ source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="source_id",
+ connection_id="connection_id",
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.SNOWFLAKE,
+ )
activity_inputs = ImportDataActivityInputs(
- team_id=team.pk, schema_id=uuid.uuid4(), source_id=uuid.uuid4(), run_id="run_id"
+ team_id=team.pk, schema_id=uuid.uuid4(), source_id=source.id, run_id="run_id"
)
with time_machine.travel("2024-01-01 12:00:00", tick=False):
@@ -678,5 +685,7 @@ def test_report_heartbeat_timeout_heartbeat_not_within_timeout(team):
"workflow_run_id": mock_info.workflow_run_id,
"workflow_type": mock_info.workflow_type,
"attempt": mock_info.attempt,
+ # The stamp that makes a death diagnosable per connector.
+ "source_type": ExternalDataSourceType.SNOWFLAKE,
},
)