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.

feat(data-warehouse): link existing sources to the warehouse destination (#111854)

Tom Owers51496d35724e
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 94a96f1d8c1d..8a70f4d19e50 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -22,6 +22,7 @@ from products.warehouse_sources.backend.models.external_data_destination import
ExternalDataDestination,
ExternalDataSchemaDestination,
ExternalDataSourceDestination,
+ get_or_create_warehouse_destination,
resolve_destinations,
)
from products.warehouse_sources.backend.models.external_data_job import (
@@ -113,6 +114,7 @@ __all__ = [
"get_latest_run_if_exists",
"latest_completed_job_prefetch",
"get_or_create_datawarehouse_credential",
+ "get_or_create_warehouse_destination",
"clickhouse_column_to_dwh_column",
"clickhouse_columns_to_dwh_columns",
"motherduck_column_to_dwh_column",
diff --git a/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_destinations.py b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_destinations.py
new file mode 100644
index 000000000000..172d54a39936
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/backfill_warehouse_source_destinations.py
@@ -0,0 +1,163 @@
+"""Add explicit warehouse links to sources created before destination links existed.
+
+New sources now receive a link during setup. This command covers older sources so their
+destination set no longer depends on the implicit fallback during normal operation.
+"""
+
+from itertools import groupby, islice
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+
+import structlog
+
+from products.warehouse_sources.backend.models.external_data_destination import (
+ ExternalDataDestination,
+ ExternalDataSourceDestination,
+ get_or_create_warehouse_destination,
+)
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
+logger = structlog.get_logger(__name__)
+
+BATCH_SIZE = 500
+
+
+class Command(BaseCommand):
+ help = (
+ "Link sources without destinations to their team's PostHog warehouse. "
+ "Previews by default; pass --live-run to persist."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, default=None, help="Only process sources belonging to this team.")
+ parser.add_argument("--limit", type=int, default=None, help="Only scan the first N sources.")
+ parser.add_argument(
+ "--live-run", action="store_true", help="Create links. Without this the command only reports what it found."
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int | None = options["team_id"]
+ limit: int | None = options["limit"]
+ live_run: bool = options["live_run"]
+ if limit is not None and limit < 0:
+ raise CommandError("--limit must be zero or greater")
+
+ # Ordered by team so `groupby` below sees each team's sources together, and deleted
+ # sources are left out: one never syncs again, so a link for it is noise.
+ # `select_related(None)` clears the default manager's join, which `only()` cannot defer
+ # past — without it Django refuses the query.
+ sources = (
+ ExternalDataSource.objects.exclude(deleted=True)
+ .select_related(None)
+ .only("id", "team_id")
+ .order_by("team_id", "id")
+ )
+ if team_id is not None:
+ sources = sources.filter(team_id=team_id)
+ if limit is not None:
+ sources = sources[:limit]
+
+ scanned = 0
+ skipped = 0
+ links = 0
+ failures = 0
+ teams: set[int] = set()
+ destination_teams: set[int] = set()
+ source_iterator = sources.iterator(chunk_size=BATCH_SIZE)
+
+ while batch := list(islice(source_iterator, BATCH_SIZE)):
+ scanned += len(batch)
+ for current_team_id, team_sources in groupby(batch, key=lambda source: source.team_id):
+ grouped_sources = list(team_sources)
+ scoped_links = ExternalDataSourceDestination.objects.for_team(current_team_id)
+ missing = grouped_sources
+ try:
+ linked_ids = set(
+ scoped_links.filter(source_id__in=[source.pk for source in grouped_sources]).values_list(
+ "source_id", flat=True
+ )
+ )
+ missing = [source for source in grouped_sources if source.pk not in linked_ids]
+ skipped += len(grouped_sources) - len(missing)
+ if not missing:
+ continue
+
+ teams.add(current_team_id)
+ destination_exists = (
+ ExternalDataDestination.objects.for_team(current_team_id)
+ .filter(type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE, deleted=False)
+ .exists()
+ )
+ if not live_run:
+ links += len(missing)
+ if not destination_exists:
+ destination_teams.add(current_team_id)
+ continue
+
+ destination = get_or_create_warehouse_destination(current_team_id)
+ created = 0
+ failed = 0
+ skipped_during_run = 0
+ for source in missing:
+ # One savepoint per source, so a source that cannot be linked costs only
+ # itself. A transaction around the whole group would hold its locks for
+ # as long as the group takes.
+ try:
+ with transaction.atomic():
+ # Serialize with destination-set edits before checking for links.
+ ExternalDataSource.objects.select_for_update(of=("self",)).get(pk=source.pk)
+ if scoped_links.filter(source_id=source.pk).exists():
+ skipped_during_run += 1
+ continue
+ ExternalDataSourceDestination.objects.for_team(current_team_id).create(
+ team_id=current_team_id,
+ source=source,
+ destination=destination,
+ enabled=True,
+ )
+ created += 1
+ except Exception as error:
+ failed += 1
+ logger.exception(
+ "Could not link warehouse source",
+ source_id=str(source.pk),
+ team_id=current_team_id,
+ error=str(error),
+ )
+ links += created
+ failures += failed
+ skipped += skipped_during_run
+ if not destination_exists:
+ destination_teams.add(current_team_id)
+ except Exception as error:
+ failures += len(missing)
+ logger.exception(
+ "Could not process warehouse source group",
+ team_id=current_team_id,
+ error=str(error),
+ )
+
+ logger.info(
+ "Warehouse source destination backfill progress",
+ scanned=scanned,
+ skipped=skipped,
+ links=links,
+ teams=len(teams),
+ failures=failures,
+ )
+
+ link_label = "links created" if live_run else "links would create"
+ destination_label = (
+ "warehouse destination rows created" if live_run else "warehouse destination rows would create"
+ )
+ self.stdout.write(
+ f"sources scanned: {scanned}, sources already linked (skipped): {skipped}, "
+ f"{link_label}: {links}, teams touched: {len(teams)}, {destination_label}: {len(destination_teams)}, "
+ f"failures: {failures}"
+ )
+ if not live_run:
+ self.stdout.write("preview only, nothing written. Re-run with --live-run to persist.")
+ if failures:
+ raise CommandError(f"{failures} source(s) could not be linked; see the errors above and re-run")
diff --git a/products/warehouse_sources/backend/presentation/views/destination_links.py b/products/warehouse_sources/backend/presentation/views/destination_links.py
index 210f071864b2..1d6e16816a0c 100644
--- a/products/warehouse_sources/backend/presentation/views/destination_links.py
+++ b/products/warehouse_sources/backend/presentation/views/destination_links.py
@@ -14,6 +14,7 @@ from rest_framework.exceptions import ValidationError
from products.warehouse_sources.backend.facade.models import (
ExternalDataDestination,
ExternalDataSchemaDestination,
+ ExternalDataSource,
ExternalDataSourceDestination,
)
@@ -86,8 +87,10 @@ def set_source_destinations(*, team_id: int, source_id: Any, destination_ids: li
destinations = _resolve_destinations(team_id, destination_ids)
# Atomic because the delete and the creates are one edit: a failure between them would leave
- # the source with a partial set, and every table without an override would sync to it.
+ # the source with a partial set, and every table without an override would sync to it. Locking
+ # the source also serializes this edit with the destination backfill.
with transaction.atomic():
+ ExternalDataSource.objects.select_for_update(of=("self",)).get(pk=source_id, team_id=team_id)
ExternalDataSourceDestination.objects.for_team(team_id).filter(source_id=source_id).delete()
for destination in destinations:
ExternalDataSourceDestination.objects.for_team(team_id).create(
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
index b46931e06e66..89a5f97dc738 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/source_setup.py
@@ -44,6 +44,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSource,
PendingSourceCredential,
+ get_or_create_warehouse_destination,
sync_old_schemas_with_new_schemas,
)
from products.warehouse_sources.backend.facade.source_management import (
@@ -1724,21 +1725,22 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# Attach destinations before any schedule starts. Extraction snapshots the set onto the
# run, so a source whose destinations arrive after its first sync began writes that run
# to the warehouse alone, and reaching the others costs a full resync.
- if destination_ids:
- try:
- set_source_destinations(
- team_id=self.team_id,
- source_id=new_source_model.pk,
- destination_ids=destination_ids,
- )
- except Exception as e:
- # The source is already created and its tables are configured. Losing that over a
- # destination set the user can still fix on the Destinations tab is the worse trade.
- base.logger.exception(
- "Could not attach destinations to a new source",
- exc_info=e,
- source_id=new_source_model.pk,
- )
+ # Write the default set so new sources do not depend on the implicit fallback.
+ try:
+ selected_destination_ids = destination_ids or [get_or_create_warehouse_destination(self.team_id).pk]
+ set_source_destinations(
+ team_id=self.team_id,
+ source_id=new_source_model.pk,
+ destination_ids=selected_destination_ids,
+ )
+ except Exception as e:
+ # The source is already created and its tables are configured. Losing that over a
+ # destination set the user can still fix on the Destinations tab is the worse trade.
+ base.logger.exception(
+ "Could not attach destinations to a new source",
+ exc_info=e,
+ source_id=new_source_model.pk,
+ )
# Create all sync schedules over a single shared Temporal connection. Creating them
# one call at a time reconnects to Temporal on every iteration, which does not scale
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
index 33bd274048c8..fb0d47c45182 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py
@@ -439,7 +439,7 @@ class TestExternalDataSource(APIBaseTest):
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
return_value=(True, None),
)
- def test_a_source_created_without_destinations_is_unchanged(self, _mock_validate):
+ def test_a_source_created_without_destinations_is_linked_to_the_warehouse(self, _mock_validate):
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",
data={
@@ -453,11 +453,9 @@ class TestExternalDataSource(APIBaseTest):
)
assert response.status_code == status.HTTP_201_CREATED, response.json()
- assert (
- not ExternalDataSourceDestination.objects.for_team(self.team.pk)
- .filter(source_id=response.json()["id"])
- .exists()
- )
+ link = ExternalDataSourceDestination.objects.for_team(self.team.pk).get(source_id=response.json()["id"])
+ assert link.enabled is True
+ assert link.destination.type == ExternalDataDestination.Type.POSTHOG_WAREHOUSE
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source.StripeSource.validate_credentials",
diff --git a/products/warehouse_sources/backend/tests/test_external_data_destination.py b/products/warehouse_sources/backend/tests/test_external_data_destination.py
index c3ee4f194c9f..41996f61f1b3 100644
--- a/products/warehouse_sources/backend/tests/test_external_data_destination.py
+++ b/products/warehouse_sources/backend/tests/test_external_data_destination.py
@@ -1,4 +1,10 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from parameterized import parameterized
from posthog.models.team import Team
@@ -98,3 +104,102 @@ class TestGetOrCreateWarehouseDestination(BaseTest):
theirs = get_or_create_warehouse_destination(other_team.pk)
assert mine.id != theirs.id
+
+
+class TestBackfillWarehouseSourceDestinations(BaseTest):
+ def _source(self, source_id: str, team: Team | None = None) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team or self.team,
+ source_id=source_id,
+ connection_id=f"conn-{source_id}",
+ status="Running",
+ source_type=ExternalDataSourceType.STRIPE,
+ )
+
+ @parameterized.expand(
+ [
+ ("new_destination_first_run", 1, False),
+ ("new_destination_second_run", 2, False),
+ ("existing_destination_first_run", 1, True),
+ ("existing_destination_second_run", 2, True),
+ ]
+ )
+ def test_a_source_without_links_gains_one_for_the_warehouse(
+ self, _case: str, runs: int, warehouse_exists: bool
+ ) -> None:
+ source = self._source("src")
+ existing_destination = get_or_create_warehouse_destination(self.team.pk) if warehouse_exists else None
+
+ for _ in range(runs):
+ call_command("backfill_warehouse_source_destinations", live_run=True)
+
+ links = list(ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source))
+ assert len(links) == 1
+ assert links[0].enabled is True
+ assert links[0].destination.type == ExternalDataDestination.Type.POSTHOG_WAREHOUSE
+ if existing_destination:
+ assert links[0].destination_id == existing_destination.pk
+ assert (
+ ExternalDataDestination.objects.for_team(self.team.pk)
+ .filter(type=ExternalDataDestination.Type.POSTHOG_WAREHOUSE, deleted=False)
+ .count()
+ == 1
+ )
+
+ def test_a_source_with_an_external_link_is_unchanged(self) -> None:
+ source = self._source("src")
+ external_destination = ExternalDataDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, type=ExternalDataDestination.Type.REDSHIFT, name="Redshift"
+ )
+ link = ExternalDataSourceDestination.objects.for_team(self.team.pk).create(
+ team_id=self.team.pk, source=source, destination=external_destination, enabled=False
+ )
+
+ call_command("backfill_warehouse_source_destinations", live_run=True)
+
+ links = list(ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source))
+ assert len(links) == 1
+ assert links[0].pk == link.pk
+ assert links[0].destination_id == external_destination.pk
+ assert links[0].enabled is False
+ assert ExternalDataDestination.objects.for_team(self.team.pk).count() == 1
+
+ def test_preview_creates_no_links_or_warehouse_destination(self) -> None:
+ source = self._source("src")
+
+ call_command("backfill_warehouse_source_destinations")
+
+ assert not ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source).exists()
+ assert not ExternalDataDestination.objects.for_team(self.team.pk).exists()
+
+ def test_team_id_only_backfills_that_teams_sources(self) -> None:
+ source = self._source("mine")
+ other_team = Team.objects.create(organization=self.organization, name="Other team")
+ other_source = self._source("other", team=other_team)
+
+ call_command("backfill_warehouse_source_destinations", team_id=self.team.pk, live_run=True)
+
+ assert ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source).count() == 1
+ assert not ExternalDataSourceDestination.objects.for_team(other_team.pk).filter(source=other_source).exists()
+ assert not ExternalDataDestination.objects.for_team(other_team.pk).exists()
+
+ def test_a_deleted_source_is_left_alone(self) -> None:
+ # A deleted source never syncs again, so a link for it is noise the backfill should not add.
+ source = self._source("deleted-source")
+ source.deleted = True
+ source.save(update_fields=["deleted"])
+
+ call_command("backfill_warehouse_source_destinations", "--live-run")
+
+ assert not ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source_id=source.pk).exists()
+
+ def test_a_failed_link_makes_the_command_fail(self) -> None:
+ source = self._source("src")
+
+ with (
+ patch.object(ExternalDataSourceDestination, "save", side_effect=RuntimeError("write failed")),
+ self.assertRaisesMessage(CommandError, "1 source(s) could not be linked"),
+ ):
+ call_command("backfill_warehouse_source_destinations", "--live-run")
+
+ assert not ExternalDataSourceDestination.objects.for_team(self.team.pk).filter(source=source).exists()