: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
perf(warehouse-sources): shrink external data job rows (#91990)
Daniel RC512cacaed930
diff --git a/products/warehouse_sources/backend/migrations/0166_externaldatajob_detach_created_by.py b/products/warehouse_sources/backend/migrations/0166_externaldatajob_detach_created_by.pynew file mode 100644index 000000000000..ee58f987b5ab--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0166_externaldatajob_detach_created_by.py@@ -0,0 +1,49 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++from posthog.migration_helpers import DropForeignKey, DropIndexConcurrently+++class Migration(migrations.Migration):+ # DROP INDEX CONCURRENTLY cannot run inside a transaction.+ atomic = False++ dependencies = [+ ("warehouse_sources", "0165_migrate_bigquery_job_inputs_to_auth_type"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="externaldatajob",+ name="created_by",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.DO_NOTHING,+ to=settings.AUTH_USER_MODEL,+ ),+ )+ ],+ database_operations=[+ # Without the index below, the FK check on a user delete would seq-scan this table,+ # so the constraint has to go with it. Both operations are idempotent, so a+ # bin/migrate retry after a lost lock race re-runs them safely.+ DropForeignKey("posthog_externaldatajob", column="created_by_id"),+ # The state operation on its own would emit a plain DROP INDEX under ACCESS+ # EXCLUSIVE, which blocks reads and writes on a table that takes a steady+ # insert rate. The index is implicit, created by the foreign key rather than+ # by a Django Index, so it has no model_name + Index the safe helpers take.+ DropIndexConcurrently(+ index_name="posthog_externaldatajob_created_by_id_570bace7",+ table_name="posthog_externaldatajob",+ columns="(created_by_id)",+ ),+ ],+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 5b98b51424e4..895245918fe9 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0165_migrate_bigquery_job_inputs_to_auth_type+0166_externaldatajob_detach_created_bydiff --git a/products/warehouse_sources/backend/models/external_data_job.py b/products/warehouse_sources/backend/models/external_data_job.pyindex e88328fa11bd..9708f7e784b4 100644--- a/products/warehouse_sources/backend/models/external_data_job.py+++ b/products/warehouse_sources/backend/models/external_data_job.py@@ -18,6 +18,19 @@ class ExternalDataJob(CreatedMetaFields, UpdatedMetaFields, UUIDTModel):Status = ExternalDataJobStatusPipelineVersion = ExternalDataJobPipelineVersion+ # Overridden from CreatedMetaFields. Import workflows create every job row, so the column is+ # always NULL, and its index only cost a write per insert. With no index, a user delete would+ # seq-scan this table twice (Django's SET_NULL update, then the Postgres FK check), so the+ # constraint goes too and Django's cascade skips it.+ created_by = models.ForeignKey(+ "posthog.User",+ on_delete=models.DO_NOTHING,+ null=True,+ blank=True,+ db_index=False,+ db_constraint=False,+ )+team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")pipeline = models.ForeignKey("warehouse_sources.ExternalDataSource", related_name="jobs", on_delete=models.CASCADE)schema = models.ForeignKey("warehouse_sources.ExternalDataSchema", on_delete=models.CASCADE, null=True, blank=True)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.pyindex 20151539b0ec..d698ed2c550c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py@@ -133,11 +133,28 @@ def _verify_v3_lock_still_held(team_id: int, schema_id: uuid.UUID) -> None:)+# Per-run state, not configuration. `cdc_deferred_runs` is a notification queue that reaches+# hundreds of KB on a busy CDC schema, and `schema_metadata` is the source table's column list.+# Copying them onto every job row was most of the snapshot's storage cost.+_SNAPSHOT_EXCLUDED_CONFIG_KEYS = frozenset({"cdc_deferred_runs", "schema_metadata"})++def _build_schema_snapshot(schema: ExternalDataSchema) -> dict[str, Any]:+ """The schema as it was when this job started, for debugging a run after the fact.++ `post_import_job` reads `last_synced_at` back, and CDC extraction adds `cdc_write_mode` for+ the jobs API. The rest is only ever read by a person: the schema audit log does not diff+ `sync_type_config`, so this is the one record of the cursor and reset flags a run ran with.+ """+ sync_type_config = {+ key: value+ for key, value in (schema.sync_type_config or {}).items()+ if key not in _SNAPSHOT_EXCLUDED_CONFIG_KEYS+ }return {"name": schema.name,"sync_type": schema.sync_type,- "sync_type_config": schema.sync_type_config,+ "sync_type_config": sync_type_config,"sync_frequency_interval": schema.sync_frequency_interval.total_seconds()if schema.sync_frequency_intervalelse None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.pyindex 568a8d0cb3e8..f907192d72e5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py@@ -21,6 +21,7 @@ from products.warehouse_sources.backend.models.external_data_source import Exterfrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.workflow_activities.create_job_model import (CreateExternalDataJobModelActivityInputs,+ _build_schema_snapshot,_create_job,_enrichment_pending,_statistics_stale,@@ -179,6 +180,28 @@ class TestEnrichmentPending:assert _enrichment_pending(team.id, table, _schema(team, table, description=None)) is False+class TestBuildSchemaSnapshot:+ def test_copies_the_config_without_the_per_run_state_blobs(self) -> None:+ config = {+ "incremental_field": "updated_at",+ "incremental_field_last_value": "2026-09-01T00:00:00+00:00",+ "reset_pipeline": True,+ "schema_metadata": {"columns": [{"name": "id", "type": "int"}]},+ "cdc_deferred_runs": [{"run_id": "r1"}],+ }+ schema = ExternalDataSchema(name="Charge", sync_type="incremental", sync_type_config=dict(config))++ snapshot = _build_schema_snapshot(schema)++ assert snapshot["sync_type_config"] == {+ "incremental_field": "updated_at",+ "incremental_field_last_value": "2026-09-01T00:00:00+00:00",+ "reset_pipeline": True,+ }+ assert snapshot["sync_type"] == "incremental"+ assert schema.sync_type_config == config++@pytest.mark.django_dbclass TestCreateJob:# Guards the deadlock we saw in production: Postgres can abort the ExternalDataJob INSERT with