: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
fix(data-imports): survive a team deleted mid table-size calculation (#95635)
Tom Owers65eb6a9a5ab7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.pyindex 2323c5126180..ef423ae6ce45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/calculate_table_size.py@@ -1,7 +1,7 @@import dataclassesfrom django.conf import settings-from django.db import close_old_connections+from django.db import DatabaseError, close_old_connectionsfrom structlog.contextvars import bind_contextvarsfrom temporalio import activity@@ -71,13 +71,28 @@ def calculate_table_size_activity(inputs: CalculateTableSizeActivityInputs) -> Nlogger.debug(f"Table size delta in MiB = {table_size_delta:.2f}")job.storage_delta_mib = table_size_delta- job.save(update_fields=["storage_delta_mib", "updated_at"])+ try:+ job.save(update_fields=["storage_delta_mib", "updated_at"])+ except DatabaseError:+ # get_size_of_folder() (an S3 listing) can run long enough for the job's team to be+ # deleted meanwhile, cascading away this row before the UPDATE lands. Not a defect —+ # exit the same way the DoesNotExist checks above do.+ if not ExternalDataJob.objects.filter(id=job.id).exists():+ logger.debug(f"Job was deleted while calculating table size, exiting early. Job id = {job.id}")+ return+ raisetable.size_in_s3_mib = total_mib- # Scoped to the field this activity actually changes: an unscoped save() compares this- # possibly-stale in-memory url_pattern (table was loaded before the potentially long- # get_size_of_folder() call above) against the row's current DB value, and a credential-less- # table with no other change in flight trips the url_pattern guard on that false mismatch.- table.save(update_fields=["size_in_s3_mib", "updated_at"])+ try:+ # Scoped to the field this activity actually changes: an unscoped save() compares this+ # possibly-stale in-memory url_pattern (table was loaded before the potentially long+ # get_size_of_folder() call above) against the row's current DB value, and a credential-less+ # table with no other change in flight trips the url_pattern guard on that false mismatch.+ table.save(update_fields=["size_in_s3_mib", "updated_at"])+ except DatabaseError:+ if not DataWarehouseTable.objects.filter(id=table.id).exists():+ logger.debug(f"Table was deleted while calculating table size, exiting early. Table id = {table.id}")+ return+ raiselogger.debug("Table model updated")diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.pyindex c2b643adb84a..e2f33f81e3a3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_calculate_table_size.py@@ -63,3 +63,25 @@ class TestCalculateTableSizeActivity:table.refresh_from_db()assert table.size_in_s3_mib == 12.5assert table.url_pattern == "https://posthog-owned.example/team/stripe_charge_repartitioned"++ def test_survives_a_concurrent_team_deletion(self) -> None:+ # get_size_of_folder() (an S3 listing) can take long enough for the team owning this job+ # to be deleted meanwhile, cascading away the job and table rows before this activity's+ # own save() runs. Django's update_fields save() used to surface that as an unhandled+ # DatabaseError ("Save with update_fields did not affect any rows") instead of the same+ # clean early exit the DoesNotExist checks give a schema/job deleted before this activity+ # even starts.+ team = _team()+ schema, table, job = _schema_table_job(team)++ def _slow_listing(_folder: str) -> float:+ team.delete()+ return 12.5++ with patch.object(calc, "get_size_of_folder", side_effect=_slow_listing):+ calculate_table_size_activity(+ CalculateTableSizeActivityInputs(team_id=team.id, schema_id=str(schema.id), job_id=str(job.id))+ )++ assert not ExternalDataJob.objects.filter(id=job.id).exists()+ assert not DataWarehouseTable.objects.filter(id=table.id).exists()