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(data-warehouse): stop redelivered batches corrupting destination tables (#103052)

Tom Owers52a9067be52a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py b/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py
index f5ca0ea67588..52ae65e9c5b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/destinations/contracts.py
@@ -84,6 +84,11 @@ class DestinationWriter(Protocol):
re-claims a batch whose state it could not confirm, so `write_batch` in particular has
to be idempotent per `batch_index` (merge on primary keys, delete-then-insert by batch
index, or a deterministic object key).
+
+ Nothing upstream promises a batch holds one row per primary key. Sources re-yield a page
+ after a crash, and a CDC lane carries every event a row went through, so a writer that
+ merges on the keys has to collapse its merge source itself. `writers.merge_dedup` does
+ that for the SQL destinations.
"""
# The v3 Redis sync lock is released when this writer's child job goes terminal. Only the
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_bigquery.py
new file mode 100644
index 000000000000..90b9fa81d4ae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_bigquery.py
@@ -0,0 +1,185 @@
+"""An in-memory stand-in for `bigquery.Client`, holding rows rather than recording calls.
+
+The writer's guarantees are about what the destination table ends up holding after a batch is
+re-applied or a finished run is replayed, so a test that only counted calls would not see them.
+This fake keeps rows and labels per table and applies the writer's load, copy, delete, merge and
+drop-column statements to them, which lets a test assert the table's contents.
+
+It also refuses a `MERGE` whose source matches one target row twice, the way BigQuery does, so
+a source batch carrying a key more than once fails here too rather than passing quietly.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from typing import Any
+
+import pyarrow.parquet as pq
+from google.api_core.exceptions import NotFound
+from google.cloud import bigquery
+
+Row = dict[str, Any]
+
+_MERGE_TABLES = re.compile(r"MERGE\s+`([^`]+)`\s+T\s+USING\s+`([^`]+)`\s+S\s+ON\s+(.*?)\s+WHEN\s", re.IGNORECASE)
+# Read out of the ON clause alone: the UPDATE SET clause has the same `T.x = S.x` shape, and
+# taking its columns as keys would make every row look unmatched.
+_MERGE_KEYS = re.compile(r"T\.`([^`]+)`\s*=\s*S\.`([^`]+)`")
+_DELETE = re.compile(r"DELETE FROM\s+`([^`]+)`\s+WHERE\s+`([^`]+)`\s*=\s*(-?\d+)", re.IGNORECASE)
+_DROP_COLUMN = re.compile(
+ r"ALTER TABLE\s+`([^`]+)`\s+DROP COLUMN IF EXISTS\s+`([^`]+)`",
+ re.IGNORECASE,
+)
+
+
+class MergeMultiMatchError(RuntimeError):
+ """BigQuery's "UPDATE/MERGE must match at most one source row for each target row"."""
+
+
+class FakeTable:
+ def __init__(self, columns: list[str]) -> None:
+ self.columns = list(columns)
+ self.rows: list[Row] = []
+ self.labels: dict[str, str] = {}
+
+ @property
+ def schema(self) -> list[bigquery.SchemaField]:
+ return [bigquery.SchemaField(name, "STRING") for name in self.columns]
+
+ def add_columns(self, columns: list[str]) -> None:
+ for column in columns:
+ if column not in self.columns:
+ self.columns.append(column)
+ for row in self.rows:
+ row.setdefault(column, None)
+
+
+class _Job:
+ def result(self) -> None:
+ return None
+
+
+class FakeBigQueryClient:
+ project = "proj"
+
+ def __init__(self) -> None:
+ self.tables: dict[str, FakeTable] = {}
+ self.datasets: set[str] = set()
+
+ # --- what the writer calls -----------------------------------------------------------
+
+ def create_dataset(self, name: str, exists_ok: bool = False) -> None:
+ self.datasets.add(name)
+
+ def get_table(self, ref: str | bigquery.Table) -> FakeTable:
+ name = _ref_of(ref)
+ if name not in self.tables:
+ raise NotFound(f"Not found: Table {name}")
+ return self.tables[name]
+
+ def create_table(self, table: bigquery.Table, exists_ok: bool = False) -> FakeTable:
+ name = _ref_of(table)
+ if name in self.tables and not exists_ok:
+ raise ValueError(f"Already Exists: Table {name}")
+ created = FakeTable([field.name for field in table.schema])
+ self.tables.setdefault(name, created)
+ return self.tables[name]
+
+ def update_table(self, table: FakeTable, fields: list[str]) -> FakeTable:
+ return table
+
+ def delete_table(self, ref: str, not_found_ok: bool = False) -> None:
+ name = _ref_of(ref)
+ if name not in self.tables and not not_found_ok:
+ raise NotFound(f"Not found: Table {name}")
+ self.tables.pop(name, None)
+
+ def load_table_from_file(self, buffer, ref: str, job_config: bigquery.LoadJobConfig) -> _Job:
+ data = pq.read_table(buffer)
+ rows = data.to_pylist()
+ columns = list(data.schema.names)
+ name = _ref_of(ref)
+
+ if job_config.write_disposition == bigquery.WriteDisposition.WRITE_TRUNCATE or name not in self.tables:
+ self.tables[name] = FakeTable(columns)
+ else:
+ self.tables[name].add_columns(columns)
+
+ table = self.tables[name]
+ for row in rows:
+ table.rows.append({column: row.get(column) for column in table.columns})
+ return _Job()
+
+ def copy_table(self, source: str, destination: str, job_config: bigquery.CopyJobConfig) -> _Job:
+ origin = self.get_table(source)
+ name = _ref_of(destination)
+ # WRITE_TRUNCATE replaces the destination's data and schema but leaves its own labels
+ # alone, which is what lets the writer read its marker back after publishing.
+ labels = self.tables[name].labels if name in self.tables else {}
+ copied = FakeTable(origin.columns)
+ copied.rows = [dict(row) for row in origin.rows]
+ copied.labels = dict(labels)
+ self.tables[name] = copied
+ return _Job()
+
+ def query(self, statement: str) -> _Job:
+ for handler in (self._delete, self._drop_column, self._merge):
+ if handler(statement):
+ return _Job()
+ raise AssertionError(f"FakeBigQueryClient cannot run: {statement}")
+
+ # --- statement handling ---------------------------------------------------------------
+
+ def _delete(self, statement: str) -> bool:
+ match = _DELETE.search(statement)
+ if not match:
+ return False
+ table, column, value = match.group(1), match.group(2), int(match.group(3))
+ target = self.get_table(table)
+ target.rows = [row for row in target.rows if row.get(column) != value]
+ return True
+
+ def _drop_column(self, statement: str) -> bool:
+ match = _DROP_COLUMN.search(statement)
+ if not match:
+ return False
+ table, column = match.group(1), match.group(2)
+ target = self.get_table(table)
+ if column in target.columns:
+ target.columns.remove(column)
+ for row in target.rows:
+ row.pop(column, None)
+ return True
+
+ def _merge(self, statement: str) -> bool:
+ tables = _MERGE_TABLES.search(statement)
+ if not tables:
+ return False
+
+ target = self.get_table(tables.group(1))
+ source = self.get_table(tables.group(2))
+ keys = [target_key for target_key, _ in _MERGE_KEYS.findall(tables.group(3))]
+ target.add_columns(source.columns)
+
+ incoming_per_key = Counter(_key_of(row, keys) for row in source.rows)
+ for row in target.rows:
+ if incoming_per_key[_key_of(row, keys)] > 1:
+ raise MergeMultiMatchError("UPDATE/MERGE must match at most one source row for each target row")
+
+ for incoming in source.rows:
+ matched = [row for row in target.rows if _key_of(row, keys) == _key_of(incoming, keys)]
+ if matched:
+ matched[0].update(incoming)
+ else:
+ target.rows.append({column: incoming.get(column) for column in target.columns})
+ return True
+
+
+def _key_of(row: Row, keys: list[str]) -> tuple:
+ return tuple(row.get(key) for key in keys)
+
+
+def _ref_of(ref: str | bigquery.Table) -> str:
+ if isinstance(ref, bigquery.Table):
+ return f"{ref.project}.{ref.dataset_id}.{ref.table_id}"
+ return ref
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_databricks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_databricks.py
new file mode 100644
index 000000000000..666b98b1ddaf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_databricks.py
@@ -0,0 +1,121 @@
+"""An in-memory stand-in for `DatabricksClient`, modelling Unity Catalog's name handling.
+
+Unity Catalog lowercases the schema and table names it stores, and answers its metadata API
+case-insensitively. This fake does both: it keys tables by their lowercased name, so a metadata
+lookup finds a table whatever case the caller asked in, while a literal comparison written into
+an `information_schema` query only matches the lowercased name that is actually stored.
+
+That difference is the point. A writer that reads `information_schema` with the configured
+name unlowered finds no row for a table it created under a name carrying any uppercase, and
+then treats its own table as somebody else's.
+"""
+
+from __future__ import annotations
+
+import io
+import re
+from contextlib import asynccontextmanager
+from typing import Any
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+
+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import DatabricksField
+
+_INFORMATION_SCHEMA_TABLES = re.compile(r"information_schema\.tables", re.IGNORECASE)
+_TABLE_NAME_PREDICATE = re.compile(r"table_name\)?\s*=\s*'([^']*)'", re.IGNORECASE)
+_COMMENT_ON = re.compile(r"COMMENT ON TABLE\s+(\S+)\s+IS\s+'(.*)'\s*$", re.IGNORECASE | re.DOTALL)
+_REMOVE = re.compile(r"REMOVE\s+'([^']+)'", re.IGNORECASE)
+_QUALIFIED_TABLE = re.compile(r"`[^`]+`\.`[^`]+`\.`([^`]+)`")
+
+
+class FakeDatabricksTable:
+ def __init__(self, columns: list[str]) -> None:
+ self.columns = list(columns)
+ self.rows: list[dict[str, Any]] = []
+ self.comment: str | None = None
+
+
+class FakeDatabricksClient:
+ def __init__(self) -> None:
+ self.tables: dict[str, FakeDatabricksTable] = {}
+ self.volumes: set[str] = set()
+ self.volume_files: dict[str, bytes] = {}
+ self.logger = _NullLogger()
+
+ @asynccontextmanager
+ async def connect(self):
+ yield self
+
+ # --- metadata -------------------------------------------------------------------------
+
+ async def acreate_volume(self, volume: str) -> None:
+ self.volumes.add(volume)
+
+ async def aget_table_columns(self, table_name: str, timeout: float | None = None) -> list[str]:
+ # Unity Catalog's metadata API resolves a name regardless of the case it is asked in.
+ table = self.tables.get(table_name.lower())
+ return list(table.columns) if table else []
+
+ async def acreate_table(self, table_name: str, fields: list[DatabricksField]) -> None:
+ self.tables.setdefault(table_name.lower(), FakeDatabricksTable([name for name, _ in fields]))
+
+ async def adelete_table(self, table_name: str) -> None:
+ self.tables.pop(table_name.lower(), None)
+
+ # --- data -----------------------------------------------------------------------------
+
+ async def aput_file_stream_to_volume(self, file: io.BytesIO, volume_path: str, file_name: str) -> None:
+ self.volume_files[f"{volume_path}/{file_name}"] = file.getvalue()
+
+ async def acopy_into_table_from_volume(
+ self, table_name: str, path: str, fields: list[DatabricksField], with_schema_evolution: bool = False
+ ) -> None:
+ table = self.tables[table_name.lower()]
+ data = pq.read_table(pa.BufferReader(self.volume_files[path]))
+ for column in data.schema.names:
+ if column not in table.columns:
+ table.columns.append(column)
+ table.rows.extend(data.to_pylist())
+
+ # --- statements -------------------------------------------------------------------------
+
+ async def execute_query(
+ self, query: str, fetch_results: bool = True, timeout: float | None = None
+ ) -> list[tuple] | None:
+ if _INFORMATION_SCHEMA_TABLES.search(query):
+ return self._select_comment(query)
+
+ comment = _COMMENT_ON.search(query.strip())
+ if comment:
+ self.tables[_table_of(comment.group(1)).lower()].comment = comment.group(2).replace("''", "'")
+ return None
+
+ remove = _REMOVE.search(query)
+ if remove:
+ self.volume_files.pop(remove.group(1), None)
+ return None
+
+ return None
+
+ def _select_comment(self, query: str) -> list[tuple]:
+ predicate = _TABLE_NAME_PREDICATE.search(query)
+ assert predicate is not None, f"FakeDatabricksClient cannot run: {query}"
+ # Compared literally against the stored name, which is always lowercase: an unlowered
+ # predicate finds nothing, exactly as it would against Unity Catalog.
+ table = self.tables.get(predicate.group(1))
+ return [] if table is None else [(table.comment,)]
+
+
+def _table_of(qualified: str) -> str:
+ match = _QUALIFIED_TABLE.search(qualified)
+ assert match is not None, f"not a qualified Databricks table: {qualified}"
+ return match.group(1)
+
+
+class _NullLogger:
+ def warning(self, *args: Any, **kwargs: Any) -> None:
+ return None
+
+ def info(self, *args: Any, **kwargs: Any) -> None:
+ return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_snowflake.py
new file mode 100644
index 000000000000..5efc5d631fc1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/fake_snowflake.py
@@ -0,0 +1,219 @@
+"""An in-memory stand-in for `SnowflakeClient`, holding rows rather than recording calls.
+
+The guarantee under test is what the destination table ends up holding after a finished run's
+final batch is delivered a second time, so the fake has to carry rows through the whole shape a
+full refresh takes: load into a per-run staging table, drop the bookkeeping column, drop the
+live table, rename the staging table over it, and comment the result.
+
+Only the statements this writer sends are understood. Anything else is an assertion failure
+rather than a silent no-op, so a statement the fake does not model cannot pass unnoticed.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from contextlib import asynccontextmanager
+from typing import Any
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+
+from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import NamedBytesIO, SnowflakeTable
+
+_CREATE_SCHEMA = re.compile(r'^CREATE SCHEMA IF NOT EXISTS "([^"]+)"', re.IGNORECASE)
+_CREATE_TABLE = re.compile(r'^CREATE TABLE IF NOT EXISTS "[^"]+"\."([^"]+)"\s*\((.*)\)$', re.IGNORECASE | re.DOTALL)
+_ADD_COLUMN = re.compile(r'^ALTER TABLE "[^"]+"\."([^"]+)" ADD COLUMN IF NOT EXISTS "([^"]+)"', re.IGNORECASE)
+_DROP_COLUMN = re.compile(r'^ALTER TABLE "[^"]+"\."([^"]+)" DROP COLUMN IF EXISTS "([^"]+)"', re.IGNORECASE | re.DOTALL)
+_SET_COMMENT = re.compile(r'^ALTER TABLE "[^"]+"\."([^"]+)" SET COMMENT = \'(.*)\'$', re.IGNORECASE | re.DOTALL)
+_RENAME = re.compile(r'^ALTER TABLE "[^"]+"\."([^"]+)" RENAME TO "[^"]+"\."([^"]+)"$', re.IGNORECASE)
+_DROP_TABLE = re.compile(r'^DROP TABLE IF EXISTS "[^"]+"\."([^"]+)"$', re.IGNORECASE)
+_DELETE = re.compile(r'^DELETE FROM "[^"]+"\."([^"]+)" WHERE "([^"]+)" = (-?\d+)$', re.IGNORECASE | re.DOTALL)
+_SELECT_TABLES = re.compile(r"FROM information_schema\.tables", re.IGNORECASE)
+_SELECT_COLUMNS = re.compile(r"FROM information_schema\.columns", re.IGNORECASE)
+_COLUMN_NAME = re.compile(r'"([^"]+)"\s')
+_MERGE = re.compile(
+ r'^MERGE INTO "[^"]+"\."([^"]+)" AS target USING "[^"]+"\."([^"]+)" AS source ON (.*?)\s+WHEN\s',
+ re.IGNORECASE | re.DOTALL,
+)
+# Read out of the ON clause alone: the UPDATE SET clause has the same `target.x = source.x`
+# shape, and taking its columns as keys would make every row look unmatched.
+_MERGE_KEYS = re.compile(r'target\."([^"]+)" = source\."([^"]+)"')
+
+
+class MergeMultiMatchError(RuntimeError):
+ """Snowflake's "Duplicate row detected during DML action"."""
+
+
+class FakeSnowflakeTable:
+ def __init__(self, columns: list[str]) -> None:
+ self.columns = list(columns)
+ self.rows: list[dict[str, Any]] = []
+ self.comment: str | None = None
+
+
+class FakeSnowflakeClient:
+ def __init__(self) -> None:
+ self.tables: dict[str, FakeSnowflakeTable] = {}
+ self.schemas: set[str] = set()
+ # Keyed the way Snowflake keys an internal stage: per table, then per file path.
+ self.stage_files: dict[tuple[str, str], bytes] = {}
+
+ @asynccontextmanager
+ async def connect(self):
+ yield self
+
+ # --- the table stage --------------------------------------------------------------------
+
+ async def remove_internal_stage_files(self, table: SnowflakeTable) -> None:
+ for key in [k for k in self.stage_files if k[0] == table.name and k[1].startswith(table.stage_prefix)]:
+ del self.stage_files[key]
+
+ async def put_file_to_snowflake_table_stage(self, file: NamedBytesIO, table: SnowflakeTable) -> None:
+ key = (table.name, f"{table.stage_prefix}/{file.name}")
+ assert key not in self.stage_files, f"PUT does not overwrite, and {key} is already staged"
+ self.stage_files[key] = file.getvalue()
+
+ async def copy_loaded_files_to_snowflake_table(self, table: SnowflakeTable, timeout: float) -> None:
+ target = self.tables[table.name]
+ for (name, path), payload in sorted(self.stage_files.items()):
+ if name != table.name or not path.startswith(table.stage_prefix):
+ continue
+ data = pq.read_table(pa.BufferReader(payload))
+ for column in data.schema.names:
+ if column not in target.columns:
+ target.columns.append(column)
+ target.rows.extend(data.to_pylist())
+
+ # --- statements ---------------------------------------------------------------------------
+
+ async def execute_async_query(
+ self,
+ query: str,
+ parameters: dict[str, Any] | None = None,
+ fetch_results: bool = False,
+ timeout: float | None = None,
+ ) -> tuple[list[tuple], None] | None:
+ statement = query.strip()
+
+ if _SELECT_TABLES.search(statement):
+ return self._select_from_tables(statement, parameters or {})
+ if _SELECT_COLUMNS.search(statement):
+ table = self.tables.get((parameters or {}).get("table", ""))
+ return ([(column,) for column in table.columns] if table else [], None)
+
+ for handler in (
+ self._create_schema,
+ self._create_table,
+ self._add_column,
+ self._drop_column,
+ self._set_comment,
+ self._rename,
+ self._drop_table,
+ self._delete,
+ self._merge,
+ ):
+ if handler(statement):
+ return None
+
+ raise AssertionError(f"FakeSnowflakeClient cannot run: {statement}")
+
+ def _select_from_tables(self, statement: str, parameters: dict[str, Any]) -> tuple[list[tuple], None]:
+ table = self.tables.get(parameters.get("table", ""))
+ if table is None:
+ return ([], None)
+ return ([(table.comment,)] if "comment" in statement.lower() else [(1,)], None)
+
+ def _create_schema(self, statement: str) -> bool:
+ match = _CREATE_SCHEMA.search(statement)
+ if not match:
+ return False
+ self.schemas.add(match.group(1))
+ return True
+
+ def _create_table(self, statement: str) -> bool:
+ match = _CREATE_TABLE.search(statement)
+ if not match:
+ return False
+ columns = _COLUMN_NAME.findall(match.group(2))
+ self.tables.setdefault(match.group(1), FakeSnowflakeTable(columns))
+ return True
+
+ def _add_column(self, statement: str) -> bool:
+ match = _ADD_COLUMN.search(statement)
+ if not match:
+ return False
+ table = self.tables[match.group(1)]
+ if match.group(2) not in table.columns:
+ table.columns.append(match.group(2))
+ return True
+
+ def _drop_column(self, statement: str) -> bool:
+ match = _DROP_COLUMN.search(statement)
+ if not match:
+ return False
+ table = self.tables[match.group(1)]
+ if match.group(2) in table.columns:
+ table.columns.remove(match.group(2))
+ for row in table.rows:
+ row.pop(match.group(2), None)
+ return True
+
+ def _set_comment(self, statement: str) -> bool:
+ match = _SET_COMMENT.search(statement)
+ if not match:
+ return False
+ self.tables[match.group(1)].comment = match.group(2).replace("''", "'")
+ return True
+
+ def _rename(self, statement: str) -> bool:
+ match = _RENAME.search(statement)
+ if not match:
+ return False
+ self.tables[match.group(2)] = self.tables.pop(match.group(1))
+ return True
+
+ def _drop_table(self, statement: str) -> bool:
+ match = _DROP_TABLE.search(statement)
+ if not match:
+ return False
+ self.tables.pop(match.group(1), None)
+ return True
+
+ def _delete(self, statement: str) -> bool:
+ match = _DELETE.search(statement)
+ if not match:
+ return False
+ table = self.tables[match.group(1)]
+ column, value = match.group(2), int(match.group(3))
+ table.rows = [row for row in table.rows if row.get(column) != value]
+ return True
+
+ def _merge(self, statement: str) -> bool:
+ match = _MERGE.search(statement)
+ if not match:
+ return False
+
+ target = self.tables[match.group(1)]
+ source = self.tables[match.group(2)]
+ keys = [key for key, _ in _MERGE_KEYS.findall(match.group(3))]
+
+ incoming_per_key = Counter(_key_of(row, keys) for row in source.rows)
+ for row in target.rows:
+ if incoming_per_key[_key_of(row, keys)] > 1:
+ raise MergeMultiMatchError("Duplicate row detected during DML action")
+
+ for column in source.columns:
+ if column not in target.columns:
+ target.columns.append(column)
+ for incoming in source.rows:
+ matched = [row for row in target.rows if _key_of(row, keys) == _key_of(incoming, keys)]
+ if matched:
+ matched[0].update(incoming)
+ else:
+ target.rows.append({column: incoming.get(column) for column in target.columns})
+ return True
+
+
+def _key_of(row: dict[str, Any], keys: list[str]) -> tuple:
+ return tuple(row.get(key) for key in keys)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
index d6e55376add2..073a72cd2a10 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_bigquery_writer.py
@@ -1,28 +1,49 @@
+import io
+from collections.abc import AsyncIterator
+
import pytest
from unittest.mock import MagicMock
+import pyarrow as pa
+import pyarrow.parquet as pq
from google.api_core.exceptions import NotFound
+from google.cloud import bigquery
-from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import DestinationRunContext
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_bigquery import (
+ FakeBigQueryClient,
+ MergeMultiMatchError,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.bigquery import (
_OWNERSHIP_LABEL_KEY,
+ BigQueryDestinationConfigurationError,
BigQueryDestinationWriter,
UnrelatedTableExistsError,
+ staging_table_name,
)
-def _ctx(schema_id: str = "schema") -> DestinationRunContext:
+def _ctx(
+ schema_id: str = "schema",
+ sync_type: str = "full_refresh",
+ primary_keys: tuple[str, ...] = (),
+ run_uuid: str = "run-a1",
+) -> DestinationRunContext:
return DestinationRunContext(
team_id=1,
schema_id=schema_id,
source_id="source",
job_id="job",
- run_uuid="run-a1",
+ run_uuid=run_uuid,
destination_id="destination",
destination_type="BigQuery",
destination_name="test bigquery",
table_name="charges",
- sync_type="full_refresh",
+ sync_type=sync_type,
+ primary_keys=primary_keys,
config={"project": "proj", "dataset": "dataset"},
)
@@ -33,6 +54,54 @@ def _table(labels: dict | None = None) -> MagicMock:
return table
+class LocalBigQueryWriter(BigQueryDestinationWriter):
+ """Points the writer at an in-memory BigQuery instead of a customer's project."""
+
+ def __init__(self, ctx: DestinationRunContext, client: FakeBigQueryClient) -> None:
+ super().__init__(ctx)
+ self._fake = client
+
+ def _get_client(self) -> bigquery.Client:
+ return self._fake # type: ignore[return-value] # ty: ignore[invalid-return-type]
+
+
+async def _batches(*record_batches: pa.RecordBatch) -> AsyncIterator[pa.RecordBatch]:
+ for batch in record_batches:
+ yield batch
+
+
+def _rows(ids: list[int], names: list[str]) -> pa.RecordBatch:
+ return pa.RecordBatch.from_pydict({"id": ids, "name": names})
+
+
+def _parquet(batch: pa.RecordBatch) -> io.BytesIO:
+ buffer = io.BytesIO()
+ pq.write_table(pa.Table.from_batches([batch]), buffer)
+ buffer.seek(0)
+ return buffer
+
+
+def _read(client: FakeBigQueryClient, table: str = "charges") -> list[tuple]:
+ rows = client.get_table(f"proj.dataset.{table}").rows
+ return sorted((row["id"], row["name"]) for row in rows)
+
+
+async def _deliver(
+ writer: BigQueryDestinationWriter,
+ ctx: DestinationRunContext,
+ batch: pa.RecordBatch,
+ batch_index: int,
+ *,
+ is_final: bool = False,
+) -> None:
+ await writer.prepare_run(ctx)
+ await writer.write_batch(
+ _batches(batch), DestinationBatchContext(run=ctx, batch_index=batch_index, is_final_batch=is_final)
+ )
+ if is_final:
+ await writer.finalize_run(ctx)
+
+
class TestSchemaLabel:
def test_the_same_schema_id_always_hashes_to_the_same_label(self) -> None:
writer = BigQueryDestinationWriter(_ctx("schema-a"))
@@ -99,3 +168,152 @@ class TestMarkOwned:
(updated_table, fields), _kwargs = client.update_table.call_args
assert fields == ["labels"]
assert updated_table.labels == {"team": "data", _OWNERSHIP_LABEL_KEY: writer._schema_label()}
+
+
+class TestConfigValidation:
+ def test_a_destination_with_no_dataset_is_rejected_before_a_batch_is_read(self) -> None:
+ ctx = DestinationRunContext(
+ team_id=1,
+ schema_id="schema",
+ source_id="source",
+ job_id="job",
+ run_uuid="run-a1",
+ destination_id="destination",
+ destination_type="BigQuery",
+ destination_name="test bigquery",
+ table_name="charges",
+ sync_type="full_refresh",
+ config={"project": "proj"},
+ )
+
+ with pytest.raises(BigQueryDestinationConfigurationError):
+ BigQueryDestinationWriter(ctx)
+
+
+class TestFullRefresh:
+ async def test_the_live_table_only_changes_once_the_run_completes(self) -> None:
+ client = FakeBigQueryClient()
+ ctx = _ctx()
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["a"]), 0)
+ with pytest.raises(NotFound):
+ client.get_table("proj.dataset.charges")
+
+ await _deliver(writer, ctx, _rows([2], ["b"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b")]
+
+ async def test_reapplying_a_batch_does_not_duplicate_its_rows(self) -> None:
+ # Without the batch-index stamp only batch 0 truncated, so re-applying any later batch
+ # appended a second copy of its rows to the staging table.
+ client = FakeBigQueryClient()
+ ctx = _ctx()
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["a"]), 0)
+ await _deliver(writer, ctx, _rows([2], ["b"]), 1)
+ await _deliver(writer, ctx, _rows([2], ["b"]), 1)
+ await _deliver(writer, ctx, _rows([3], ["c"]), 2, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b"), (3, "c")]
+
+ async def test_replaying_the_published_final_batch_keeps_the_earlier_batches(self) -> None:
+ # Without the publish stamp this replays as "rebuild a staging table from one batch,
+ # then copy it over the finished table", leaving only the final batch's rows.
+ client = FakeBigQueryClient()
+ ctx = _ctx()
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1, 2], ["a", "b"]), 0)
+ await _deliver(writer, ctx, _rows([3], ["c"]), 1, is_final=True)
+ assert _read(client) == [(1, "a"), (2, "b"), (3, "c")]
+
+ await _deliver(writer, ctx, _rows([3], ["c"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b"), (3, "c")]
+
+ async def test_the_published_table_does_not_carry_the_batch_index_column(self) -> None:
+ # The column is the staging table's own bookkeeping, and a synced table is supposed to
+ # mirror its source.
+ client = FakeBigQueryClient()
+ ctx = _ctx()
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["a"]), 0, is_final=True)
+
+ assert client.get_table("proj.dataset.charges").columns == ["id", "name"]
+
+ async def test_a_run_that_never_finishes_leaves_the_previous_data_in_place(self) -> None:
+ client = FakeBigQueryClient()
+ first = _ctx(run_uuid="run-a1")
+ await _deliver(LocalBigQueryWriter(first, client), first, _rows([1], ["old"]), 0, is_final=True)
+
+ second = _ctx(run_uuid="run-b2")
+ await _deliver(LocalBigQueryWriter(second, client), second, _rows([2], ["new"]), 0)
+ # `abort_destinations` builds a fresh writer, so cleanup has to run on one that has
+ # never connected.
+ await LocalBigQueryWriter(second, client).abort_run(second)
+
+ assert _read(client) == [(1, "old")]
+ with pytest.raises(NotFound):
+ client.get_table(f"proj.dataset.{staging_table_name(second)}")
+
+
+class TestIncremental:
+ async def test_the_first_run_of_an_incremental_schema_creates_its_merge_target(self) -> None:
+ # A schema is on sync_type "incremental" from its very first run, and nothing else
+ # creates the table the MERGE needs, so without this the first sync could never land.
+ client = FakeBigQueryClient()
+ ctx = _ctx(sync_type="incremental", primary_keys=("id",))
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1, 2], ["a", "b"]), 0, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b")]
+
+ async def test_rows_are_merged_on_the_primary_key(self) -> None:
+ client = FakeBigQueryClient()
+ ctx = _ctx(sync_type="incremental", primary_keys=("id",))
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1, 2], ["first", "second"]), 0)
+ await _deliver(writer, ctx, _rows([1], ["updated"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "updated"), (2, "second")]
+
+ async def test_a_batch_carrying_one_key_twice_keeps_the_last_row(self) -> None:
+ # Nothing upstream promises a staged batch holds each key once, and BigQuery rejects a
+ # MERGE whose source matches a target row more than once — on every retry.
+ client = FakeBigQueryClient()
+ ctx = _ctx(sync_type="incremental", primary_keys=("id",))
+ writer = LocalBigQueryWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["first"]), 0)
+ await _deliver(writer, ctx, _rows([1, 1], ["stale", "latest"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "latest")]
+
+ async def test_the_fake_rejects_a_duplicated_key_the_way_bigquery_does(self) -> None:
+ # Guards the test above: if the fake accepted a multi-matching MERGE, that test would
+ # pass with or without the dedup.
+ client = FakeBigQueryClient()
+ client.load_table_from_file(
+ _parquet(_rows([1], ["first"])),
+ "proj.dataset.charges",
+ bigquery.LoadJobConfig(write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE),
+ )
+ client.load_table_from_file(
+ _parquet(_rows([1, 1], ["stale", "latest"])),
+ "proj.dataset.source",
+ bigquery.LoadJobConfig(write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE),
+ )
+
+ with pytest.raises(MergeMultiMatchError):
+ client.query(
+ "MERGE `proj.dataset.charges` T USING `proj.dataset.source` S ON T.`id` = S.`id` "
+ "WHEN MATCHED THEN UPDATE SET T.`name` = S.`name` "
+ "WHEN NOT MATCHED THEN INSERT (`id`, `name`) VALUES (S.`id`, S.`name`)"
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py
index d4af848e6550..94fcc94031de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_builtin_writers.py
@@ -17,12 +17,19 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
register_builtin_destination_writers,
)
-# Azure Blob and S3 validate their config eagerly at construction time (a missing container or
-# bucket would otherwise write to a nonsense name hundreds of MiB into a batch), so those two
-# need enough config to pass that check. Every other builtin writer accepts an empty config here.
+# Some writers validate their config eagerly at construction time, because a name they cannot
+# build would otherwise surface hundreds of MiB into a batch, or reach a shared client that
+# interpolates it into a statement unescaped. Those need enough config to pass that check.
+# Every other builtin writer accepts an empty config here.
_MINIMAL_CONFIG: dict[str, dict] = {
str(ExternalDataDestination.Type.AZURE_BLOB): {"container_name": "container"},
str(ExternalDataDestination.Type.S3): {"bucket": "bucket", "region": "us-east-1"},
+ str(ExternalDataDestination.Type.BIGQUERY): {"project": "project", "dataset": "dataset"},
+ str(ExternalDataDestination.Type.SNOWFLAKE): {
+ "database": "database",
+ "schema": "schema",
+ "warehouse": "warehouse",
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py
new file mode 100644
index 000000000000..3f204f406099
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_databricks_writer.py
@@ -0,0 +1,112 @@
+from collections.abc import AsyncIterator
+
+import pytest
+
+import pyarrow as pa
+from parameterized import parameterized
+
+from products.batch_exports.backend.temporal.destinations.databricks_batch_export import DatabricksClient
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_databricks import (
+ FakeDatabricksClient,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.databricks import (
+ DatabricksDestinationWriter,
+ UnrelatedTableExistsError,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+class LocalDatabricksWriter(DatabricksDestinationWriter):
+ """Points the writer at an in-memory Databricks instead of a customer's workspace."""
+
+ def __init__(self, ctx: DestinationRunContext, client: FakeDatabricksClient) -> None:
+ super().__init__(ctx)
+ self._fake = client
+
+ async def _make_client(self) -> DatabricksClient:
+ return self._fake # type: ignore[return-value] # ty: ignore[invalid-return-type]
+
+
+async def _batches(*record_batches: pa.RecordBatch) -> AsyncIterator[pa.RecordBatch]:
+ for batch in record_batches:
+ yield batch
+
+
+def _rows(ids: list[int], names: list[str]) -> pa.RecordBatch:
+ return pa.RecordBatch.from_pydict({"id": ids, "name": names})
+
+
+def _ctx(table_name: str, run_uuid: str, schema_id: str = "schema") -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id=schema_id,
+ source_id="source",
+ job_id="job",
+ run_uuid=run_uuid,
+ destination_id="destination",
+ destination_type="Databricks",
+ destination_name="test databricks",
+ table_name=table_name,
+ sync_type="incremental",
+ config={"catalog": "main", "schema": "Default", "http_path": "/sql/1.0", "volume": "vol"},
+ )
+
+
+def _read(client: FakeDatabricksClient, table: str) -> list[tuple]:
+ return sorted((row["id"], row["name"]) for row in client.tables[table.lower()].rows)
+
+
+class TestUnityCatalogNameCase:
+ """Unity Catalog lowercases the names it stores, so a writer that looks its own table up
+ case-sensitively stops recognizing it as soon as the name carries any uppercase. The run
+ that created the table then reports it as somebody else's, on this run and on every later
+ one, because nothing about the name changes.
+ """
+
+ @parameterized.expand(
+ [
+ ("all lowercase", "charges"),
+ ("mixed case", "Stripe_Charges"),
+ ("all uppercase", "CHARGES"),
+ ]
+ )
+ async def test_a_later_run_writes_into_the_table_an_earlier_run_created(self, _name: str, table_name: str) -> None:
+ client = FakeDatabricksClient()
+ first = _ctx(table_name, "run-a1")
+ second = _ctx(table_name, "run-b2")
+
+ await LocalDatabricksWriter(first, client).write_batch(
+ _batches(_rows([1], ["a"])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+ await LocalDatabricksWriter(second, client).write_batch(
+ _batches(_rows([2], ["b"])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+
+ assert _read(client, table_name) == [(1, "a"), (2, "b")]
+
+ async def test_a_table_a_different_schema_created_is_still_refused(self) -> None:
+ # The case-insensitive lookup must not turn into "any table is ours": ownership is
+ # scoped to the schema whose sync created the table.
+ client = FakeDatabricksClient()
+ first = _ctx("Charges", "run-a1", schema_id="schema-a")
+ second = _ctx("Charges", "run-b2", schema_id="schema-b")
+
+ await LocalDatabricksWriter(first, client).write_batch(
+ _batches(_rows([1], ["a"])),
+ DestinationBatchContext(run=first, batch_index=0, is_final_batch=True),
+ )
+
+ with pytest.raises(UnrelatedTableExistsError):
+ await LocalDatabricksWriter(second, client).write_batch(
+ _batches(_rows([2], ["b"])),
+ DestinationBatchContext(run=second, batch_index=0, is_final_batch=True),
+ )
+
+ assert _read(client, "Charges") == [(1, "a")]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py
index 891ec56a8421..bb811f1f1281 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_postgres_writer.py
@@ -17,11 +17,13 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.postgres import (
PostgresDestinationWriter,
UnrelatedTableExistsError,
- _owned_marker,
_scoped_identifier,
merge_stage_name,
staging_table_name,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.run_markers import (
+ owned_marker,
+)
pytestmark = pytest.mark.asyncio
@@ -434,6 +436,23 @@ class TestIncremental:
finally:
_drop(dsn, table_name)
+ async def test_a_batch_carrying_one_key_twice_keeps_the_last_row(self, dsn, table_name) -> None:
+ # Nothing upstream promises a staged batch holds each key once: sources re-yield a page
+ # after a crash and CDC carries several events for one row. Postgres answers
+ # `ON CONFLICT DO UPDATE` over two rows of one key with "cannot affect row a second
+ # time", and it answers the same way on every retry.
+ ctx = _ctx(table_name, "incremental", primary_keys=("id",))
+ writer = LocalPostgresWriter(ctx, dsn)
+ try:
+ await writer.write_batch(
+ _batches(_rows(["stale", "latest"], [1, 1])),
+ DestinationBatchContext(run=ctx, batch_index=0, is_final_batch=True),
+ )
+
+ assert _read(dsn, table_name) == [(1, "latest")]
+ finally:
+ _drop(dsn, table_name)
+
async def test_a_new_source_column_is_added_rather_than_dropped(self, dsn, table_name) -> None:
ctx = _ctx(table_name, "incremental", primary_keys=("id",))
writer = LocalPostgresWriter(ctx, dsn)
@@ -705,7 +724,7 @@ class TestMergeConstraints:
# this table, so the writer has to add one before it can merge into it.
with psycopg.connect(dsn, autocommit=True) as conn:
conn.execute(f'CREATE TABLE "{table_name}" (id BIGINT, name TEXT)')
- conn.execute(f"COMMENT ON TABLE \"{table_name}\" IS '{_owned_marker('schema')}'")
+ conn.execute(f"COMMENT ON TABLE \"{table_name}\" IS '{owned_marker('schema')}'")
ctx = _ctx(table_name, "incremental", primary_keys=("id",))
writer = LocalPostgresWriter(ctx, dsn)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py
new file mode 100644
index 000000000000..82c58099de1f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/tests/test_snowflake_writer.py
@@ -0,0 +1,251 @@
+from collections.abc import AsyncIterator
+
+import pytest
+
+import pyarrow as pa
+from parameterized import parameterized
+
+from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import SnowflakeClient
+from products.warehouse_sources.backend.temporal.data_imports.destinations.contracts import (
+ DestinationBatchContext,
+ DestinationRunContext,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.tests.fake_snowflake import (
+ FakeSnowflakeClient,
+ FakeSnowflakeTable,
+ MergeMultiMatchError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.snowflake import (
+ SnowflakeDestinationWriter,
+ UnrelatedTableExistsError,
+ merge_stage_name,
+ stage_prefix,
+ staging_table_name,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+class LocalSnowflakeWriter(SnowflakeDestinationWriter):
+ """Points the writer at an in-memory Snowflake instead of a customer's account."""
+
+ def __init__(self, ctx: DestinationRunContext, client: FakeSnowflakeClient) -> None:
+ super().__init__(ctx)
+ self._fake = client
+
+ async def _make_client(self) -> SnowflakeClient:
+ return self._fake # type: ignore[return-value] # ty: ignore[invalid-return-type]
+
+
+async def _batches(*record_batches: pa.RecordBatch) -> AsyncIterator[pa.RecordBatch]:
+ for batch in record_batches:
+ yield batch
+
+
+def _rows(ids: list[int], names: list[str]) -> pa.RecordBatch:
+ return pa.RecordBatch.from_pydict({"id": ids, "name": names})
+
+
+def _ctx(
+ sync_type: str = "full_refresh",
+ primary_keys: tuple[str, ...] = (),
+ run_uuid: str = "run-a1",
+ schema_id: str = "schema",
+ config: dict | None = None,
+) -> DestinationRunContext:
+ return DestinationRunContext(
+ team_id=1,
+ schema_id=schema_id,
+ source_id="source",
+ job_id="job",
+ run_uuid=run_uuid,
+ destination_id="destination",
+ destination_type="Snowflake",
+ destination_name="test snowflake",
+ table_name="charges",
+ sync_type=sync_type,
+ primary_keys=primary_keys,
+ config=config if config is not None else {"database": "DB", "schema": "PUBLIC", "warehouse": "WH"},
+ )
+
+
+def _read(client: FakeSnowflakeClient, table: str = "charges") -> list[tuple]:
+ return sorted((row["id"], row["name"]) for row in client.tables[table].rows)
+
+
+async def _deliver(
+ writer: SnowflakeDestinationWriter,
+ ctx: DestinationRunContext,
+ batch: pa.RecordBatch,
+ batch_index: int,
+ *,
+ is_final: bool = False,
+) -> None:
+ await writer.write_batch(
+ _batches(batch), DestinationBatchContext(run=ctx, batch_index=batch_index, is_final_batch=is_final)
+ )
+ if is_final:
+ await writer.finalize_run(ctx)
+
+
+class TestFullRefresh:
+ async def test_the_live_table_only_changes_once_the_run_completes(self) -> None:
+ client = FakeSnowflakeClient()
+ ctx = _ctx()
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["a"]), 0)
+ assert "charges" not in client.tables
+
+ await _deliver(writer, ctx, _rows([2], ["b"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b")]
+
+ async def test_reapplying_a_batch_does_not_duplicate_its_rows(self) -> None:
+ client = FakeSnowflakeClient()
+ ctx = _ctx()
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ batch = _rows([1, 2], ["a", "b"])
+ await _deliver(writer, ctx, batch, 0)
+ # A crash after the write but before the state was recorded re-claims this batch.
+ await _deliver(writer, ctx, batch, 0, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b")]
+
+ async def test_replaying_the_published_final_batch_keeps_the_earlier_batches(self) -> None:
+ # Without the publish stamp this replays as "rebuild a staging table from one batch,
+ # then swap it over the finished table", leaving only the final batch's rows. Reachable
+ # whenever the write marker is missing: Redis down, or a crash between the swap and the
+ # marker.
+ client = FakeSnowflakeClient()
+ ctx = _ctx()
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1, 2], ["a", "b"]), 0)
+ await _deliver(writer, ctx, _rows([3], ["c"]), 1, is_final=True)
+ assert _read(client) == [(1, "a"), (2, "b"), (3, "c")]
+
+ await _deliver(writer, ctx, _rows([3], ["c"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "a"), (2, "b"), (3, "c")]
+
+ async def test_the_published_table_does_not_carry_the_batch_index_column(self) -> None:
+ client = FakeSnowflakeClient()
+ ctx = _ctx()
+
+ await _deliver(LocalSnowflakeWriter(ctx, client), ctx, _rows([1], ["a"]), 0, is_final=True)
+
+ assert client.tables["charges"].columns == ["id", "name"]
+
+ async def test_a_second_full_refresh_may_replace_a_table_the_first_one_created(self) -> None:
+ # The table the first run published carries its publish stamp, and the ownership check
+ # has to keep reading that as "owned by this schema" or no later run could ever publish.
+ client = FakeSnowflakeClient()
+ first = _ctx(run_uuid="run-a1")
+ second = _ctx(run_uuid="run-b2")
+
+ await _deliver(LocalSnowflakeWriter(first, client), first, _rows([1], ["old"]), 0, is_final=True)
+ await _deliver(LocalSnowflakeWriter(second, client), second, _rows([2], ["new"]), 0, is_final=True)
+
+ assert _read(client) == [(2, "new")]
+
+ async def test_a_full_refresh_refuses_to_replace_a_table_a_different_schema_created(self) -> None:
+ client = FakeSnowflakeClient()
+ first = _ctx(schema_id="schema-a", run_uuid="run-a1")
+ second = _ctx(schema_id="schema-b", run_uuid="run-b2")
+
+ await _deliver(LocalSnowflakeWriter(first, client), first, _rows([1], ["a"]), 0, is_final=True)
+
+ second_writer = LocalSnowflakeWriter(second, client)
+ await _deliver(second_writer, second, _rows([2], ["b"]), 0)
+ with pytest.raises(UnrelatedTableExistsError):
+ await second_writer.finalize_run(second)
+
+ assert _read(client) == [(1, "a")]
+
+
+class TestIncremental:
+ async def test_rows_are_merged_on_the_primary_key(self) -> None:
+ client = FakeSnowflakeClient()
+ ctx = _ctx(sync_type="incremental", primary_keys=("id",))
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1, 2], ["first", "second"]), 0)
+ await _deliver(writer, ctx, _rows([1], ["updated"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "updated"), (2, "second")]
+
+ async def test_a_batch_carrying_one_key_twice_keeps_the_last_row(self) -> None:
+ # Nothing upstream promises a staged batch holds each key once, and Snowflake rejects a
+ # MERGE whose source matches a target row more than once, on every retry.
+ client = FakeSnowflakeClient()
+ ctx = _ctx(sync_type="incremental", primary_keys=("id",))
+ writer = LocalSnowflakeWriter(ctx, client)
+
+ await _deliver(writer, ctx, _rows([1], ["first"]), 0)
+ await _deliver(writer, ctx, _rows([1, 1], ["stale", "latest"]), 1, is_final=True)
+
+ assert _read(client) == [(1, "latest")]
+
+ async def test_the_fake_rejects_a_duplicated_key_the_way_snowflake_does(self) -> None:
+ # Guards the test above: if the fake accepted a multi-matching MERGE, that test would
+ # pass with or without the dedup.
+ client = FakeSnowflakeClient()
+ client.tables["charges"] = FakeSnowflakeTable(["id", "name"])
+ client.tables["charges"].rows = [{"id": 1, "name": "first"}]
+ client.tables["stage"] = FakeSnowflakeTable(["id", "name"])
+ client.tables["stage"].rows = [{"id": 1, "name": "stale"}, {"id": 1, "name": "latest"}]
+
+ with pytest.raises(MergeMultiMatchError):
+ await client.execute_async_query(
+ 'MERGE INTO "PUBLIC"."charges" AS target USING "PUBLIC"."stage" AS source '
+ 'ON target."id" = source."id" '
+ 'WHEN MATCHED THEN UPDATE SET target."name" = source."name" '
+ 'WHEN NOT MATCHED THEN INSERT ("id", "name") VALUES (source."id", source."name")'
+ )
+
+
+class TestRunScopedScratchNames:
+ """Two runs of one table's incremental sync can be in flight together, because this writer
+ does not hold the sync lock. They share the live table, and therefore its internal stage, so
+ a scratch name that only carries the batch index collides: one run's stage cleanup deletes
+ the file the other just uploaded, and one run's `DROP TABLE` drops the merge source the
+ other is reading.
+ """
+
+ @parameterized.expand(
+ [
+ ("stage file path", lambda run_uuid: stage_prefix(run_uuid, 0, 0)),
+ ("merge scratch table", lambda run_uuid: merge_stage_name("charges", run_uuid, 0, 0)),
+ ("staging table", lambda run_uuid: staging_table_name(_ctx(run_uuid=run_uuid))),
+ ]
+ )
+ def test_two_runs_of_the_same_table_and_batch_get_different_names(self, _name, name_for) -> None:
+ assert name_for("3f8c1d2e-aaaa-4000-8000-000000000001") != name_for("9b2d4e6f-bbbb-4000-8000-000000000002")
+
+
+class TestIdentifierSafety:
+ """`SnowflakeClient` interpolates these four straight into `USE ...` statements with no
+ escaping of its own, and a destination's config is editable.
+ """
+
+ @parameterized.expand(
+ [
+ ("database", {"database": 'DB" -- ', "schema": "PUBLIC", "warehouse": "WH"}),
+ ("schema", {"database": "DB", "schema": 'PUBLIC"', "warehouse": "WH"}),
+ ("warehouse", {"database": "DB", "schema": "PUBLIC", "warehouse": "WH\n"}),
+ ("role", {"database": "DB", "schema": "PUBLIC", "warehouse": "WH", "role": 'R"'}),
+ ("missing database", {"schema": "PUBLIC", "warehouse": "WH"}),
+ ("missing warehouse", {"database": "DB", "schema": "PUBLIC"}),
+ ]
+ )
+ def test_a_config_that_could_break_out_of_its_quoting_is_rejected(self, _name, config) -> None:
+ with pytest.raises(ValueError):
+ SnowflakeDestinationWriter(_ctx(config=config))
+
+ def test_an_unset_role_is_allowed(self) -> None:
+ # Snowflake falls back to the user's default role, so no role is a valid config.
+ writer = SnowflakeDestinationWriter(_ctx(config={"database": "DB", "schema": "PUBLIC", "warehouse": "WH"}))
+
+ assert writer._role is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py
index 9fc02c772f58..eec7a7b90f02 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/azure_blob.py
@@ -4,6 +4,13 @@ The same idea as the S3 writer: each batch becomes one blob at a name derived fr
the batch index, so re-applying a batch overwrites its own blob rather than adding a second
copy. Nothing needs staging or a swap.
+That is also why this writer carries no publish stamp, unlike the SQL destinations. Publishing
+is one more blob under the same run prefix, the manifest, and re-writing it says the same thing
+it said the first time. A redelivered final batch therefore rewrites its own blob and its own
+manifest, and no blob any earlier batch wrote is touched. A destination that publishes by
+swapping a staging table over the live one has no such property, which is what the stamp exists
+to cover there.
+
Connection handling comes from batch exports' Azure Blob destination:
- `validate_azure_blob_connection_string` plus `MalformedConnectionStringError` turn a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
index d9e3d1d1e534..bd1b89323e2e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/bigquery.py
@@ -33,8 +33,14 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
-
-BATCH_INDEX_COLUMN = "_ph_batch_index"
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
+ dedupe_merge_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.run_markers import (
+ BATCH_INDEX_COLUMN,
+ run_scope,
+ stamp_batch_index,
+)
# Proof this writer created a table, so a sync never truncates, merges into or appends to one
# the customer already had. `table_name` comes from the source's resource name, which a custom
@@ -45,13 +51,23 @@ BATCH_INDEX_COLUMN = "_ph_batch_index"
# lets `finalize_run` check the live table's label after the swap that publishes it.
_OWNERSHIP_LABEL_KEY = "posthog_sync_schema"
+# The run that last published this table, carried beside the ownership label. A redelivered
+# final batch reads it to tell "this run already published" from "this run never started";
+# without it the replay rebuilds a staging table out of that one batch and copies it over the
+# complete table.
+_PUBLISHED_RUN_LABEL_KEY = "posthog_sync_run"
+
+
+class BigQueryDestinationConfigurationError(ValueError):
+ """The destination's config cannot produce a valid BigQuery write."""
+
class UnrelatedTableExistsError(RuntimeError):
"""A sync would have overwritten, merged into or appended to a table it never created."""
def staging_table_name(ctx: DestinationRunContext) -> str:
- return f"{ctx.table_name}__ph_stage_{ctx.run_uuid.replace('-', '')[:12]}"
+ return f"{ctx.table_name}__ph_stage_{run_scope(ctx.run_uuid)}"
def _backtick(name: str) -> str:
@@ -75,6 +91,20 @@ class BigQueryDestinationWriter:
self._client: bigquery.Client | None = None
self._project: str = config.get("project") or config.get("project_id") or ""
+ self._validate_config()
+
+ def _validate_config(self) -> None:
+ """Reject a config that cannot write, before a batch is read.
+
+ Left to fail later, a missing dataset fails inside a load job, hundreds of MiB into the
+ batch, and reports itself as a table-reference error rather than as missing config.
+ """
+ if not self._dataset:
+ raise BigQueryDestinationConfigurationError(
+ f"Destination {self._ctx.destination_name} has no dataset. Add a dataset to the destination, "
+ "then run the sync again."
+ )
+
def _get_client(self) -> bigquery.Client:
"""The underlying BigQuery client, resolved the way the batch export resolves it.
@@ -122,6 +152,11 @@ class BigQueryDestinationWriter:
# entropy left to stay collision-free for this many schemas.
return hashlib.sha256(self._ctx.schema_id.encode()).hexdigest()[:63]
+ def _run_label(self) -> str:
+ # Hashed for the same reason as `_schema_label`: `run_uuid` carries no guarantee that it
+ # only holds characters a BigQuery label value accepts.
+ return hashlib.sha256(self._ctx.run_uuid.encode()).hexdigest()[:63]
+
def _check_owned_or_absent(self, client: bigquery.Client, table_ref: str, action: str) -> bool:
"""Whether `table_ref` does not exist yet.
@@ -139,11 +174,37 @@ class BigQueryDestinationWriter:
)
return False
- def _mark_owned(self, client: bigquery.Client, table_ref: str) -> None:
+ def _set_labels(self, client: bigquery.Client, table_ref: str, labels: dict[str, str]) -> None:
existing = client.get_table(table_ref)
- existing.labels = {**(existing.labels or {}), _OWNERSHIP_LABEL_KEY: self._schema_label()}
+ existing.labels = {**(existing.labels or {}), **labels}
client.update_table(existing, ["labels"])
+ def _mark_owned(self, client: bigquery.Client, table_ref: str) -> None:
+ self._set_labels(client, table_ref, {_OWNERSHIP_LABEL_KEY: self._schema_label()})
+
+ def _mark_published(self, client: bigquery.Client, table_ref: str) -> None:
+ self._set_labels(
+ client,
+ table_ref,
+ {_OWNERSHIP_LABEL_KEY: self._schema_label(), _PUBLISHED_RUN_LABEL_KEY: self._run_label()},
+ )
+
+ def _already_published(self, ctx: DestinationRunContext) -> bool:
+ """Whether this run already copied its staging table over the live table."""
+ client = self._get_client()
+ try:
+ client.get_table(self._table_ref(staging_table_name(ctx)))
+ except NotFound:
+ pass
+ else:
+ return False
+
+ try:
+ live = client.get_table(self._table_ref(ctx.table_name))
+ except NotFound:
+ return False
+ return (live.labels or {}).get(_PUBLISHED_RUN_LABEL_KEY) == self._run_label()
+
async def prepare_run(self, ctx: DestinationRunContext) -> None:
def ensure_dataset() -> None:
client = self._get_client()
@@ -154,6 +215,12 @@ class BigQueryDestinationWriter:
async def write_batch(
self, batches: AsyncIterator[pa.RecordBatch], ctx: DestinationBatchContext
) -> BatchWriteOutcome:
+ if ctx.run.is_full_refresh and await sync_to_async(self._already_published, thread_sensitive=False)(ctx.run):
+ # This run's staging table is gone and the live table carries this run's publish
+ # label, so the run finished. Rebuilding a staging table from this one batch and
+ # copying it over the live table would replace the whole table with it.
+ return BatchWriteOutcome(rows_written=0)
+
rows_written = 0
chunk = 0
@@ -170,60 +237,94 @@ class BigQueryDestinationWriter:
async def _write_one(self, record_batch: pa.RecordBatch, ctx: DestinationBatchContext, chunk: int) -> int:
run = ctx.run
full_refresh = run.is_full_refresh
- # pq.write_table needs a Table, and one record batch is one load job.
- table = pa.Table.from_batches([record_batch])
-
- is_first_write = ctx.batch_index == 0 and chunk == 0
+ is_first_chunk = chunk == 0
def write() -> int:
client = self._get_client()
if full_refresh:
- staging = staging_table_name(run)
- # Batch 0 truncates so a re-run of the whole batch sequence starts clean; later
- # batches append. Re-applying one batch is covered by the apply marker.
- # Only the very first chunk of the very first batch truncates; every later
- # chunk appends, or it would wipe what the chunk before it just loaded.
- disposition = (
- bigquery.WriteDisposition.WRITE_TRUNCATE
- if is_first_write
- else bigquery.WriteDisposition.WRITE_APPEND
- )
- staging_ref = self._table_ref(staging)
- if is_first_write:
- # The staging name is unique to this run, so a genuine collision is remote,
- # but refusing to reuse an unrelated table costs one read and closes the gap.
- self._check_owned_or_absent(client, staging_ref, "reuse it as a staging table")
- self._load(client, staging, table, disposition)
- if is_first_write:
- self._mark_owned(client, staging_ref)
- return table.num_rows
+ return self._write_full_refresh_chunk(client, record_batch, ctx, first_chunk=is_first_chunk)
if run.is_incremental and run.primary_keys:
- temp = f"{run.table_name}__ph_tmp_{run.run_uuid.replace('-', '')[:8]}_{ctx.batch_index}_{chunk}"
- target_ref = self._table_ref(run.table_name)
- if is_first_write:
- # A merge target BigQuery rejects outright if it does not already exist, so
- # this only ever narrows an existing failure to a clearer one; it never
- # creates or marks a table that was never there to check.
- self._check_owned_or_absent(client, target_ref, "merge into it")
- self._load(client, temp, table, bigquery.WriteDisposition.WRITE_TRUNCATE)
- self._merge(client, run.table_name, temp, list(table.schema.names), list(run.primary_keys))
- client.delete_table(self._table_ref(temp), not_found_ok=True)
- if is_first_write:
- self._mark_owned(client, target_ref)
- return table.num_rows
+ return self._merge_chunk(client, record_batch, ctx, chunk)
+ # pq.write_table needs a Table, and one record batch is one load job.
+ table = pa.Table.from_batches([record_batch])
target_ref = self._table_ref(run.table_name)
- if is_first_write:
- self._check_owned_or_absent(client, target_ref, "append to it")
+ target_absent = self._check_owned_or_absent(client, target_ref, "append to it")
self._load(client, run.table_name, table, bigquery.WriteDisposition.WRITE_APPEND)
- if is_first_write:
+ if target_absent:
self._mark_owned(client, target_ref)
return table.num_rows
return await sync_to_async(write, thread_sensitive=False)()
+ def _write_full_refresh_chunk(
+ self, client: bigquery.Client, record_batch: pa.RecordBatch, ctx: DestinationBatchContext, *, first_chunk: bool
+ ) -> int:
+ """Append one chunk to the run's staging table, having cleared this batch's own rows.
+
+ Every staged row carries the batch that wrote it, and the first chunk of a batch deletes
+ the rows its previous attempt left. Without that, a re-applied batch appends a second
+ copy of its rows: the consumer re-claims any batch whose outcome it could not confirm,
+ and the staging table lives for the whole run, so nothing else removes them.
+ """
+ staging = staging_table_name(ctx.run)
+ staging_ref = self._table_ref(staging)
+ table = pa.Table.from_batches([stamp_batch_index(record_batch, ctx.batch_index)])
+
+ if first_chunk:
+ # The staging name is unique to this run, so a genuine collision is remote, but
+ # refusing to reuse an unrelated table costs one read and closes the gap.
+ staging_absent = self._check_owned_or_absent(client, staging_ref, "reuse it as a staging table")
+ if not staging_absent:
+ self._delete_batch_rows(client, staging, ctx.batch_index)
+
+ self._load(client, staging, table, bigquery.WriteDisposition.WRITE_APPEND)
+ if staging_absent:
+ self._mark_owned(client, staging_ref)
+ return table.num_rows
+
+ self._load(client, staging, table, bigquery.WriteDisposition.WRITE_APPEND)
+ return table.num_rows
+
+ def _delete_batch_rows(self, client: bigquery.Client, table: str, batch_index: int) -> None:
+ client.query(
+ f"DELETE FROM {self._quoted_table(table)} WHERE {_backtick(BATCH_INDEX_COLUMN)} = {int(batch_index)}"
+ ).result()
+
+ def _merge_chunk(
+ self, client: bigquery.Client, record_batch: pa.RecordBatch, ctx: DestinationBatchContext, chunk: int
+ ) -> int:
+ """Upsert one chunk on the primary keys, staging it in a scratch table first."""
+ run = ctx.run
+ primary_keys = list(run.primary_keys)
+ # BigQuery rejects a `MERGE` whose source matches one target row more than once, and it
+ # rejects it again on every retry.
+ table = pa.Table.from_batches([dedupe_merge_source(record_batch, primary_keys)])
+
+ temp = f"{run.table_name}__ph_tmp_{run_scope(run.run_uuid, 8)}_{ctx.batch_index}_{chunk}"
+ target_ref = self._table_ref(run.table_name)
+ target_absent = self._check_owned_or_absent(client, target_ref, "merge into it")
+
+ self._load(client, temp, table, bigquery.WriteDisposition.WRITE_TRUNCATE)
+ try:
+ if target_absent:
+ # `MERGE` fails outright against a target that does not exist, and an
+ # incremental schema is on `sync_type` "incremental" from its very first run,
+ # so nothing else ever creates it. Take the schema BigQuery just derived for the
+ # scratch table rather than mapping Arrow types a second time.
+ self._create_like(client, target_ref, temp)
+ self._mark_owned(client, target_ref)
+ self._merge(client, run.table_name, temp, list(table.schema.names), primary_keys)
+ finally:
+ client.delete_table(self._table_ref(temp), not_found_ok=True)
+ return table.num_rows
+
+ def _create_like(self, client: bigquery.Client, table_ref: str, model: str) -> None:
+ """Create an empty table carrying another table's schema."""
+ client.create_table(bigquery.Table(table_ref, schema=client.get_table(self._table_ref(model)).schema))
+
def _load(self, client: bigquery.Client, table: str, data: pa.Table, disposition: str) -> None:
"""Load an Arrow table as parquet, letting BigQuery derive and evolve the schema."""
buffer = io.BytesIO()
@@ -275,18 +376,27 @@ class BigQueryDestinationWriter:
# that cannot be skipped on the strength of `write_batch`'s: a table sharing the
# generated name could have appeared, or lost its label, between the two calls.
self._check_owned_or_absent(client, target_ref, "replace it with the full refresh's staging table")
+ # The batch-index column belongs to the staging table's own bookkeeping, so it is
+ # dropped before the copy rather than published as part of the synced table.
+ client.query(
+ f"ALTER TABLE {self._quoted_table(staging)} DROP COLUMN IF EXISTS {_backtick(BATCH_INDEX_COLUMN)}"
+ ).result()
client.copy_table(
self._table_ref(staging),
target_ref,
job_config=bigquery.CopyJobConfig(write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE),
).result()
- self._mark_owned(client, target_ref)
+ # Stamp the run that published, so a redelivery of the final batch can tell "already
+ # published" from "never started" and refuse to rebuild the table.
+ self._mark_published(client, target_ref)
client.delete_table(self._table_ref(staging), not_found_ok=True)
await sync_to_async(publish, thread_sensitive=False)()
async def abort_run(self, ctx: DestinationRunContext) -> None:
- if not ctx.is_full_refresh or self._client is None:
+ # No `self._client is None` guard: `abort_destinations` builds a fresh writer for this
+ # call, so the client is always unset here and the cleanup would never run.
+ if not ctx.is_full_refresh:
return
def drop() -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
index 57a49f0a99f6..c32915f36567 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/databricks.py
@@ -44,6 +44,18 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
+ dedupe_merge_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.run_markers import (
+ BATCH_INDEX_COLUMN,
+ is_owned_by,
+ is_published_by,
+ owned_marker,
+ published_marker,
+ run_scope,
+ stamp_batch_index,
+)
_DATABRICKS_BY_ARROW = {
pa.bool_(): "BOOLEAN",
@@ -66,8 +78,6 @@ _DATABRICKS_BY_ARROW = {
pa.date64(): "DATE",
}
-BATCH_INDEX_COLUMN = "_ph_batch_index"
-
# Server-side backstop. Every statement below is bounded client-side well within this, so it
# only catches a query the client-side timeout cannot reach, such as one whose connection went
# away, rather than letting it run on the customer's warehouse until something else notices.
@@ -142,27 +152,13 @@ def _assert_safe_identifier(value: str, what: str) -> str:
return value
-def _run_scope(run_uuid: str) -> str:
- """A short token unique to one run, safe in both a table name and a volume path."""
- return run_uuid.replace("-", "")[:12]
-
-
def staging_table_name(ctx: DestinationRunContext) -> str:
- return f"{ctx.table_name}__ph_stage_{_run_scope(ctx.run_uuid)}"
+ return f"{ctx.table_name}__ph_stage_{run_scope(ctx.run_uuid)}"
-# Proof this writer created a table, so a sync never mutates, merges into or drops one the
-# customer already had. `table_name` comes from the source's resource name, which a custom
-# source manifest controls, so without this any table sharing that name is fair game.
-#
-# Stored as a Databricks table comment: `ALTER TABLE ... RENAME` keeps a table's comment, so
-# the marker set on a full refresh's staging table survives into `finalize_run`'s swap. Scoped
-# by schema id because `table_name` collides across sources on purpose and ownership must not.
-_OWNERSHIP_COMMENT = "posthog-warehouse-sync-owned"
-
-
-def _owned_marker(schema_id: str) -> str:
- return f"{_OWNERSHIP_COMMENT}:{schema_id}"
+# The ownership and publish markers are stored as Databricks table comments:
+# `ALTER TABLE ... RENAME` keeps a table's comment, so the marker set on a full refresh's
+# staging table survives into `finalize_run`'s swap.
class UnrelatedTableExistsError(RuntimeError):
@@ -263,9 +259,17 @@ class DatabricksDestinationWriter:
async def _table_comment(self, client: DatabricksClient, table: str) -> str | None:
async with handle_common_errors(f"SELECT comment FOR {table}", ONE_MINUTE):
+ # Matched case-insensitively because Unity Catalog stores schema and table names
+ # lowercased, while `self._schema` and `table` carry whatever case the destination
+ # config and the source's resource name gave them. An exact match would find no row
+ # for an uppercase name, so `_is_owned` would report a table this writer created as
+ # unowned and every run of it would raise `UnrelatedTableExistsError`. The existence
+ # probe next to this one matches case-insensitively already, which is what makes the
+ # two disagree.
rows = await client.execute_query(
f"SELECT comment FROM {backtick(self._catalog)}.information_schema.tables "
- f"WHERE table_schema = {sql_literal(self._schema)} AND table_name = {sql_literal(table)}",
+ f"WHERE lower(table_schema) = {sql_literal(self._schema.lower())} "
+ f"AND lower(table_name) = {sql_literal(table.lower())}",
timeout=ONE_MINUTE,
)
if not rows:
@@ -273,26 +277,27 @@ class DatabricksDestinationWriter:
return rows[0][0]
async def _is_owned(self, client: DatabricksClient, table: str, schema_id: str) -> bool:
- # Not a plain `startswith`: schema ids are arbitrary strings, and one could be a
- # character-prefix of another, which would let a table another schema owns pass as
- # owned here. Split on the marker's own `:` separator instead so the owning schema id
- # is compared for exact equality.
- comment = await self._table_comment(client, table)
- if comment is None:
+ return is_owned_by(await self._table_comment(client, table), schema_id)
+
+ async def _already_published(self, client: DatabricksClient, ctx: DestinationRunContext) -> bool:
+ """Whether this run already swapped its staging table into place."""
+ if await self._table_exists(client, staging_table_name(ctx)):
return False
- marker, sep, rest = comment.partition(":")
- if marker != _OWNERSHIP_COMMENT or not sep:
+ if not await self._table_exists(client, ctx.table_name):
return False
- return rest == schema_id
+ return is_published_by(await self._table_comment(client, ctx.table_name), ctx.schema_id, ctx.run_uuid)
- async def _mark_owned(self, client: DatabricksClient, table: str, schema_id: str) -> None:
+ async def _set_comment(self, client: DatabricksClient, table: str, marker: str) -> None:
async with handle_common_errors(f"COMMENT ON TABLE {table}", FIVE_MINUTES):
await client.execute_query(
- f"COMMENT ON TABLE {self._qualified(table)} IS {sql_literal(_owned_marker(schema_id))}",
+ f"COMMENT ON TABLE {self._qualified(table)} IS {sql_literal(marker)}",
fetch_results=False,
timeout=FIVE_MINUTES,
)
+ async def _mark_owned(self, client: DatabricksClient, table: str, schema_id: str) -> None:
+ await self._set_comment(client, table, owned_marker(schema_id))
+
async def _claim_table(self, client: DatabricksClient, table: str, schema_id: str) -> bool:
"""Refuse to touch `table` unless this call creates it or a prior one already owns it.
@@ -328,20 +333,19 @@ class DatabricksDestinationWriter:
# another schema's in-flight upload.
await client.acreate_volume(self._volume)
+ if full_refresh and await self._already_published(client, run):
+ # This run's staging table is gone and the live table carries this run's publish
+ # stamp, so the run finished. Re-creating a staging table from this one batch and
+ # swapping it in would replace the whole table with it.
+ return BatchWriteOutcome(rows_written=0)
+
first = True
chunk = 0
async for batch in batches:
if batch.num_rows == 0:
continue
- stamped = (
- batch.append_column(
- BATCH_INDEX_COLUMN,
- pa.array([ctx.batch_index] * batch.num_rows, type=pa.int32()),
- )
- if full_refresh
- else batch
- )
+ stamped = stamp_batch_index(batch, ctx.batch_index) if full_refresh else batch
fields = fields_for(batch.schema, with_batch_index=full_refresh)
if first:
@@ -366,13 +370,12 @@ class DatabricksDestinationWriter:
first = False
if run.is_incremental and run.primary_keys and not full_refresh:
- await self._merge_chunk(
+ rows_written += await self._merge_chunk(
client, target, stamped, fields, list(run.primary_keys), run.run_uuid, ctx.batch_index, chunk
)
else:
await self._copy_chunk(client, target, stamped, fields, run.run_uuid, ctx.batch_index, chunk)
-
- rows_written += batch.num_rows
+ rows_written += batch.num_rows
chunk += 1
return BatchWriteOutcome(rows_written=rows_written)
@@ -397,7 +400,7 @@ class DatabricksDestinationWriter:
# same `target` (the live table), so without `run_uuid` here their staged files would
# share one name and one run's rows could be COPY'd by the other, or removed out from
# under it once loaded.
- file_name = f"ph_{_run_scope(run_uuid)}_{batch_index}_{chunk}.parquet"
+ file_name = f"ph_{run_scope(run_uuid)}_{batch_index}_{chunk}.parquet"
volume_path = f"{self._volume_path()}/{target}"
await client.aput_file_stream_to_volume(buffer, volume_path, file_name)
@@ -431,12 +434,16 @@ class DatabricksDestinationWriter:
run_uuid: str,
batch_index: int,
chunk: int,
- ) -> None:
+ ) -> int:
"""Upsert on the primary keys, staging the chunk in a scratch table first."""
+ # Delta rejects a `MERGE` whose source matches one target row more than once
+ # (`DELTA_MULTIPLE_SOURCE_ROW_MATCHING_TARGET_ROW_IN_MERGE`), and it rejects it again on
+ # every retry.
+ batch = dedupe_merge_source(batch, primary_keys)
columns = list(batch.schema.names)
# Run-scoped for the same reason as the staged file in `_copy_chunk`: two overlapping
# runs of this table must not merge from, or drop, each other's scratch table.
- stage_table = f"{target}__ph_merge_{_run_scope(run_uuid)}_{batch_index}_{chunk}"
+ stage_table = f"{target}__ph_merge_{run_scope(run_uuid)}_{batch_index}_{chunk}"
async with client.managed_table(stage_table, fields, delete=True):
await self._copy_chunk(client, stage_table, batch, fields, run_uuid, batch_index, chunk)
@@ -458,6 +465,8 @@ class DatabricksDestinationWriter:
timeout=ONE_HOUR,
)
+ return batch.num_rows
+
async def finalize_run(self, ctx: DestinationRunContext) -> None:
"""Publish a full refresh by swapping the staging table into place."""
if not ctx.is_full_refresh:
@@ -491,6 +500,13 @@ class DatabricksDestinationWriter:
fetch_results=False,
timeout=FIVE_MINUTES,
)
+ # Stamp the run that published on the staging table, before it swaps into place.
+ # The comment survives the rename below, so the table is never visible under its
+ # live name without the marker already on it. Stamping after the rename would leave
+ # a crash window where the swap completes but the marker never lands, and a
+ # redelivered final batch would then rebuild staging from just that batch and
+ # publish over the table that already holds the complete data.
+ await self._set_comment(client, staging, published_marker(ctx.schema_id, ctx.run_uuid))
await client.adelete_table(ctx.table_name)
async with handle_common_errors(f"ALTER TABLE {staging} RENAME TO {ctx.table_name}", FIVE_MINUTES):
await client.execute_query(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/merge_dedup.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/merge_dedup.py
new file mode 100644
index 000000000000..36ef0761912b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/merge_dedup.py
@@ -0,0 +1,36 @@
+"""Collapsing a merge source to one row per primary key.
+
+Nothing upstream promises a staged batch holds each key once. Sources re-yield a page after a
+crash and CDC carries several events for one row, and the pipeline leans on the merge to settle
+it: the delta writer collapses its own copy of the batch with `first_per_pk_table(..., keep=
+"last")`, but it does that after `deliver_batch_to_destinations` has already handed the raw
+staged file to every external destination.
+
+A duplicated key is not a duplicate row at the destination, it is a failed batch. Postgres
+answers `ON CONFLICT DO UPDATE` over two rows of one key with "cannot affect row a second
+time", and the `MERGE` statements on BigQuery, Databricks and Snowflake all reject a source
+row that matches a target row more than once. The batch then fails the same way on every
+retry, so the sync stops until the source stops repeating the key.
+
+Keeping the last occurrence is what the delta writer does, so both copies of the data settle on
+the same row.
+"""
+
+from __future__ import annotations
+
+import pyarrow as pa
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import first_per_pk_table
+
+
+def dedupe_merge_source(batch: pa.RecordBatch, primary_keys: list[str]) -> pa.RecordBatch:
+ """Keep the last row of each primary key in `batch`, in the batch's own row order."""
+ keys = [key for key in primary_keys if key in batch.schema.names]
+ if not keys or batch.num_rows < 2:
+ return batch
+
+ deduped = first_per_pk_table(pa.Table.from_batches([batch]), keys, keep="last")
+ if deduped.num_rows == batch.num_rows:
+ return batch
+
+ return deduped.combine_chunks().to_batches()[0]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py
index 485d9ac2ec90..706522ba327c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py
@@ -50,33 +50,25 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
+ dedupe_merge_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.run_markers import (
+ BATCH_INDEX_COLUMN,
+ is_owned_by,
+ is_published_by,
+ owned_marker,
+ published_marker,
+ run_scope,
+ stamp_batch_index,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.sql_types import (
is_nested_type,
postgres_type_for,
)
-# Marks which batch of a run wrote a staged row, so re-applying a batch can delete exactly
-# what its previous attempt wrote instead of the whole staging table.
-BATCH_INDEX_COLUMN = "_ph_batch_index"
-
-# Proof this writer created a table, so a sync never drops or merges into one the customer
-# already had. `table_name` comes from the source's resource name, which a custom-source
-# manifest controls, so without it any table sharing that name is fair game.
-#
-# Stored as a Postgres comment because those follow the table's OID, surviving the rename in
-# `finalize_run`. Scoped by schema id because `table_name` collides across sources on purpose
-# and ownership must not.
-_OWNERSHIP_COMMENT = "posthog-warehouse-sync-owned"
-
-
-def _owned_marker(schema_id: str) -> str:
- """Ownership marker scoped to the schema whose sync created the table."""
- return f"{_OWNERSHIP_COMMENT}:{schema_id}"
-
-
-def _published_comment(schema_id: str, run_uuid: str) -> str:
- """Ownership marker plus the run that last published, so a replay can recognize itself."""
- return f"{_owned_marker(schema_id)}:{run_uuid}"
+# The ownership and publish markers are stored as Postgres comments because those follow the
+# table's OID, surviving the rename in `finalize_run`.
class UnrelatedTableExistsError(RuntimeError):
@@ -98,14 +90,14 @@ def _scoped_identifier(base: str, suffix: str) -> str:
def staging_table_name(ctx: DestinationRunContext) -> str:
# Run-scoped, so two runs of the same table never share a staging table.
- return _scoped_identifier(ctx.table_name, f"__ph_stage_{ctx.run_uuid.replace('-', '')[:12]}")
+ return _scoped_identifier(ctx.table_name, f"__ph_stage_{run_scope(ctx.run_uuid)}")
def merge_stage_name(target: str, ctx: DestinationRunContext) -> str:
# `target` is the live table on an incremental run, so it can already be at the identifier
# limit. Reserve room for the suffix or the stage name truncates onto the live table, and
# dropping the stage would drop it.
- return _scoped_identifier(target, f"__ph_merge_{ctx.run_uuid.replace('-', '')[:8]}")
+ return _scoped_identifier(target, f"__ph_merge_{run_scope(ctx.run_uuid, 8)}")
def _to_json_text(value: Any, *, from_map: bool) -> str | None:
@@ -255,6 +247,11 @@ class PostgresDestinationWriter:
if field.name in existing:
continue
async with self._write_cursor(client) as cursor:
+ # TODO: `RedshiftDestinationWriter` inherits this statement, and Redshift may
+ # not accept `ADD COLUMN IF NOT EXISTS`. If it does not, every Redshift sync
+ # whose source grows a column fails here with a syntax error rather than
+ # evolving the table. Confirm against a real cluster. The guard above already
+ # skips columns the table has, so a plain `ADD COLUMN` would also do.
await cursor.execute(
sql.SQL("ALTER TABLE {}.{} ADD COLUMN IF NOT EXISTS {} {}").format(
sql.Identifier(self._schema),
@@ -385,10 +382,7 @@ class PostgresDestinationWriter:
column_names = list(batch.schema.names)
if full_refresh:
- stamped = batch.append_column(
- self._batch_index_column,
- pa.array([ctx.batch_index] * batch.num_rows, type=pa.int32()),
- )
+ stamped = stamp_batch_index(batch, ctx.batch_index)
await self._load_batch(client, target, stamped, [*column_names, self._batch_index_column])
return batch.num_rows
@@ -404,20 +398,25 @@ class PostgresDestinationWriter:
"""Upsert a batch on the schema's primary keys, through a stage table."""
run = self._ctx
stage = merge_stage_name(target, run)
+ source = dedupe_merge_source(batch, list(run.primary_keys))
- await self._ensure_merge_stage(client, stage, batch.schema)
- await self._load_batch(client, stage, batch, column_names)
+ await self._ensure_merge_stage(client, target, stage, batch.schema)
+ await self._load_batch(client, stage, source, column_names)
await self._upsert_from_stage(client, target, stage, column_names, list(run.primary_keys))
- return batch.num_rows
+ return source.num_rows
- async def _ensure_merge_stage(self, client: PostgreSQLClient, stage: str, schema: pa.Schema) -> None:
+ async def _ensure_merge_stage(self, client: PostgreSQLClient, target: str, stage: str, schema: pa.Schema) -> None:
"""Ready the run's stage table to receive one batch.
Created once per run and emptied between batches rather than created and dropped per
batch. A table per batch is not free on someone else's server: each one writes catalog
rows that later have to be vacuumed, and vacuuming catalog tables can need locks.
`abort_run` and `finalize_run` drop it.
+
+ `target` is unused here because `ON CONFLICT` names its columns, so a stage carrying
+ only the batch's own columns is enough. Redshift's merge selects the destination's full
+ column list out of the stage, so its override builds the stage from `target` instead.
"""
await client.acreate_table(
self._schema, stage, self._fields_for(schema, with_batch_index=False), exists_ok=True
@@ -523,24 +522,12 @@ class PostgresDestinationWriter:
# it as a literal is safe the same way the fixed constant was.
await cursor.execute(
sql.SQL("COMMENT ON TABLE {}.{} IS {}").format(
- sql.Identifier(self._schema), sql.Identifier(table), sql.Literal(_owned_marker(schema_id))
+ sql.Identifier(self._schema), sql.Identifier(table), sql.Literal(owned_marker(schema_id))
)
)
async def _is_owned(self, client: PostgreSQLClient, table: str, schema_id: str) -> bool:
- # Not a plain `startswith`: schema ids are arbitrary strings, and one could be a
- # character-prefix of another ("abc" of "abc123"), which would let a table another
- # schema owns pass as owned here. Split on the marker's own `:` separators instead so
- # the owning schema id is compared for exact equality; a published table carries the
- # run uuid as a further segment after it, which this ignores.
- comment = await self._table_comment(client, table)
- if comment is None:
- return False
- marker, sep, rest = comment.partition(":")
- if marker != _OWNERSHIP_COMMENT or not sep:
- return False
- owner = rest.split(":", 1)[0]
- return owner == schema_id
+ return is_owned_by(await self._table_comment(client, table), schema_id)
async def _table_comment(self, client: PostgreSQLClient, table: str) -> str | None:
async with client.connection.cursor() as cursor:
@@ -563,7 +550,7 @@ class PostgresDestinationWriter:
return False
if not await self._table_exists(client, ctx.table_name):
return False
- return await self._table_comment(client, ctx.table_name) == _published_comment(ctx.schema_id, ctx.run_uuid)
+ return is_published_by(await self._table_comment(client, ctx.table_name), ctx.schema_id, ctx.run_uuid)
async def finalize_run(self, ctx: DestinationRunContext) -> None:
"""Publish a full refresh by swapping the staging table into place."""
@@ -594,6 +581,9 @@ class PostgresDestinationWriter:
)
async with self._write_cursor(client) as cursor:
+ # TODO: `RedshiftDestinationWriter` inherits this statement, and Redshift may
+ # not accept `DROP COLUMN IF EXISTS`. If it does not, every Redshift full
+ # refresh fails here and no run ever publishes. Confirm against a real cluster.
await cursor.execute(
sql.SQL("ALTER TABLE {}.{} DROP COLUMN IF EXISTS {}").format(
sql.Identifier(self._schema),
@@ -621,7 +611,7 @@ class PostgresDestinationWriter:
sql.SQL("COMMENT ON TABLE {}.{} IS {}").format(
sql.Identifier(self._schema),
sql.Identifier(ctx.table_name),
- sql.Literal(_published_comment(ctx.schema_id, ctx.run_uuid)),
+ sql.Literal(published_marker(ctx.schema_id, ctx.run_uuid)),
)
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
index a46043c21505..5b5ce19ea77c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/redshift.py
@@ -22,8 +22,6 @@ Wiring that up here is follow-up work.
from __future__ import annotations
import json
-from collections.abc import AsyncIterator
-from contextlib import asynccontextmanager
from typing import Any, ClassVar, cast
import pyarrow as pa
@@ -100,37 +98,41 @@ class RedshiftDestinationWriter(PostgresDestinationWriter):
self, client: PostgreSQLClient, table: str, batch: pa.RecordBatch, column_names: list[str]
) -> None:
"""Insert rather than COPY FROM STDIN, which Redshift does not support."""
+ nested = {field.name for field in batch.schema if is_nested_type(field.type)}
statement = sql.SQL("INSERT INTO {}.{} ({}) VALUES ({})").format(
sql.Identifier(self._schema),
sql.Identifier(table),
sql.SQL(", ").join(sql.Identifier(c) for c in column_names),
- sql.SQL(", ").join(sql.Placeholder() for _ in column_names),
+ # A JSON string bound straight into a SUPER column is stored as a string scalar,
+ # so `col.key` navigation over it returns NULL. `JSON_PARSE` is what turns the text
+ # into the SUPER structure the column was created to hold.
+ sql.SQL(", ").join(
+ sql.SQL("JSON_PARSE({})").format(sql.Placeholder()) if c in nested else sql.Placeholder()
+ for c in column_names
+ ),
)
payload = [[_encode(record.get(name)) for name in column_names] for record in batch.to_pylist()]
async with self._write_cursor(client) as cursor:
await cursor.executemany(statement, payload)
- @asynccontextmanager
- async def _merge_stage(
- self, client: PostgreSQLClient, target: str, stage: str, schema: pa.Schema
- ) -> AsyncIterator[str]:
- """Stage a batch in a copy of the destination table.
-
- `amerge_tables` inserts an unmatched row positionally, so the stage has to carry the
- destination's own columns in the destination's own order. Copying the destination's
- definition is the only way to hold that for a table this writer grows column by
- column. Columns the batch does not carry stay NULL, which is what the row would have
- held anyway.
+ async def _ensure_merge_stage(self, client: PostgreSQLClient, target: str, stage: str, schema: pa.Schema) -> None:
+ """Ready the run's stage table as a copy of the destination table.
+
+ `amerge_tables` selects the destination's full column list out of the stage and inserts
+ an unmatched row positionally, so the stage has to carry the destination's own columns
+ in the destination's own order. A stage built from the batch alone is short of any
+ column the destination grew on an earlier run, and the merge's `SELECT` then names a
+ column the stage does not have. Copying the destination's definition is the only way to
+ hold that for a table this writer grows column by column. Columns the batch does not
+ carry stay NULL, which is what the row would have held anyway.
+
+ Created once per run and emptied between batches, same as the base writer's stage, and
+ dropped by `abort_run` and `finalize_run`.
"""
async with self._write_cursor(client) as cursor:
- # A previous attempt at this batch may have died before dropping the stage, and
- # its rows are not this batch's.
- await cursor.execute(
- sql.SQL("DROP TABLE IF EXISTS {}.{}").format(sql.Identifier(self._schema), sql.Identifier(stage))
- )
await cursor.execute(
- sql.SQL("CREATE TABLE {}.{} (LIKE {}.{})").format(
+ sql.SQL("CREATE TABLE IF NOT EXISTS {}.{} (LIKE {}.{})").format(
sql.Identifier(self._schema),
sql.Identifier(stage),
sql.Identifier(self._schema),
@@ -138,8 +140,13 @@ class RedshiftDestinationWriter(PostgresDestinationWriter):
)
)
- async with client.managed_table(self._schema, stage, [], create=False, delete=True) as name:
- yield name
+ # The stage outlives the batch that created it, so a column the source grew mid-run has
+ # to reach it too, or the insert names a column the stage does not have.
+ await self._evolve_table(client, stage, schema)
+ async with self._write_cursor(client) as cursor:
+ await cursor.execute(
+ sql.SQL("TRUNCATE TABLE {}.{}").format(sql.Identifier(self._schema), sql.Identifier(stage))
+ )
async def _upsert_from_stage(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/run_markers.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/run_markers.py
new file mode 100644
index 000000000000..3629bf1140f4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/run_markers.py
@@ -0,0 +1,78 @@
+"""Markers a writer leaves on a destination table so a redelivered batch recognizes its own work.
+
+`DestinationWriter` requires `write_batch` to be idempotent per batch index. The per-batch
+marker in `load.idempotency` cannot carry that on its own: it is Redis with a TTL, and
+`mark_batch_as_processed` silently does nothing when Redis is unreachable. An external
+destination also has no delta history to fall back on, which leaves the markers below as the
+only defense against a redelivered batch.
+
+Each marker is written wherever the destination can carry text on a table: a Postgres or
+Snowflake comment, a Databricks table comment, a BigQuery label.
+
+- The ownership marker names the schema whose sync created the table, so a sync never drops or
+ mutates a table the customer already had.
+- The publish marker adds the run that swapped a full refresh into place. Without it, a
+ redelivered final batch rebuilds a staging table out of that one batch and swaps it over the
+ complete table, so the destination is left holding only the final batch's rows.
+
+The batch-index column is the other half of the same job. A full refresh stamps every staged
+row with the batch that wrote it, so re-applying a batch deletes exactly what its previous
+attempt wrote instead of appending a second copy. `finalize_run` drops the column before the
+staging table is published.
+"""
+
+from __future__ import annotations
+
+import pyarrow as pa
+
+# Marks which batch of a run wrote a staged row.
+BATCH_INDEX_COLUMN = "_ph_batch_index"
+
+OWNERSHIP_MARKER = "posthog-warehouse-sync-owned"
+
+
+def run_scope(run_uuid: str, length: int = 12) -> str:
+ """A short token unique to one run, safe inside a table name or an object path."""
+ return run_uuid.replace("-", "")[:length]
+
+
+def owned_marker(schema_id: str) -> str:
+ """Ownership marker scoped to the schema whose sync created the table.
+
+ Scoped by schema id because `table_name` is derived from the source's resource name, which
+ collides across sources on purpose. Ownership must not.
+ """
+ return f"{OWNERSHIP_MARKER}:{schema_id}"
+
+
+def published_marker(schema_id: str, run_uuid: str) -> str:
+ """Ownership marker plus the run that last published, so a replay can recognize itself."""
+ return f"{owned_marker(schema_id)}:{run_uuid}"
+
+
+def is_owned_by(marker: str | None, schema_id: str) -> bool:
+ """Whether `marker` says this schema's sync created the table."""
+ # Not a plain `startswith`: schema ids are arbitrary strings, and one could be a
+ # character-prefix of another ("abc" of "abc123"), which would let a table another schema
+ # owns pass as owned here. Split on the marker's own `:` separators instead, so the owning
+ # schema id is compared for exact equality. A published table carries the run uuid as a
+ # further segment after it, which this ignores.
+ if marker is None:
+ return False
+ name, separator, rest = marker.partition(":")
+ if name != OWNERSHIP_MARKER or not separator:
+ return False
+ return rest.split(":", 1)[0] == schema_id
+
+
+def is_published_by(marker: str | None, schema_id: str, run_uuid: str) -> bool:
+ """Whether `marker` says this run already published its full refresh."""
+ return marker is not None and marker == published_marker(schema_id, run_uuid)
+
+
+def stamp_batch_index(batch: pa.RecordBatch, batch_index: int) -> pa.RecordBatch:
+ """Add the batch-index column a full refresh's staged rows carry."""
+ return batch.append_column(
+ BATCH_INDEX_COLUMN,
+ pa.array([batch_index] * batch.num_rows, type=pa.int32()),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
index 9fcf1e8dab5e..8595bfe4dc6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/s3.py
@@ -4,6 +4,13 @@ Each batch is written to a key derived from the run and the batch index, so re-a
overwrites its own object rather than appending a second copy. Nothing here needs a staging
area or a swap.
+That is also why this writer carries no publish stamp, unlike the SQL destinations. Publishing
+is one more object under the same run prefix, the manifest, and re-writing it says the same
+thing it said the first time. A redelivered final batch therefore rewrites its own object and
+its own manifest, and no object any earlier batch wrote is touched. A destination that
+publishes by swapping a staging table over the live one has no such property, which is what
+the stamp exists to cover there.
+
Credentials, the client and its config come from batch exports' S3 destination:
- `_get_s3_integration` resolves all three shapes an S3-family integration can take. A
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
index 01552102e273..f7df352e154a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/snowflake.py
@@ -44,6 +44,18 @@ from products.warehouse_sources.backend.temporal.data_imports.destinations.contr
DestinationBatchContext,
DestinationRunContext,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.merge_dedup import (
+ dedupe_merge_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.run_markers import (
+ BATCH_INDEX_COLUMN,
+ is_owned_by,
+ is_published_by,
+ owned_marker,
+ published_marker,
+ run_scope,
+ stamp_batch_index,
+)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.destinations_load.writers.sql_types import (
quote_identifier,
)
@@ -69,8 +81,6 @@ _SNOWFLAKE_BY_ARROW = {
pa.date64(): "DATE",
}
-BATCH_INDEX_COLUMN = "_ph_batch_index"
-
# batch exports' `SnowflakeClient` writes the stage path and the COPY INTO column list by
# interpolating the names it is handed with no escaping of its own: a raw double-quoted
# identifier, inside a single-quoted path. Batch exports only ever passes it names it derived
@@ -89,20 +99,8 @@ def _assert_safe_identifier(value: str, what: str) -> str:
return value
-# Proof this writer created a table, so a sync never drops, merges into, or replaces one the
-# customer already had. `table_name` comes from the source's resource name, which a custom-source
-# manifest controls, so without it any table sharing that name in the configured role's reach is
-# fair game.
-#
-# Stored as a Snowflake table comment because that survives the `RENAME TO` in `finalize_run`.
-# Scoped by schema id because `table_name` collides across sources on purpose and ownership must
-# not.
-_OWNERSHIP_COMMENT = "posthog-warehouse-sync-owned"
-
-
-def _owned_marker(schema_id: str) -> str:
- """Ownership marker scoped to the schema whose sync created the table."""
- return f"{_OWNERSHIP_COMMENT}:{schema_id}"
+# The ownership and publish markers are stored as Snowflake table comments because a comment
+# survives the `RENAME TO` in `finalize_run`.
class UnrelatedTableExistsError(RuntimeError):
@@ -178,7 +176,24 @@ def _rows_of(result) -> list:
def staging_table_name(ctx: DestinationRunContext) -> str:
- return f"{ctx.table_name}__PH_STAGE_{ctx.run_uuid.replace('-', '')[:12]}"
+ return f"{ctx.table_name}__PH_STAGE_{run_scope(ctx.run_uuid)}"
+
+
+# This writer does not hold the sync lock (`holds_sync_lock` is False), so two runs of the same
+# table's incremental sync_type can be in flight together. Both write into the same live table,
+# and so into the same internal stage, which is why both names below carry the run: without it
+# one run's stage cleanup deletes the file the other just PUT but has not yet copied, and one
+# run's `DROP TABLE` drops the merge source the other is reading.
+
+
+def stage_prefix(run_uuid: str, batch_index: int, chunk: int) -> str:
+ """The internal-stage path one chunk's parquet file is uploaded under."""
+ return f"ph_{run_scope(run_uuid)}_{batch_index}_{chunk}"
+
+
+def merge_stage_name(target: str, run_uuid: str, batch_index: int, chunk: int) -> str:
+ """The scratch table one chunk is merged from."""
+ return f"{target}__PH_MERGE_{run_scope(run_uuid)}_{batch_index}_{chunk}"
class SnowflakeDestinationWriter:
@@ -188,10 +203,15 @@ class SnowflakeDestinationWriter:
def __init__(self, ctx: DestinationRunContext) -> None:
self._ctx = ctx
config = ctx.config or {}
- self._database = config.get("database") or ""
- self._schema = config.get("schema") or "PUBLIC"
- self._warehouse = config.get("warehouse") or ""
- self._role = config.get("role")
+ # `SnowflakeClient` interpolates all four straight into `USE DATABASE "..."`,
+ # `USE SCHEMA "..."`, `USE WAREHOUSE "..."` and the connector's `role` argument, with no
+ # escaping of its own. They come from a destination's config, which a team member edits,
+ # so anything that could break out of that quoting is rejected here.
+ self._database = _assert_safe_identifier(config.get("database") or "", "database")
+ self._schema = _assert_safe_identifier(config.get("schema") or "PUBLIC", "schema")
+ self._warehouse = _assert_safe_identifier(config.get("warehouse") or "", "warehouse")
+ role = config.get("role")
+ self._role = _assert_safe_identifier(role, "role") if role else None
# --- connection -------------------------------------------------------------------
@@ -273,23 +293,24 @@ class SnowflakeDestinationWriter:
rows = _rows_of(result)
return rows[0][0] if rows else None
- async def _mark_owned(self, client: SnowflakeClient, table: str, schema_id: str) -> None:
+ async def _set_comment(self, client: SnowflakeClient, table: str, marker: str) -> None:
await client.execute_async_query(
- f"ALTER TABLE {self._qualified(table)} SET COMMENT = {_sql_string_literal(_owned_marker(schema_id))}"
+ f"ALTER TABLE {self._qualified(table)} SET COMMENT = {_sql_string_literal(marker)}"
)
+ async def _mark_owned(self, client: SnowflakeClient, table: str, schema_id: str) -> None:
+ await self._set_comment(client, table, owned_marker(schema_id))
+
async def _is_owned(self, client: SnowflakeClient, table: str, schema_id: str) -> bool:
- # Not a plain `startswith`: schema ids are arbitrary strings, and one could be a
- # character-prefix of another ("abc" of "abc123"), which would let a table another
- # schema owns pass as owned here. Split on the marker's own `:` separator instead so the
- # owning schema id is compared for exact equality.
- comment = await self._table_comment(client, table)
- if comment is None:
+ return is_owned_by(await self._table_comment(client, table), schema_id)
+
+ async def _already_published(self, client: SnowflakeClient, ctx: DestinationRunContext) -> bool:
+ """Whether this run already swapped its staging table into place."""
+ if await self._table_exists(client, staging_table_name(ctx)):
return False
- marker, sep, owner = comment.partition(":")
- if marker != _OWNERSHIP_COMMENT or not sep:
+ if not await self._table_exists(client, ctx.table_name):
return False
- return owner == schema_id
+ return is_published_by(await self._table_comment(client, ctx.table_name), ctx.schema_id, ctx.run_uuid)
# --- writer protocol ----------------------------------------------------------------
@@ -307,20 +328,19 @@ class SnowflakeDestinationWriter:
rows_written = 0
async with client.connect():
+ if full_refresh and await self._already_published(client, run):
+ # This run's staging table is gone and the live table carries this run's publish
+ # stamp, so the run finished. Re-creating a staging table from this one batch and
+ # swapping it in would replace the whole table with it.
+ return BatchWriteOutcome(rows_written=0)
+
first = True
chunk = 0
async for batch in batches:
if batch.num_rows == 0:
continue
- stamped = (
- batch.append_column(
- BATCH_INDEX_COLUMN,
- pa.array([ctx.batch_index] * batch.num_rows, type=pa.int32()),
- )
- if full_refresh
- else batch
- )
+ stamped = stamp_batch_index(batch, ctx.batch_index) if full_refresh else batch
if first:
# `target` is the live table on an incremental run, and this writer's own
@@ -358,11 +378,12 @@ class SnowflakeDestinationWriter:
first = False
if run.is_incremental and run.primary_keys and not full_refresh:
- await self._merge_chunk(client, target, stamped, list(run.primary_keys), ctx.batch_index, chunk)
+ rows_written += await self._merge_chunk(
+ client, target, stamped, list(run.primary_keys), run.run_uuid, ctx.batch_index, chunk
+ )
else:
- await self._copy_chunk(client, target, stamped, ctx.batch_index, chunk)
-
- rows_written += batch.num_rows
+ await self._copy_chunk(client, target, stamped, run.run_uuid, ctx.batch_index, chunk)
+ rows_written += batch.num_rows
chunk += 1
return BatchWriteOutcome(rows_written=rows_written)
@@ -376,9 +397,9 @@ class SnowflakeDestinationWriter:
return NamedBytesIO(buffer.getvalue(), name)
async def _copy_chunk(
- self, client: SnowflakeClient, target: str, batch: pa.RecordBatch, batch_index: int, chunk: int
+ self, client: SnowflakeClient, target: str, batch: pa.RecordBatch, run_uuid: str, batch_index: int, chunk: int
) -> None:
- prefix = f"ph_{batch_index}_{chunk}"
+ prefix = stage_prefix(run_uuid, batch_index, chunk)
table = _stage_table(target, batch.schema, prefix)
# The stage path is derived from the batch index, so a retry of this chunk lands on the
@@ -397,16 +418,20 @@ class SnowflakeDestinationWriter:
target: str,
batch: pa.RecordBatch,
primary_keys: list[str],
+ run_uuid: str,
batch_index: int,
chunk: int,
- ) -> None:
+ ) -> int:
"""Upsert on the primary keys, staging the chunk in a scratch table first."""
+ # A `MERGE` whose source holds one key twice is rejected as a nondeterministic update,
+ # and it is rejected again on every retry.
+ batch = dedupe_merge_source(batch, primary_keys)
columns = list(batch.schema.names)
- stage_table = f"{target}__PH_MERGE_{batch_index}_{chunk}"
+ stage_table = merge_stage_name(target, run_uuid, batch_index, chunk)
await self._ensure_table(client, stage_table, batch.schema, with_batch_index=False)
try:
- await self._copy_chunk(client, stage_table, batch, batch_index, chunk)
+ await self._copy_chunk(client, stage_table, batch, run_uuid, batch_index, chunk)
on_clause = " AND ".join(
f"target.{quote_identifier(k)} = source.{quote_identifier(k)}" for k in primary_keys
@@ -427,6 +452,8 @@ class SnowflakeDestinationWriter:
finally:
await client.execute_async_query(f"DROP TABLE IF EXISTS {self._qualified(stage_table)}")
+ return batch.num_rows
+
async def finalize_run(self, ctx: DestinationRunContext) -> None:
"""Publish a full refresh by swapping the staging table into place."""
if not ctx.is_full_refresh:
@@ -455,6 +482,13 @@ class SnowflakeDestinationWriter:
await client.execute_async_query(
f"ALTER TABLE {self._qualified(staging)} DROP COLUMN IF EXISTS {quote_identifier(BATCH_INDEX_COLUMN)}"
)
+ # Stamp the run that published on the staging table, before it swaps into place.
+ # The comment survives the rename below, so the table is never visible under its
+ # live name without the marker already on it. Stamping after the rename would leave
+ # a crash window where the swap completes but the marker never lands, and a
+ # redelivered final batch would then rebuild staging from just that batch and
+ # publish over the table that already holds the complete data.
+ await self._set_comment(client, staging, published_marker(ctx.schema_id, ctx.run_uuid))
await client.execute_async_query(f"DROP TABLE IF EXISTS {self._qualified(ctx.table_name)}")
await client.execute_async_query(
f"ALTER TABLE {self._qualified(staging)} RENAME TO {self._qualified(ctx.table_name)}"