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): prevent sync_type_config lost updates in CDC (#65594)

Daniel RCa4f282015e13
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index 8407ed500ab3..b7aafc293dae 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -15,6 +15,7 @@ import uuid
import typing
import datetime as dt
import dataclasses
+from collections.abc import Callable
from django.db import close_old_connections
@@ -44,7 +45,10 @@ from posthog.temporal.data_imports.workflow_activities.create_job_model import _
from posthog.utils import get_machine_id
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
logger = structlog.get_logger(__name__)
@@ -163,6 +167,37 @@ class CDCExtractActivity:
).exclude(deleted=True)
)
+ # ------------------------------------------------------------------
+ # sync_type_config persistence (locked merge, see update_sync_type_config_keys)
+ # ------------------------------------------------------------------
+ def _update_schema_sync_type_config(
+ self,
+ schema: ExternalDataSchema,
+ *,
+ updates: dict[str, typing.Any] | None = None,
+ removes: list[str] | None = None,
+ mutate: Callable[[dict[str, typing.Any]], None] | None = None,
+ extra_model_fields: dict[str, typing.Any] | None = None,
+ ) -> None:
+ """Persist a `sync_type_config` change through the locked-merge helper, then refresh the
+ in-memory copy from the returned dict.
+
+ Every `sync_type_config` write in this activity goes through here so the long-lived
+ in-memory schema can't clobber a concurrent API PATCH (or another writer) — the merge
+ re-reads the row under a lock instead of overwriting it wholesale.
+ """
+ schema.sync_type_config = update_sync_type_config_keys(
+ schema.id,
+ schema.team_id,
+ updates=updates,
+ removes=removes,
+ mutate=mutate,
+ extra_model_fields=extra_model_fields,
+ )
+ if extra_model_fields:
+ for field, value in extra_model_fields.items():
+ setattr(schema, field, value)
+
# ------------------------------------------------------------------
# Deferred run flushing
# ------------------------------------------------------------------
@@ -237,8 +272,7 @@ class CDCExtractActivity:
finally:
producer.close()
- schema.sync_type_config["cdc_deferred_runs"] = []
- schema.save(update_fields=["sync_type_config", "updated_at"])
+ self._update_schema_sync_type_config(schema, updates={"cdc_deferred_runs": []})
log.info("deferred_runs_flushed", schema_id=str(schema.id))
@@ -350,51 +384,48 @@ class CDCExtractActivity:
"""Persist a batch result into the tracker's deferred entry in sync_type_config.
Creates the entry on first call (keyed by run_uuid), appends to it on
- subsequent calls. Saves immediately so progress survives process failures.
+ subsequent calls. Persists immediately so progress survives process failures.
- IMPORTANT: This mutates the in-memory schema.sync_type_config and saves
- with update_fields=["sync_type_config"]. This is safe because
- cdc_extract_activity is single-threaded and all sync_type_config writes
- happen sequentially within this activity. Do not call from async contexts.
+ The entry lookup + append runs inside the locked merge (see
+ update_sync_type_config_keys) so an interleaved API PATCH can't drop the
+ deferred runs this activity is accumulating — read-modify-write on a stale
+ copy is exactly the lost update the merge prevents.
"""
- deferred = schema.sync_type_config.setdefault("cdc_deferred_runs", [])
-
- entry: dict | None = None
- for d in deferred:
- if d.get("run_uuid") == tracker.run_uuid:
- entry = d
- break
-
- if entry is None:
- entry = {
- "job_id": str(tracker.job.id),
- "run_uuid": tracker.run_uuid,
- # Replayed by the deferred flush so it targets the same Delta table this batch went to.
- "resource_name": tracker.write_resource_name,
- "data_folder": tracker.s3_writer.get_data_folder(),
- "schema_path": None, # written on finalization
- "total_batches": 0,
- "total_rows": 0,
- "primary_keys": tracker.key_columns or None,
- "cdc_write_mode": tracker.cdc_write_mode,
- "cdc_table_mode": tracker.cdc_table_mode,
- "batch_results": [],
- }
- deferred.append(entry)
-
- entry["batch_results"].append(
- {
- "s3_path": batch_result.s3_path,
- "row_count": batch_result.row_count,
- "byte_size": batch_result.byte_size,
- "batch_index": batch_result.batch_index,
- "timestamp_ns": batch_result.timestamp_ns,
- }
- )
- entry["total_batches"] = tracker.batch_index
- entry["total_rows"] = tracker.total_rows
- schema.save(update_fields=["sync_type_config", "updated_at"])
+ def _append_batch(config: dict[str, typing.Any]) -> None:
+ deferred = config.setdefault("cdc_deferred_runs", [])
+ entry: dict | None = next((d for d in deferred if d.get("run_uuid") == tracker.run_uuid), None)
+
+ if entry is None:
+ entry = {
+ "job_id": str(tracker.job.id),
+ "run_uuid": tracker.run_uuid,
+ # Replayed by the deferred flush so it targets the same Delta table this batch went to.
+ "resource_name": tracker.write_resource_name,
+ "data_folder": tracker.s3_writer.get_data_folder(),
+ "schema_path": None, # written on finalization
+ "total_batches": 0,
+ "total_rows": 0,
+ "primary_keys": tracker.key_columns or None,
+ "cdc_write_mode": tracker.cdc_write_mode,
+ "cdc_table_mode": tracker.cdc_table_mode,
+ "batch_results": [],
+ }
+ deferred.append(entry)
+
+ entry["batch_results"].append(
+ {
+ "s3_path": batch_result.s3_path,
+ "row_count": batch_result.row_count,
+ "byte_size": batch_result.byte_size,
+ "batch_index": batch_result.batch_index,
+ "timestamp_ns": batch_result.timestamp_ns,
+ }
+ )
+ entry["total_batches"] = tracker.batch_index
+ entry["total_rows"] = tracker.total_rows
+
+ self._update_schema_sync_type_config(schema, mutate=_append_batch)
self._schema_log(schema).info(
"cdc_deferred_run_stored",
@@ -405,6 +436,21 @@ class CDCExtractActivity:
total_rows=tracker.total_rows,
)
+ def _persist_deferred_finalization(
+ self, schema: ExternalDataSchema, tracker: _WriteTracker, schema_path: str
+ ) -> None:
+ """Stamp the final schema_path + totals onto the tracker's deferred entry under the merge lock."""
+
+ def _finalize(config: dict[str, typing.Any]) -> None:
+ for entry in config.get("cdc_deferred_runs", []):
+ if entry.get("run_uuid") == tracker.run_uuid:
+ entry["schema_path"] = schema_path
+ entry["total_batches"] = tracker.batch_index
+ entry["total_rows"] = tracker.total_rows
+ break
+
+ self._update_schema_sync_type_config(schema, mutate=_finalize)
+
# ------------------------------------------------------------------
# Storage naming
# ------------------------------------------------------------------
@@ -645,8 +691,9 @@ class CDCExtractActivity:
# Persist discovered PKs to avoid re-querying
for schema in self.cdc_schemas:
if schema.name in queried_pks:
- schema.sync_type_config["primary_key_columns"] = queried_pks[schema.name]
- schema.save(update_fields=["sync_type_config", "updated_at"])
+ self._update_schema_sync_type_config(
+ schema, updates={"primary_key_columns": queried_pks[schema.name]}
+ )
self.log.info("pk_columns_loaded", tables=list(self.pk_columns_by_table.keys()))
@@ -792,8 +839,7 @@ class CDCExtractActivity:
pk_log.warning("pk_columns_changed", table=table_name, old=stored_pks, new=decoder_pks)
self.pk_columns_by_table[table_name] = decoder_pks
if pk_schema is not None:
- pk_schema.sync_type_config["primary_key_columns"] = decoder_pks
- pk_schema.save(update_fields=["sync_type_config", "updated_at"])
+ self._update_schema_sync_type_config(pk_schema, updates={"primary_key_columns": decoder_pks})
def _handle_truncates(self) -> list[str]:
"""Process any truncated tables observed during decoding.
@@ -816,18 +862,17 @@ class CDCExtractActivity:
def _reset_schema_to_snapshot(self, schema: ExternalDataSchema, *, clear_deferred_runs: bool = False) -> None:
"""Put a schema back into snapshot mode so its own schedule re-syncs it from scratch."""
- schema.sync_type_config["cdc_mode"] = "snapshot"
- schema.sync_type_config.pop("cdc_last_log_position", None)
- # A source TRUNCATE (or a lost slot) leaves the warehouse table in place, so without
- # reset_pipeline the re-snapshot takes the incremental-merge path and upserts the
- # current rows over the stale ones — pre-truncate rows never deleted. Forcing it makes
- # the batch import wipe the table first (handle_reset_or_full_refresh, which also clears
- # the flag). The {name}_cdc companion is reset independently by the snapshot seed.
- schema.sync_type_config["reset_pipeline"] = True
+ removes = ["cdc_last_log_position"]
if clear_deferred_runs:
- schema.sync_type_config.pop("cdc_deferred_runs", None)
- schema.initial_sync_complete = False
- schema.save(update_fields=["sync_type_config", "initial_sync_complete", "updated_at"])
+ removes.append("cdc_deferred_runs")
+ # reset_pipeline forces the batch import to wipe the table first (handle_reset_or_full_refresh),
+ # preventing pre-truncate rows from surviving a TRUNCATE or lost-slot re-snapshot.
+ self._update_schema_sync_type_config(
+ schema,
+ updates={"cdc_mode": "snapshot", "reset_pipeline": True},
+ removes=removes,
+ extra_model_fields={"initial_sync_complete": False},
+ )
def _unpause_schema_schedule(self, schema: ExternalDataSchema) -> None:
schema_log = self._schema_log(schema)
@@ -906,14 +951,8 @@ class CDCExtractActivity:
elif schema.cdc_mode == "snapshot":
# Write schema file and update the deferred entry with final metadata.
schema_path = tracker.s3_writer.write_schema()
- deferred = schema.sync_type_config.get("cdc_deferred_runs", [])
- for entry in deferred:
- if entry.get("run_uuid") == tracker.run_uuid:
- entry["schema_path"] = schema_path
- entry["total_batches"] = tracker.batch_index
- entry["total_rows"] = tracker.total_rows
- break
- schema.save(update_fields=["sync_type_config", "updated_at"])
+ if schema_path is not None:
+ self._persist_deferred_finalization(schema, tracker, schema_path)
tracker.job.rows_synced = tracker.total_rows
tracker.job.status = ExternalDataJob.Status.COMPLETED
@@ -938,8 +977,7 @@ class CDCExtractActivity:
for schema in self.cdc_schemas:
if schema.sync_type_config.get("cdc_mode") == "snapshot":
continue
- schema.sync_type_config["cdc_last_log_position"] = self.last_end_lsn
- schema.save(update_fields=["sync_type_config", "updated_at"])
+ self._update_schema_sync_type_config(schema, updates={"cdc_last_log_position": self.last_end_lsn})
# ------------------------------------------------------------------
# Failure / success finalization
diff --git a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
index 417466dc3ff0..5c79548d06be 100644
--- a/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/posthog/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -97,6 +97,36 @@ def _make_schema(
return schema
+def _fake_update_schema_sync_type_config(schema, *, updates=None, removes=None, mutate=None, extra_model_fields=None):
+ """Stand-in for CDCExtractActivity._update_schema_sync_type_config that merges onto the
+ in-memory mock schema. The real helper re-reads the row from Postgres under a lock, which these
+ mock-only tests don't have; this mirrors its merge order (updates, then removes, then mutate)
+ and its post-merge application of `extra_model_fields` onto the schema."""
+ config = schema.sync_type_config or {}
+ if updates:
+ config.update(updates)
+ if removes:
+ for key in removes:
+ config.pop(key, None)
+ if mutate is not None:
+ mutate(config)
+ schema.sync_type_config = config
+ if extra_model_fields:
+ for field, value in extra_model_fields.items():
+ setattr(schema, field, value)
+
+
[email protected](autouse=True)
+def _stub_sync_type_config_merge():
+ """Route every activity sync_type_config write onto the in-memory mock schema (no DB)."""
+ with patch.object(
+ CDCExtractActivity,
+ "_update_schema_sync_type_config",
+ side_effect=_fake_update_schema_sync_type_config,
+ ):
+ yield
+
+
# Shared patch decorator for CDC activity tests
_CDC_ACTIVITY_PATCHES = [
"posthog.temporal.data_imports.cdc.activities.close_old_connections",
@@ -288,7 +318,6 @@ class TestFlushDeferredRuns:
mock_producer.flush.assert_called_once()
assert schema.sync_type_config["cdc_deferred_runs"] == []
- schema.save.assert_called()
@patch("posthog.temporal.data_imports.cdc.activities.PostgresProducer")
def test_no_op_when_no_deferred_runs(self, MockProducer):
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index 0a3dce2aabf9..2c22ca287bbc 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -2,6 +2,8 @@ import datetime as dt
from collections.abc import Callable
from typing import Any, Optional, cast
+from django.db import transaction
+
import structlog
import temporalio
from drf_spectacular.utils import extend_schema, extend_schema_field
@@ -57,6 +59,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
sync_frequency_interval_to_sync_frequency,
sync_frequency_to_sync_frequency_interval,
+ update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -108,13 +111,18 @@ def _reset_cdc_for_full_resnapshot(instance: ExternalDataSchema) -> None:
exc_info=e,
)
- instance.sync_type_config["reset_pipeline"] = True
- instance.sync_type_config["cdc_mode"] = "snapshot"
- instance.sync_type_config.pop("cdc_last_log_position", None)
- instance.sync_type_config.pop("cdc_deferred_runs", None)
+ # Merge under a row lock so the reset can't clobber a concurrent CDC extract activity's
+ # sync_type_config writes (and the status/initial_sync_complete save below skips the JSON
+ # column, leaving no second window for the merged config to be overwritten).
+ instance.sync_type_config = update_sync_type_config_keys(
+ instance.id,
+ instance.team_id,
+ updates={"reset_pipeline": True, "cdc_mode": "snapshot"},
+ removes=["cdc_last_log_position", "cdc_deferred_runs"],
+ )
instance.initial_sync_complete = False
instance.status = ExternalDataSchema.Status.RUNNING
- instance.save()
+ instance.save(update_fields=["initial_sync_complete", "status", "updated_at"])
try:
trigger_external_data_workflow(instance)
@@ -470,6 +478,37 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
callback()
+ def _save_merging_sync_type_config(
+ self,
+ instance: ExternalDataSchema,
+ validated_data: dict[str, Any],
+ original_sync_type_config: dict[str, Any],
+ ) -> ExternalDataSchema:
+ """Persist the update, replaying only the sync_type_config keys this request changed onto a
+ freshly-locked copy of the row.
+
+ super().update() does a full-instance save that rewrites sync_type_config wholesale from the
+ copy loaded at the start of the request, so without this it would revert any key a concurrent
+ CDC extract activity (cdc_last_log_position, cdc_deferred_runs, cdc_mode) committed in between.
+ The lock is held across the save so nothing interleaves.
+ """
+ intended = instance.sync_type_config or {}
+ changed = {
+ key: value
+ for key, value in intended.items()
+ if key not in original_sync_type_config or original_sync_type_config[key] != value
+ }
+ removed = [key for key in original_sync_type_config if key not in intended]
+ with transaction.atomic():
+ locked = ExternalDataSchema.objects.select_for_update().get(pk=instance.pk)
+ merged = locked.sync_type_config or {}
+ merged.update(changed)
+ for key in removed:
+ merged.pop(key, None)
+ instance.sync_type_config = merged
+ validated_data["sync_type_config"] = merged
+ return super().update(instance, validated_data)
+
def update(self, instance: ExternalDataSchema, validated_data: dict[str, Any]) -> ExternalDataSchema:
data = self.initial_data if isinstance(self.initial_data, dict) else {}
@@ -477,6 +516,12 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
# whether the change adds a new physical write target (and therefore needs a re-snapshot).
previous_cdc_table_mode = instance.cdc_table_mode
+ # Snapshot sync_type_config before the branches below mutate it in place. The terminal save
+ # diffs against this to persist only the keys this request changed. Shallow is enough: the
+ # branches replace top-level keys (they never mutate a nested value in place), so a key is
+ # "changed" iff its top-level value differs.
+ original_sync_type_config = dict(instance.sync_type_config or {})
+
# Refuse cdc_table_mode transitions that would kick a re-snapshot when the team is over its
# monthly sync billing limit. Checked here (pre-save) so we don't end up with the new mode
# persisted but no resnapshot triggered. Mirrors the gate in `resync` / `reload`.
@@ -848,7 +893,9 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
instance.sync_type_config.update({"reset_pipeline": True})
validated_data["sync_type_config"].update({"reset_pipeline": True})
- updated_instance = super().update(instance, validated_data)
+ # Persist under a row lock, replaying only the sync_type_config keys this request changed
+ # so a concurrent CDC extract activity's writes aren't reverted by the full-instance save.
+ updated_instance = self._save_merging_sync_type_config(instance, validated_data, original_sync_type_config)
if source.supports_scheduled_sync and (
should_sync is not None or was_sync_frequency_updated or was_sync_time_of_day_updated
@@ -1077,10 +1124,12 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
# reset_pipeline wipes the warehouse table first — otherwise the snapshot
# merges current rows over the stale pre-disable ones and never drops deletes.
if should_sync is True and not newly_set_to_cdc:
+ # Mutate in memory only — the locked terminal save in `update()` (which calls this)
+ # persists both fields, merging cdc_mode onto the freshly-read config so a concurrent
+ # CDC extract activity's writes survive. A separate save here would clobber them.
instance.sync_type_config["cdc_mode"] = "snapshot"
instance.sync_type_config["reset_pipeline"] = True
instance.initial_sync_complete = False
- instance.save(update_fields=["sync_type_config", "initial_sync_complete", "updated_at"])
# Remove table from capture set when toggling sync off
elif should_sync is False and instance.should_sync:
@@ -1208,21 +1257,29 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if latest_running_job and latest_running_job.workflow_id and latest_running_job.status == "Running":
cancel_external_data_workflow(latest_running_job.workflow_id)
- instance.sync_type_config.update({"reset_pipeline": True})
-
- if instance.is_cdc:
+ cdc_resync = instance.is_cdc
+ updates: dict[str, Any] = {"reset_pipeline": True}
+ removes: list[str] = []
+ if cdc_resync:
# Reset CDC state so the next run does a full re-snapshot
- instance.sync_type_config["cdc_mode"] = "snapshot"
- instance.sync_type_config.pop("cdc_last_log_position", None)
- instance.sync_type_config.pop("cdc_deferred_runs", None)
+ updates["cdc_mode"] = "snapshot"
+ removes = ["cdc_last_log_position", "cdc_deferred_runs"]
+
+ # Merge under a row lock so this reset can't clobber a concurrent CDC extract activity's
+ # sync_type_config writes. Persist BEFORE triggering the workflow so the Postgres source
+ # sees cdc_mode="snapshot" when it reloads the schema from DB — otherwise a race: the
+ # workflow starts, loads stale "streaming" mode, raises CDCHandledExternally, and the
+ # full-refresh never runs.
+ # initial_sync_complete is saved in the same transaction as cdc_mode via extra_model_fields
+ # so no reader can observe cdc_mode="snapshot" with initial_sync_complete=True.
+ extra: dict[str, Any] = {"initial_sync_complete": False} if cdc_resync else {}
+ instance.sync_type_config = update_sync_type_config_keys(
+ instance.id, instance.team_id, updates=updates, removes=removes, extra_model_fields=extra
+ )
+ if cdc_resync:
instance.initial_sync_complete = False
-
- # Save BEFORE triggering the workflow so the Postgres source sees
- # cdc_mode="snapshot" when it reloads the schema from DB.
- # Otherwise a race: the workflow starts, loads stale "streaming" mode,
- # raises CDCHandledExternally, and the full-refresh never runs.
instance.status = ExternalDataSchema.Status.RUNNING
- instance.save()
+ instance.save(update_fields=["status", "updated_at"])
try:
trigger_external_data_workflow(instance)
diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.py
index e2b69352ab32..46944ea72b0f 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py
@@ -30,7 +30,10 @@ from products.data_warehouse.backend.api.test.utils import create_external_data_
from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERN
from products.data_warehouse.backend.external_data_source.webhooks import WebhookHogFunctionCreateResult
from products.data_warehouse.backend.types import ExternalDataSourceType
-from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_schema import (
+ ExternalDataSchema,
+ update_sync_type_config_keys,
+)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
@@ -2770,6 +2773,97 @@ class TestExternalDataSchemaSerializerValidation(APIBaseTest):
assert self.schema.sync_type == ExternalDataSchema.SyncType.INCREMENTAL
+class TestSyncTypeConfigLostUpdateProtection(APIBaseTest):
+ """The serializer's full-instance save must not revert a sync_type_config key that a concurrent
+ CDC extract activity committed after the request loaded the row."""
+
+ def setUp(self):
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ team=self.team,
+ source_type=ExternalDataSourceType.POSTGRES,
+ # self_managed so the CDC publication hook in update() returns early without touching the source.
+ job_inputs={
+ "host": "h",
+ "port": 5432,
+ "database": "d",
+ "user": "u",
+ "password": "p",
+ "schema": "public",
+ "cdc_enabled": True,
+ "cdc_management_mode": "self_managed",
+ "cdc_slot_name": "s",
+ "cdc_publication_name": "p",
+ },
+ )
+ self.schema = ExternalDataSchema.objects.create(
+ name="public.orders",
+ team=self.team,
+ source=self.source,
+ should_sync=True,
+ status=ExternalDataSchema.Status.COMPLETED,
+ sync_type=ExternalDataSchema.SyncType.CDC,
+ sync_type_config={
+ "cdc_mode": "streaming",
+ "cdc_table_mode": "consolidated",
+ "cdc_last_log_position": "0/100",
+ "primary_key_columns": ["id"],
+ },
+ )
+
+ def test_patch_does_not_clobber_concurrent_activity_position(self):
+ from products.data_warehouse.backend.api.external_data_schema import ExternalDataSchemaSerializer
+
+ # The serializer's in-memory copy is loaded here, holding position 0/100.
+ instance = ExternalDataSchema.objects.get(id=self.schema.id)
+
+ # A CDC extract activity commits a newer position while the request is mid-flight.
+ update_sync_type_config_keys(self.schema.id, self.team.pk, updates={"cdc_last_log_position": "0/900"})
+
+ # A user PATCH edits an unrelated (non-sync_type_config) field off the stale copy and saves.
+ serializer = ExternalDataSchemaSerializer(
+ instance,
+ data={"enabled_columns": ["id"]},
+ partial=True,
+ context={"team_id": self.team.pk, "post_commit_actions": []},
+ )
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+
+ self.schema.refresh_from_db()
+ # The user's edit applied AND the concurrent position survived (not reverted to 0/100).
+ assert self.schema.enabled_columns == ["id"]
+ assert self.schema.sync_type_config["cdc_last_log_position"] == "0/900"
+
+ def test_patch_changing_sync_type_config_key_keeps_concurrent_write(self):
+ from products.data_warehouse.backend.api.external_data_schema import ExternalDataSchemaSerializer
+
+ instance = ExternalDataSchema.objects.get(id=self.schema.id) # in-memory copy, position 0/100
+
+ # A CDC extract activity commits a newer position while the request is mid-flight.
+ update_sync_type_config_keys(self.schema.id, self.team.pk, updates={"cdc_last_log_position": "0/900"})
+
+ # The user changes a sync_type_config key (cdc_table_mode). The re-snapshot it would trigger is
+ # deferred to post-commit (which we don't run), so only the merge itself is under test here.
+ serializer = ExternalDataSchemaSerializer(
+ instance,
+ data={"cdc_table_mode": "both"},
+ partial=True,
+ context={"team_id": self.team.pk, "post_commit_actions": []},
+ )
+ with mock.patch(
+ "products.data_warehouse.backend.api.external_data_schema.is_any_external_data_schema_paused",
+ return_value=False,
+ ):
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+
+ self.schema.refresh_from_db()
+ # The user's key change landed AND the concurrent position (a key the request didn't touch) survived.
+ assert self.schema.cdc_table_mode == "both"
+ assert self.schema.sync_type_config["cdc_last_log_position"] == "0/900"
+
+
class TestAvailableColumnsAcrossSqlSources(APIBaseTest):
"""`available_columns` is source-type-agnostic — it reads `schema_metadata.columns`.
Parameterized across every SQL source to lock in that the serializer doesn't regress
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index 99c10abd7bbc..e967fd6438ea 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -1,10 +1,11 @@
import sys
import uuid
+from collections.abc import Callable, Iterable
from datetime import date, datetime, timedelta
from typing import Any, Literal, Optional
from django.conf import settings
-from django.db import models
+from django.db import models, transaction
from dateutil import parser
from django_deprecate_fields import deprecate_field
@@ -625,6 +626,56 @@ def update_should_sync(schema_id: str, team_id: int, should_sync: bool) -> Exter
return schema
+def update_sync_type_config_keys(
+ schema_id: str | uuid.UUID,
+ team_id: int,
+ *,
+ updates: dict[str, Any] | None = None,
+ removes: Iterable[str] | None = None,
+ mutate: Callable[[dict[str, Any]], None] | None = None,
+ extra_model_fields: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Atomically merge keys into a schema's `sync_type_config` under a row lock and return the
+ persisted config.
+
+ The CDC extract activity holds a long-lived in-memory schema and writes `sync_type_config`
+ repeatedly across a run, while API PATCHes rewrite the same JSON concurrently. A
+ read-modify-write off a copy loaded earlier loses whichever side saved last. Re-fetching the
+ row inside the transaction with `select_for_update` makes every writer merge onto the latest
+ committed value instead of clobbering it.
+
+ `updates` sets keys, `removes` pops keys, and `mutate` runs last for in-place edits of nested
+ structures (e.g. appending to `cdc_deferred_runs`) that must happen inside the critical section.
+ Callers refresh their in-memory copy from the returned dict.
+
+ `extra_model_fields` saves additional model fields in the same transaction and row lock — use
+ when a reset must flip both `sync_type_config` and another field (e.g. `initial_sync_complete`)
+ atomically so no reader can observe the half-written state.
+
+ Saves with `skip_activity_log=True`: `sync_type_config` is excluded from the schema's audit
+ diff anyway, and the bypass skips the extra `_get_before_update` SELECT that can fail when the
+ pooler drops the connection mid-sync.
+ """
+ with transaction.atomic():
+ schema = ExternalDataSchema.objects.select_for_update().get(id=schema_id, team_id=team_id)
+ config = schema.sync_type_config or {}
+ if updates:
+ config.update(updates)
+ if removes:
+ for key in removes:
+ config.pop(key, None)
+ if mutate is not None:
+ mutate(config)
+ schema.sync_type_config = config
+ update_fields = ["sync_type_config", "updated_at"]
+ if extra_model_fields:
+ for field, value in extra_model_fields.items():
+ setattr(schema, field, value)
+ update_fields.append(field)
+ schema.save(update_fields=update_fields, skip_activity_log=True)
+ return config
+
+
def get_all_schemas_for_source_id(source_id: str, team_id: int):
return list(ExternalDataSchema.objects.exclude(deleted=True).filter(team_id=team_id, source_id=source_id).all())
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index d427d1859e2a..476a64065d67 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
ExternalDataSchema,
apply_incremental_lookback,
process_incremental_value,
+ update_sync_type_config_keys,
)
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
@@ -191,6 +192,125 @@ class TestExternalDataSchemaActivityLogging(BaseTest):
assert schema.incremental_field_last_value == 42
+class TestUpdateSyncTypeConfigKeys(BaseTest):
+ """The locked-merge helper that keeps the CDC extract activity and concurrent API PATCHes from
+ clobbering each other's sync_type_config keys."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.source = ExternalDataSource.objects.create(
+ team_id=self.team.pk,
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type="Postgres",
+ )
+
+ def _create(self, sync_type_config: dict) -> ExternalDataSchema:
+ return ExternalDataSchema.objects.create(
+ team_id=self.team.pk, source=self.source, name="users", sync_type_config=sync_type_config
+ )
+
+ def test_updates_merge_and_preserve_unrelated_keys(self) -> None:
+ schema = self._create({"cdc_mode": "streaming", "cdc_last_log_position": "0/100"})
+ result = update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_last_log_position": "0/200"})
+ assert result == {"cdc_mode": "streaming", "cdc_last_log_position": "0/200"}
+ schema.refresh_from_db()
+ assert schema.sync_type_config == {"cdc_mode": "streaming", "cdc_last_log_position": "0/200"}
+
+ def test_removes_pop_keys(self) -> None:
+ schema = self._create(
+ {"cdc_mode": "snapshot", "cdc_last_log_position": "0/100", "cdc_deferred_runs": [{"x": 1}]}
+ )
+ result = update_sync_type_config_keys(
+ schema.id,
+ self.team.pk,
+ updates={"cdc_mode": "snapshot"},
+ removes=["cdc_last_log_position", "cdc_deferred_runs"],
+ )
+ assert result == {"cdc_mode": "snapshot"}
+ schema.refresh_from_db()
+ assert schema.sync_type_config == {"cdc_mode": "snapshot"}
+
+ def test_remove_of_absent_key_is_noop(self) -> None:
+ schema = self._create({"cdc_mode": "streaming"})
+ update_sync_type_config_keys(schema.id, self.team.pk, removes=["not_there"])
+ schema.refresh_from_db()
+ assert schema.sync_type_config == {"cdc_mode": "streaming"}
+
+ def test_mutate_appends_inside_critical_section(self) -> None:
+ schema = self._create({"cdc_deferred_runs": [{"run_uuid": "a", "batch_results": []}]})
+
+ def _mutate(config: dict) -> None:
+ for entry in config["cdc_deferred_runs"]:
+ if entry["run_uuid"] == "a":
+ entry["batch_results"].append({"s3_path": "s3://x"})
+
+ update_sync_type_config_keys(schema.id, self.team.pk, mutate=_mutate)
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_deferred_runs"][0]["batch_results"] == [{"s3_path": "s3://x"}]
+
+ def test_apply_order_is_updates_removes_mutate(self) -> None:
+ schema = self._create({"a": 1})
+
+ def _mutate(config: dict) -> None:
+ config["seen"] = sorted(config.keys())
+
+ result = update_sync_type_config_keys(schema.id, self.team.pk, updates={"b": 2}, removes=["a"], mutate=_mutate)
+ assert "a" not in result
+ assert result["seen"] == ["b"]
+
+ def test_wrong_team_id_does_not_match(self) -> None:
+ schema = self._create({"cdc_mode": "streaming"})
+ with self.assertRaises(ExternalDataSchema.DoesNotExist):
+ update_sync_type_config_keys(schema.id, self.team.pk + 12345, updates={"cdc_mode": "snapshot"})
+
+ def test_skips_activity_log(self) -> None:
+ schema = self._create({"cdc_mode": "streaming"})
+ received: list = []
+
+ def _handler(sender, **kwargs) -> None:
+ received.append(kwargs)
+
+ model_activity_signal.connect(_handler, sender=ExternalDataSchema, weak=False)
+ try:
+ with patch.object(ExternalDataSchema, "_get_before_update") as before_update:
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_last_log_position": "0/5"})
+ assert not before_update.called
+ assert received == []
+ finally:
+ model_activity_signal.disconnect(_handler, sender=ExternalDataSchema)
+
+ def test_interleaved_writes_do_not_clobber(self) -> None:
+ # Two activity-style position writes with an API-style cdc_table_mode write in between —
+ # every key survives because each call re-reads the row before merging.
+ schema = self._create({"cdc_mode": "streaming", "cdc_table_mode": "consolidated"})
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_last_log_position": "0/100"})
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_table_mode": "both"})
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_last_log_position": "0/200"})
+ schema.refresh_from_db()
+ assert schema.sync_type_config == {
+ "cdc_mode": "streaming",
+ "cdc_table_mode": "both",
+ "cdc_last_log_position": "0/200",
+ }
+
+ def test_merges_onto_latest_committed_not_stale_in_memory_copy(self) -> None:
+ # A writer holding a copy loaded before a concurrent commit must not revert that commit.
+ schema = self._create({"cdc_mode": "streaming", "cdc_last_log_position": "0/100"})
+ stale = ExternalDataSchema.objects.get(id=schema.id) # in-memory copy: position 0/100
+ # A concurrent committed write moves the position forward:
+ update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_last_log_position": "0/900"})
+ # The holder of the stale copy now persists an unrelated key through the helper:
+ result = update_sync_type_config_keys(schema.id, self.team.pk, updates={"cdc_table_mode": "both"})
+ # The concurrent position survives; the stale 0/100 never reaches the row.
+ assert result["cdc_last_log_position"] == "0/900"
+ assert result["cdc_table_mode"] == "both"
+ assert stale.sync_type_config["cdc_last_log_position"] == "0/100" # the copy really was stale
+ schema.refresh_from_db()
+ assert schema.sync_type_config["cdc_last_log_position"] == "0/900"
+
+
@pytest.mark.parametrize(
"clickhouse_type,expected",
[