: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): delete hosted upload file on self-managed table delete (#73504)
Daniel RC9bae05659350
diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.pyindex beef791ebeee..f472d52a0faa 100644--- a/products/data_warehouse/backend/presentation/views/table.py+++ b/products/data_warehouse/backend/presentation/views/table.py@@ -31,6 +31,7 @@ from products.warehouse_sources.backend.facade.api import (SUPPORTED_FILE_FORMATS,build_file_upload_s3_path,build_file_upload_url_pattern,+ hosted_upload_s3_path,)from products.warehouse_sources.backend.facade.hogql import (CLICKHOUSE_HOGQL_MAPPING,@@ -55,6 +56,34 @@ from products.warehouse_sources.backend.presentation.views.external_data_sourceMAX_UPLOAD_REQUEST_BODY_BYTES = MAX_FILE_UPLOAD_SIZE_BYTES + 1024 * 1024+def _delete_hosted_upload_file(table: DataWarehouseTable) -> None:+ """Best-effort removal of a self-managed table's backing file from PostHog's own bucket.++ Only ever touches files we host: `hosted_upload_s3_path` returns `None` for a customer-linked+ bucket, and a stored credential (the mark of a user-supplied bucket) is a further guard. Failures+ are swallowed so a storage hiccup can't block the table delete — the object simply lingers.+ """+ if table.credential_id is not None:+ return+ path = hosted_upload_s3_path(table.url_pattern)+ if path is None:+ return+ # The same uploaded file can back more than one table — `create_from_upload` doesn't claim+ # exclusive ownership of an upload — so only reclaim the object once no live table still points+ # at it. This keeps deleting one table from pulling the file out from under another, and stops a+ # table whose file is still in use from having its object removed.+ if (+ DataWarehouseTable.objects.filter(team_id=table.team_id, url_pattern=table.url_pattern, deleted=False)+ .exclude(pk=table.pk)+ .exists()+ ):+ return+ try:+ get_s3_client().rm(path)+ except Exception as e:+ capture_exception(e)++class CredentialSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)@@ -352,6 +381,7 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.M)instance.soft_delete()+ _delete_hosted_upload_file(instance)return response.Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.pyindex 920a970041ee..645c7bd90c38 100644--- a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py+++ b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py@@ -9,6 +9,7 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom rest_framework import status+from products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTable@@ -42,6 +43,7 @@ class _FakeS3:def __init__(self, *, exists_result: bool = True) -> None:self.written: dict[str, bytes] = {}+ self.removed: list[str] = []self._exists_result = exists_resultdef open(self, path: str, mode: str) -> io.BytesIO:@@ -50,6 +52,9 @@ class _FakeS3:def exists(self, path: str) -> bool:return self._exists_result+ def rm(self, path: str) -> None:+ self.removed.append(path)+@override_settings(DATAWAREHOUSE_BUCKET="test-bucket")class TestWarehouseTableUploadFile(APIBaseTest):@@ -279,3 +284,67 @@ class TestCreateTableFromUpload(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "not found" in response.json()["message"]assert DataWarehouseTable.objects.count() == 0+++@override_settings(DATAWAREHOUSE_BUCKET="test-bucket", DATAWAREHOUSE_BUCKET_DOMAIN="warehouse.posthog.test")+class TestWarehouseTableDeleteRemovesHostedFile(APIBaseTest):+ def _delete(self, table: DataWarehouseTable) -> tuple[int, list[str]]:+ s3 = _FakeS3()+ with patch(f"{VIEW_MODULE}.get_s3_client", return_value=s3):+ response = self.client.delete(f"/api/environments/{self.team.pk}/warehouse_tables/{table.id}")+ return response.status_code, s3.removed++ def test_deleting_a_hosted_upload_removes_its_backing_file(self) -> None:+ # The whole point of the fix: a self-managed table whose file we host must have that object+ # removed from our bucket on delete, not just have its row soft-deleted.+ upload_id = "11111111-1111-1111-1111-111111111111"+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name="orders",+ format="CSVWithNames",+ url_pattern=f"https://warehouse.posthog.test/file_uploads/team_{self.team.pk}/{upload_id}/orders.csv",+ columns={},+ )++ status_code, removed = self._delete(table)++ assert status_code == status.HTTP_204_NO_CONTENT+ assert removed == [f"test-bucket/file_uploads/team_{self.team.pk}/{upload_id}/orders.csv"]++ def test_deleting_a_linked_bucket_table_leaves_the_customer_file_untouched(self) -> None:+ # A self-managed table pointing at a customer's own bucket carries a credential and a foreign+ # host — deleting its file would destroy data on infra we don't own, so we must never touch it.+ credential = DataWarehouseCredential.objects.create(team=self.team, access_key="key", access_secret="secret")+ table = DataWarehouseTable.objects.create(+ team=self.team,+ name="orders",+ format="CSVWithNames",+ url_pattern="https://customer-bucket.s3.amazonaws.com/exports/orders.csv",+ credential=credential,+ columns={},+ )++ status_code, removed = self._delete(table)++ assert status_code == status.HTTP_204_NO_CONTENT+ assert removed == []++ def test_shared_upload_is_kept_until_the_last_referencing_table_is_deleted(self) -> None:+ # The same uploaded file can back more than one table. Deleting one table must not pull the+ # file out from under the other — the object is only reclaimed once the last table goes.+ upload_id = "22222222-2222-2222-2222-222222222222"+ url_pattern = f"https://warehouse.posthog.test/file_uploads/team_{self.team.pk}/{upload_id}/orders.csv"+ first = DataWarehouseTable.objects.create(+ team=self.team, name="orders", format="CSVWithNames", url_pattern=url_pattern, columns={}+ )+ second = DataWarehouseTable.objects.create(+ team=self.team, name="orders_copy", format="CSVWithNames", url_pattern=url_pattern, columns={}+ )++ status_code, removed = self._delete(first)+ assert status_code == status.HTTP_204_NO_CONTENT+ assert removed == []++ status_code, removed = self._delete(second)+ assert status_code == status.HTTP_204_NO_CONTENT+ assert removed == [f"test-bucket/file_uploads/team_{self.team.pk}/{upload_id}/orders.csv"]diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex b2ff8d0579f4..bf9e2dca4e25 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.file_uploads import (build_file_upload_s3_key,build_file_upload_s3_path,build_file_upload_url_pattern,+ hosted_upload_s3_path,)from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob as _ExternalDataJobfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema as _ExternalDataSchema@@ -69,6 +70,7 @@ __all__ = ["build_file_upload_s3_key","build_file_upload_s3_path","build_file_upload_url_pattern",+ "hosted_upload_s3_path",]# GitHub multi-repo source helpers live in ``github_warehouse_repos`` and pull the sourcediff --git a/products/warehouse_sources/backend/file_uploads.py b/products/warehouse_sources/backend/file_uploads.pyindex 994b46949ff5..2351ff2df63d 100644--- a/products/warehouse_sources/backend/file_uploads.py+++ b/products/warehouse_sources/backend/file_uploads.py@@ -68,3 +68,24 @@ def build_file_upload_url_pattern(team_id: int, upload_id: str, filename: str) -client-supplied ``upload_id`` can only ever resolve inside that team's folder."""return f"https://{settings.DATAWAREHOUSE_BUCKET_DOMAIN}/{build_file_upload_s3_key(team_id, upload_id, filename)}"+++def hosted_upload_s3_path(url_pattern: str) -> str | None:+ """The bucket-qualified ``bucket/key`` path (the form s3fs takes) backing a self-managed table+ whose file PostHog hosts in its own data warehouse bucket, or ``None`` when the table reads from+ anywhere else — most importantly a customer-linked S3/GCS bucket, which is never ours to delete.++ The gate is the URL host: only ``url_pattern``s under ``DATAWAREHOUSE_BUCKET_DOMAIN`` are hosted+ by us. That covers both the current ``file_uploads/`` prefix and the legacy ``managed/`` one.+ """+ domain = settings.DATAWAREHOUSE_BUCKET_DOMAIN+ bucket = settings.DATAWAREHOUSE_BUCKET+ if not domain or not bucket:+ return None+ prefix = f"https://{domain}/"+ if not url_pattern.startswith(prefix):+ return None+ key = url_pattern[len(prefix) :]+ if not key:+ return None+ return f"{bucket}/{key}"