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): relink an orphaned table before a v3 sync starts (#115401)

Tom Owers45c8f5907c5b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
index b2fb23af79c5..6ed03eabc5ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_sync.py
@@ -307,6 +307,47 @@ def own_linked_table(schema: ExternalDataSchema, pipeline: ExternalDataSource) -
return None if table.name == companion_name != table_name else table
+def find_orphan_table(schema: ExternalDataSchema, source: ExternalDataSource) -> DataWarehouseTable | None:
+ """A live table with the schema's table name that no schema owns.
+
+ Two schema names can resolve to one table name, so the table must have no owning schema.
+ """
+ names = resolve_table_and_folder_names(schema.name, schema.resolved_s3_folder_name)
+ return DataWarehouseTable.objects.filter(
+ team_id=schema.team_id,
+ name=build_table_name(source, names.table_storage_name),
+ external_data_source_id=source.id,
+ deleted=False,
+ externaldataschema__isnull=True,
+ ).first()
+
+
+def relink_orphan_table(
+ schema: ExternalDataSchema, source: ExternalDataSource, logger: FilteringBoundLogger
+) -> DataWarehouseTable | None:
+ """Link an unlinked schema to its orphan table before extraction. Returns the schema's table.
+
+ The extract side treats a schema with no table as a first sync, and the loader then rebuilds
+ the table from empty. An orphan holds the rows of earlier runs, so the run must merge into it.
+ """
+ # A cdc_only schema links to its `_cdc` companion, so a table with the consolidated name is not its own.
+ if schema.table_id is not None or (schema.is_cdc and schema.cdc_table_mode == "cdc_only"):
+ return schema.table
+
+ orphan = find_orphan_table(schema, source)
+ if orphan is None:
+ return None
+
+ schema.table = orphan
+ schema.save(update_fields=["table", "updated_at"])
+ logger.warning(
+ "Relinked an orphaned table to its schema before extraction",
+ table_id=str(orphan.id),
+ schema_id=str(schema.id),
+ )
+ return orphan
+
+
async def validate_schema_and_update_table(
run_id: str,
team_id: int,
@@ -387,15 +428,8 @@ async def validate_schema_and_update_table(
if table_created is None:
# The ServerException handler below can leave a created table unlinked, so look for
- # that orphan before the skip decides no table exists. Two schema names can resolve
- # to one table name, so require that no schema owns the row.
- table_created = DataWarehouseTable.objects.filter(
- team_id=team_id,
- name=table_name,
- external_data_source_id=job.pipeline.id,
- deleted=False,
- externaldataschema__isnull=True,
- ).first()
+ # that orphan before the skip decides no table exists.
+ table_created = find_orphan_table(external_data_schema, job.pipeline)
if table_created is not None:
logger.debug(f"Found existing table {table_created.id} - reusing it for schema {_schema_id}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index a7989afb04e5..591bec74422a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -74,7 +74,10 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
repartition_import_hold_reason,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputs
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import (
+ PipelineInputs,
+ relink_orphan_table,
+)
from products.warehouse_sources.backend.temporal.data_imports.retry_limits import PROGRESSLESS_RESUMABLE_ATTEMPTS
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_tracking
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
@@ -801,7 +804,8 @@ def _get_models(
if source is None:
raise Exception("No source attached to job")
- table: DataWarehouseTable | None = schema.table
+ # The pipeline reads `schema.table` to decide if this run is a first sync, so an orphan is linked first.
+ table: DataWarehouseTable | None = relink_orphan_table(schema, source, LOGGER.bind(team_id=job.team_id))
return ImportJobModels(
job=job,
schema=schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
index 129a6ccf6cb2..b257f0fbc97c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py
@@ -32,6 +32,7 @@ from posthog.temporal.common.shutdown import WorkerShuttingDownError
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
from products.warehouse_sources.backend.temporal.data_imports.external_data_job import (
NEW_TABLE_NOT_READY_MESSAGE,
_transient_error_message,
@@ -41,6 +42,8 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core imp
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
SchemaColumnTypeChangedException,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_name
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline import PipelineV3
from products.warehouse_sources.backend.temporal.data_imports.retry_limits import PROGRESSLESS_RESUMABLE_ATTEMPTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
SimpleSource,
@@ -65,7 +68,7 @@ from products.warehouse_sources.backend.temporal.data_imports.workflow_activitie
_resolve_reset_pipeline,
import_data_activity_sync,
)
-from products.warehouse_sources.backend.types import IncrementalFieldType
+from products.warehouse_sources.backend.types import DataWarehouseTableFormat, IncrementalFieldType
class _FakeAsyncCM:
@@ -168,6 +171,108 @@ class TestGetModelsPrefetchesSource(BaseTest):
models.job.folder_path()
+_INCREMENTAL = ExternalDataSchema.SyncType.INCREMENTAL
+_CDC = ExternalDataSchema.SyncType.CDC
+_PIPELINE_V3 = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.pipeline"
+
+
+class TestGetModelsRelinksAnOrphanedTable(BaseTest):
+ def _first_ever_sync_stamp(self, models: module.ImportJobModels, *, reset_pipeline: bool) -> bool:
+ # The flag the producer stamps on every queued batch: True makes the loader overwrite on batch 0.
+ resource = mock.MagicMock(
+ primary_keys=["id"],
+ partition_count=None,
+ partition_size=None,
+ partition_keys=None,
+ partition_format=None,
+ partition_mode=None,
+ cdc_write_mode=None,
+ lanes=None,
+ webhook_only=False,
+ chunk_size=None,
+ chunk_size_bytes=None,
+ )
+ resource.name = "orders"
+ with (
+ mock.patch(f"{_PIPELINE_V3}.current_import_attempt", return_value=1),
+ mock.patch(f"{_PIPELINE_V3}.current_workflow_id", return_value="wf-1"),
+ mock.patch(f"{_PIPELINE_V3}.current_workflow_run_id", return_value="wfrun-1"),
+ mock.patch(f"{_PIPELINE_V3}.S3BatchWriter"),
+ mock.patch(f"{_PIPELINE_V3}.DeltaTableRef"),
+ mock.patch(f"{_PIPELINE_V3}.build_pipeline_sinks"),
+ mock.patch(f"{_PIPELINE_V3}.PostgresProducer") as producer_cls,
+ ):
+ PipelineV3(
+ source_response=resource,
+ logger=mock.MagicMock(),
+ job_id=str(models.job.id),
+ reset_pipeline=reset_pipeline,
+ shutdown_monitor=mock.MagicMock(),
+ resumable_source_manager=None,
+ models=models,
+ )
+ return producer_cls.call_args.kwargs["is_first_ever_sync"]
+
+ @parameterized.expand(
+ [
+ # (case, sync_type, sync_type_config, reset_pipeline, expected_table, expected_first_ever_sync)
+ ("linked_table_is_kept", _INCREMENTAL, {}, False, "linked", False),
+ ("orphan_is_relinked", _INCREMENTAL, {}, False, "orphan", False),
+ ("no_table_is_a_first_sync", _INCREMENTAL, {}, False, None, True),
+ # A cdc_only schema writes its `_cdc` companion, so the consolidated table is not its own.
+ ("cdc_only_schema_is_not_relinked", _CDC, {"cdc_table_mode": "cdc_only"}, False, None, True),
+ # A reset of a relinked schema is a reset of a linked table: the Delta delete in
+ # `handle_reset_or_full_refresh` makes the run rebuild (see TestTableRebuildAcrossAttempts).
+ ("reset_relinks_and_leaves_the_rebuild_to_the_delete", _INCREMENTAL, {}, True, "orphan", False),
+ ]
+ )
+ def test_relinks_an_orphan_before_the_pipeline_decides_on_a_first_sync(
+ self,
+ case: str,
+ sync_type: str,
+ sync_type_config: dict[str, Any],
+ reset_pipeline: bool,
+ expected_table: str | None,
+ expected_first_ever_sync: bool,
+ ) -> None:
+ source = ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()), connection_id=str(uuid.uuid4()), team=self.team, source_type="Postgres"
+ )
+ schema = ExternalDataSchema.objects.create(
+ name="orders",
+ team=self.team,
+ source=source,
+ sync_type=sync_type,
+ sync_type_config={"incremental_field": "updated_at", **sync_type_config},
+ )
+ tables: dict[str, DataWarehouseTable] = {}
+ if case != "no_table_is_a_first_sync":
+ tables["orphan"] = DataWarehouseTable.objects.create(
+ name=build_table_name(source, "orders"),
+ format=DataWarehouseTableFormat.DeltaS3Wrapper,
+ url_pattern="s3://bucket/orders/*.parquet",
+ team=self.team,
+ external_data_source=source,
+ row_count=1000,
+ )
+ if case == "linked_table_is_kept":
+ tables["linked"] = tables.pop("orphan")
+ schema.table = tables["linked"]
+ schema.save()
+ job = ExternalDataJob.objects.create(
+ team=self.team, pipeline=source, schema=schema, status=ExternalDataJob.Status.RUNNING
+ )
+
+ models = cast(Any, module._get_models).func(str(job.id))
+
+ expected = tables[expected_table] if expected_table else None
+ assert models.table == expected
+ assert models.schema.table == expected
+ schema.refresh_from_db()
+ assert schema.table == expected
+ assert self._first_ever_sync_stamp(models, reset_pipeline=reset_pipeline) is expected_first_ever_sync
+
+
class TestSchemaSyncHistory(BaseTest):
@parameterized.expand(
[