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): remove the credentials row when a source create fails (#128421)

Tom Owersc894cb4afd43
diff --git a/products/warehouse_sources/backend/facade/source_inputs.py b/products/warehouse_sources/backend/facade/source_inputs.py
index 99480d0d082c..6fd7cb7b0393 100644
--- a/products/warehouse_sources/backend/facade/source_inputs.py
+++ b/products/warehouse_sources/backend/facade/source_inputs.py
@@ -22,6 +22,7 @@ class SourceInputsStore:
assign = staticmethod(_store.SourceInputsStore.assign)
save = staticmethod(_store.SourceInputsStore.save)
create = staticmethod(_store.SourceInputsStore.create)
+ discard_created = staticmethod(_store.SourceInputsStore.discard_created)
update_runtime = staticmethod(_store.SourceInputsStore.update_runtime)
update_oauth_inputs = staticmethod(_store.SourceInputsStore.update_oauth_inputs)
aload = staticmethod(_store.SourceInputsStore.aload)
diff --git a/products/warehouse_sources/backend/logic/source_credentials.py b/products/warehouse_sources/backend/logic/source_credentials.py
index 574e8442ae7b..0fe3ec12bc8f 100644
--- a/products/warehouse_sources/backend/logic/source_credentials.py
+++ b/products/warehouse_sources/backend/logic/source_credentials.py
@@ -12,7 +12,8 @@ only marked rows of the kind and auth type.
Several sources (and later other products) can use one row. An edit of a shared row needs a
confirmation, and an edit that changes where the credentials connect makes a new row. The store
-never deletes a row: a row that nothing uses stays in the integrations list.
+never deletes a row that a source used: a row that nothing uses stays in the integrations list. The
+one exception is `discard`, for the row of a source whose create did not finish.
No method returns a queryset or a model, so a later credentials service can sit behind the same
methods without a change to the callers.
@@ -32,6 +33,7 @@ from posthog.helpers.encrypted_fields import FERNET_TOKEN_PREFIX, EncryptedJSONF
from posthog.integrations import (
SOURCE_MARKER_CONFIG_KEY,
AuthAccessor,
+ IntegrationInUse,
IntegrationNotFound,
IntegrationReference,
IntegrationUsage,
@@ -241,6 +243,23 @@ class WarehouseSourceCredentialsStore:
logger.info("warehouse_source_credentials_orphaned", team_id=source.team_id, integration_id=pk)
return True
+ @staticmethod
+ def discard(source: ExternalDataSource) -> bool:
+ """Delete the row of a source whose create did not finish. Returns True when it deleted the row.
+
+ Call it after the source row is gone. The row stays when another object uses it. The row of an
+ OAuth source is out of scope, so it always stays.
+ """
+ pk = _pk(source)
+ rows = _accessor_or_none(source)
+ if pk is None or rows is None:
+ return False
+ try:
+ rows.delete(source.team_id, pk)
+ except (IntegrationNotFound, IntegrationInUse):
+ return False
+ return True
+
@staticmethod
async def aget(source: ExternalDataSource) -> dict[str, Any] | None:
return await database_sync_to_async_pool(WarehouseSourceCredentialsStore.get)(source)
diff --git a/products/warehouse_sources/backend/logic/source_inputs.py b/products/warehouse_sources/backend/logic/source_inputs.py
index 186c94bb51f4..7a4c67a3e6b6 100644
--- a/products/warehouse_sources/backend/logic/source_inputs.py
+++ b/products/warehouse_sources/backend/logic/source_inputs.py
@@ -17,6 +17,7 @@ from posthog.sync import database_sync_to_async_pool
from products.warehouse_sources.backend.facade.contracts import SharedCredentialsEdit, UnreadableSourceInputsError
from products.warehouse_sources.backend.logic.credential_auth_types import has_typed_in_credentials
+from products.warehouse_sources.backend.logic.source_credentials import WarehouseSourceCredentialsStore
from products.warehouse_sources.backend.logic.source_credentials_rollout import (
assign_credentials_reference,
shadow_compare,
@@ -144,6 +145,17 @@ class SourceInputsStore:
source.save(force_insert=True)
return source
+ @staticmethod
+ def discard_created(source: ExternalDataSource) -> None:
+ """Delete a source that `create` made when a later step of the same create fails.
+
+ One transaction deletes the source and its credentials row. The row stays when another object
+ uses it. Do not use this for a source that was in use: the store keeps the credentials rows of those.
+ """
+ with transaction.atomic():
+ source.delete()
+ WarehouseSourceCredentialsStore.discard(source)
+
@staticmethod
def update_runtime(
source: ExternalDataSource,
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 a67fd4d57d47..df5401d30236 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
@@ -86,6 +86,7 @@ from products.warehouse_sources.backend.facade.source_management import (
pin_history_naming,
reserved_column_collisions,
reserved_column_names,
+ source_type_supports_cdc,
sql_schema_metadata,
validate_and_coerce_row_filters,
)
@@ -1317,45 +1318,22 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
return error_response or Response(status=status.HTTP_400_BAD_REQUEST)
source_config = validated_config
- new_source_model = SourceInputsStore.create(
- source_id=str(uuid.uuid4()),
- connection_id=str(uuid.uuid4()),
- destination_id=str(uuid.uuid4()),
- created_by=request.user if isinstance(request.user, User) else None,
- created_via=created_via,
- team=self.team,
- status="Running",
- source_type=source_type_model,
- api_version=source.default_version,
- inputs=source.serialize_config(source_config),
- prefix=prefix,
- description=description,
- access_method=access_method,
- direct_query_enabled=direct_query_enabled,
- )
-
- # Post-create hook (Custom claims its bound OAuth2 integration row here). No-op otherwise.
- source.on_source_created(new_source_model, self.team_id)
-
- # CDC: gate per-source-type adapter availability up front so downstream blocks
- # can `if cdc_enabled` without repeating the source-type check.
- try:
- cdc_adapter: CDCSourceAdapter | None = get_cdc_adapter(new_source_model)
- except ValueError:
- cdc_adapter = None
+ api_version = source.default_version
cdc_enabled = (
- payload.get("cdc_enabled", False) and cdc_adapter is not None and base.is_cdc_enabled_for_team(self.team)
+ payload.get("cdc_enabled", False)
+ and source_type_supports_cdc(source_type_model)
+ and base.is_cdc_enabled_for_team(self.team)
)
+ # Schema discovery and the payload checks run before the insert, so a failure leaves no source and
+ # no credentials row. Discovery opens its own connection, so it must not run in a transaction.
try:
source_schemas = source.get_schemas(
- source_config, self.team_id, api_version=source.resolve_api_version(new_source_model.api_version)
+ source_config, self.team_id, api_version=source.resolve_api_version(api_version)
)
except NotImplementedError:
# Source doesn't implement schema discovery (e.g. an unreleased scaffold the UI hides).
- # Roll back the row just created so a caller can't accumulate orphaned sources, and return
- # a clean 400 instead of the uncaught 500 this would otherwise raise. Mirrors `setup`.
- new_source_model.delete()
+ # Return a clean 400 instead of the uncaught 500 this would otherwise raise. Mirrors `setup`.
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": helpers._source_unavailable_message(source_type)},
@@ -1364,31 +1342,14 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# `get_schemas` opens its own connection, so credentials validated above can still fail
# here (e.g. a BigQuery service account key rotated/revoked in between). Classify via
# the source's own non-retryable-error map, same as `database_schema` and
- # `refresh_schemas`, and roll back the row so a source that can't discover its schema
- # doesn't linger half-created.
+ # `refresh_schemas`.
error_message, is_expected_source_error = helpers._classify_refresh_schemas_error(source, e)
if not is_expected_source_error:
- base.capture_exception(
- e,
- {
- "source_type": source_type,
- "team_id": self.team_id,
- "source_id": str(new_source_model.id),
- },
- )
- new_source_model.delete()
+ base.capture_exception(e, {"source_type": source_type, "team_id": self.team_id})
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": error_message},
)
- if is_direct_query:
- new_source_model.connection_metadata = helpers.get_direct_connection_metadata(
- source_impl=source,
- source_config=source_config,
- team_id=self.team_id,
- source_model=new_source_model,
- )
- new_source_model.save(update_fields=["connection_metadata", "updated_at"])
source_schemas_by_name = {schema.name: schema for schema in source_schemas}
schema_names = [schema.name for schema in source_schemas]
source_config_dict = source_config.to_dict()
@@ -1402,7 +1363,6 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# know. Discovery ran above, so the defaults cost nothing extra here.
payload_schemas = payload.get("schemas")
if payload_schemas is not None and not isinstance(payload_schemas, list):
- new_source_model.delete()
return Response(
data={"message": "The 'schemas' field must be a list of the tables to sync."},
status=status.HTTP_400_BAD_REQUEST,
@@ -1412,7 +1372,6 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# Return 400 if we get any schema names that don't exist in our source
if any(schema.get("name") not in schema_names for schema in payload_schemas):
- new_source_model.delete()
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Schemas given do not exist in source"},
@@ -1429,7 +1388,6 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
}
)
if invalid_sync_types:
- new_source_model.delete()
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1448,7 +1406,6 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
}
)
if webhook_unsupported:
- new_source_model.delete()
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1470,7 +1427,6 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
}
)
if cdc_schemas_in_payload:
- new_source_model.delete()
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1481,6 +1437,37 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
},
)
+ new_source_model = SourceInputsStore.create(
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ created_by=request.user if isinstance(request.user, User) else None,
+ created_via=created_via,
+ team=self.team,
+ status="Running",
+ source_type=source_type_model,
+ api_version=api_version,
+ inputs=source.serialize_config(source_config),
+ prefix=prefix,
+ description=description,
+ access_method=access_method,
+ direct_query_enabled=direct_query_enabled,
+ )
+
+ # Post-create hook (Custom claims its bound OAuth2 integration row here). No-op otherwise.
+ source.on_source_created(new_source_model, self.team_id)
+
+ cdc_adapter: CDCSourceAdapter | None = get_cdc_adapter(new_source_model) if cdc_enabled else None
+
+ if is_direct_query:
+ new_source_model.connection_metadata = helpers.get_direct_connection_metadata(
+ source_impl=source,
+ source_config=source_config,
+ team_id=self.team_id,
+ source_model=new_source_model,
+ )
+ new_source_model.save(update_fields=["connection_metadata", "updated_at"])
+
active_schemas: list[ExternalDataSchema] = []
history_schemas: list[ExternalDataSchema] = []
@@ -1521,7 +1508,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# requires/refuses SSL. Surface it as a 400, but don't capture it — these are
# user/upstream connection problems, not bugs in our code, and capturing every
# one floods error tracking. Mirrors the CDC-prerequisite handlers below.
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": f"Could not connect to your database to set up change data capture: {e}"},
@@ -1540,7 +1527,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
}
)
if tables_missing_pk:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1571,7 +1558,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
f"{table} ({', '.join(columns)})" for table, columns in reserved_columns_by_table.items() if columns
)
if tables_with_reserved_column:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1600,7 +1587,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
new_source_model, new_history, history_names, synced_names
)
if tables_with_taken_history_name:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1620,7 +1607,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
assert cdc_adapter is not None # narrowed by `cdc_enabled`
cdc_error = self._setup_cdc_resources(cdc_adapter, new_source_model, payload)
if cdc_error is not None:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": cdc_error},
@@ -1647,14 +1634,14 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
)
if should_sync and requires_incremental_fields and incremental_field is None:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Incremental schemas given do not have an incremental field set"},
)
if should_sync and requires_incremental_fields and incremental_field_type is None:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": "Incremental schemas given do not have an incremental field type set"},
@@ -1680,7 +1667,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
and not source_schema.detected_primary_keys # type: ignore[union-attr]
and not has_id_column
):
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
data={
"message": f"Table '{schema_name}' has no primary key to sync incrementally on. "
@@ -1732,7 +1719,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# Only sources that push filters into their query (SQL WHERE) can honor them — a
# saved-but-ignored filter would silently sync unfiltered rows.
if not source.supports_row_filters:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1743,7 +1730,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
if reason := unsupported_row_filter_reason(
is_direct_query=new_source_model.is_direct_query, is_cdc=sync_type == "cdc"
):
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": f"Row filter not allowed for schema '{schema_name}': {reason}"},
@@ -1753,7 +1740,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
row_filters, schema_metadata, source.row_filter_columns_for_schema(schema_name)
)
except RowFilterValidationError as e:
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={"message": f"Invalid row filter for schema '{schema_name}': {e}"},
@@ -1790,7 +1777,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# bool is an int subclass — exclude it so true/false aren't treated as 1/0.
is_valid_int = isinstance(lookback_seconds, int) and not isinstance(lookback_seconds, bool)
if not is_valid_int or not (0 <= lookback_seconds <= 5_184_000):
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(
status=status.HTTP_400_BAD_REQUEST,
data={
@@ -1875,7 +1862,7 @@ class ExternalDataSourceSetupMixin(base.ExternalDataSourceViewSetBase):
# A hard delete leaves no source row for the orphan-slot sweeper to find, so
# drop the slot and publication created above before deleting the source.
cdc_adapter.cleanup_resources(new_source_model)
- new_source_model.delete()
+ SourceInputsStore.discard_created(new_source_model)
return Response(status=status.HTTP_400_BAD_REQUEST, data={"message": message})
if direct_engine_adapter is not None and is_direct_query and should_sync:
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 b428f886f44a..724f3d3ccf05 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
@@ -24,7 +24,7 @@ from rest_framework.exceptions import PermissionDenied, ValidationError
from sshtunnel import BaseSSHTunnelForwarderError
from posthog.constants import AvailableFeature
-from posthog.integrations import IntegrationManager, IntegrationNotFound
+from posthog.integrations import IntegrationManager, IntegrationNotFound, IntegrationReference
from posthog.models import OrganizationMembership, Team
from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
@@ -15790,3 +15790,143 @@ class TestSourceUpdateCredentialsRow(APIBaseTest):
assert confirmed.status_code == status.HTTP_403_FORBIDDEN, confirmed.json()
row = IntegrationManager.source("postgresql").credentials.get(self.team.pk, int(self._reference(source)))
assert row.sensitive_config["fields"]["password"] == "fake-password"
+
+
+_VIEWS = "products.warehouse_sources.backend.presentation.views.external_data_source"
+
+
[email protected](PostgresSource, "validate_credentials_for_access_method", return_value=(True, None))
+@patch(f"{_VIEWS}.base.capture_exception")
+@patch(f"{_VIEWS}.base.sync_discover_schemas_schedule")
+@patch(f"{_VIEWS}.base.bulk_create_external_data_job_schedules", return_value=[])
+class TestCreateSourceCredentialsRow(APIBaseTest):
+ CONNECTION: dict[str, Any] = {
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "app",
+ "user": "reader",
+ "password": "fake-password",
+ "schema": "public",
+ }
+
+ def _discovered(self) -> list[SourceSchema]:
+ return [
+ SourceSchema(
+ name="orders",
+ supports_incremental=True,
+ supports_append=True,
+ supports_cdc=True,
+ columns=[("id", "integer", False), ("updated_at", "timestamp", False)],
+ foreign_keys=[],
+ detected_primary_keys=["id"],
+ source_schema="public",
+ source_table_name="orders",
+ )
+ ]
+
+ def _post(self, payload: dict[str, Any], *, flag_on: bool = True, get_schemas_error: Exception | None = None):
+ reset_credentials_rollout_caches()
+ self.addCleanup(reset_credentials_rollout_caches)
+ with (
+ patch.object(schema_flags.posthoganalytics, "feature_enabled", return_value=flag_on),
+ patch.object(PostgresSource, "get_schemas", return_value=self._discovered(), side_effect=get_schemas_error),
+ patch(f"{_VIEWS}.base.is_cdc_enabled_for_team", return_value=True),
+ patch(f"{_VIEWS}.base.cdc_pg_connection"),
+ patch(f"{_VIEWS}.base.get_primary_key_columns", return_value={"orders": ["id"]}),
+ patch.object(ExternalDataSourceViewSet, "_setup_cdc_resources", return_value="Could not create the slot"),
+ ):
+ return self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={"source_type": "Postgres", "payload": {**self.CONNECTION, **payload}},
+ format="json",
+ )
+
+ def _credentials_rows(self) -> list[Any]:
+ return IntegrationManager.source("postgresql").credentials.list(self.team.pk)
+
+ @parameterized.expand(
+ [
+ ("discovery_fails", {}, True, RuntimeError("connection reset")),
+ ("schemas_not_a_list", {"schemas": "orders"}, True, None),
+ ("unknown_table", {"schemas": [{"name": "missing", "should_sync": True}]}, True, None),
+ (
+ "unknown_sync_type",
+ {"schemas": [{"name": "orders", "should_sync": True, "sync_type": "bogus"}]},
+ True,
+ None,
+ ),
+ (
+ "webhook_unsupported",
+ {"schemas": [{"name": "orders", "should_sync": True, "sync_type": "webhook"}]},
+ True,
+ None,
+ ),
+ (
+ "cdc_not_enabled",
+ {"schemas": [{"name": "orders", "should_sync": True, "sync_type": "cdc"}]},
+ True,
+ None,
+ ),
+ (
+ "cdc_setup_fails_after_insert",
+ {"cdc_enabled": True, "schemas": [{"name": "orders", "should_sync": True, "sync_type": "cdc"}]},
+ True,
+ None,
+ ),
+ (
+ "incremental_field_missing_after_insert",
+ {"schemas": [{"name": "orders", "should_sync": True, "sync_type": "incremental"}]},
+ True,
+ None,
+ ),
+ (
+ "lookback_out_of_range_after_insert",
+ {
+ "schemas": [
+ {
+ "name": "orders",
+ "should_sync": True,
+ "sync_type": "incremental",
+ "incremental_field": "updated_at",
+ "incremental_field_type": "timestamp",
+ "incremental_field_lookback_seconds": 10**9,
+ }
+ ]
+ },
+ True,
+ None,
+ ),
+ (
+ "flag_off_failure_after_insert",
+ {"schemas": [{"name": "orders", "should_sync": True, "sync_type": "incremental"}]},
+ False,
+ None,
+ ),
+ ]
+ )
+ def test_failed_create_leaves_no_source_and_no_credentials_row(
+ self,
+ _bulk_create_schedules: MagicMock,
+ _discover_schedule: MagicMock,
+ _capture: MagicMock,
+ _validate: MagicMock,
+ _name: str,
+ payload: dict[str, Any],
+ flag_on: bool,
+ get_schemas_error: Exception | None,
+ ) -> None:
+ response = self._post(payload, flag_on=flag_on, get_schemas_error=get_schemas_error)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert not ExternalDataSource.objects.filter(team_id=self.team.pk).exists()
+ assert self._credentials_rows() == []
+
+ def test_successful_create_keeps_one_credentials_row_that_the_source_uses(self, *_mocks: MagicMock) -> None:
+ response = self._post({"schemas": [{"name": "orders", "should_sync": True, "sync_type": "full_refresh"}]})
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ rows = self._credentials_rows()
+ assert len(rows) == 1
+ source = ExternalDataSource.objects.get(team_id=self.team.pk)
+ assert source.credentials_integration_id == str(IntegrationReference.from_legacy_id(rows[0].id))
+ assert rows[0].sensitive_config["fields"]["password"] == "fake-password"
diff --git a/products/warehouse_sources/backend/tests/test_source_credentials.py b/products/warehouse_sources/backend/tests/test_source_credentials.py
index a08da9109b63..c7b978266cf5 100644
--- a/products/warehouse_sources/backend/tests/test_source_credentials.py
+++ b/products/warehouse_sources/backend/tests/test_source_credentials.py
@@ -603,6 +603,36 @@ class TestWarehouseSourceCredentialsStore(BaseTest):
source.credentials_integration_id = None
assert WarehouseSourceCredentialsStore.release(source) is False
+ @parameterized.expand(
+ [
+ ("unused", False, 0),
+ ("still_used_by_another_source", True, 1),
+ ]
+ )
+ def test_discard_created_deletes_the_source_and_its_unused_row(
+ self, _name: str, shared: bool, rows_left: int
+ ) -> None:
+ source = self._source()
+ source_pk = source.pk
+ pk = self._create(source, PG_FIELDS)
+ if shared:
+ self._referencing(pk)
+
+ SourceInputsStore.discard_created(source)
+
+ assert not ExternalDataSource.objects.filter(pk=source_pk).exists()
+ assert len(IntegrationManager.source("postgresql").credentials.list(self.team.id)) == rows_left
+
+ def test_discard_created_keeps_a_row_out_of_the_store_scope(self) -> None:
+ source = self._source()
+ oauth_row = IntegrationManager.hubspot.oauth.create(self.team.id, external_id="H1", config={})
+ source.credentials_integration_id = str(oauth_row.id)
+ source.save()
+
+ SourceInputsStore.discard_created(source)
+
+ assert IntegrationManager.hubspot.oauth.get(self.team.id, oauth_row.id).id == oauth_row.id
+
@patch("products.warehouse_sources.backend.models.external_data_source.capture_exception")
def test_soft_delete_keeps_the_row_and_survives_store_failure(self, capture: Any) -> None:
deleted, failing, without_row = self._source(), self._source(), self._source()