: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(postgres): hand a stray cdc reset to capture instead of failing every run (#117965)
Tom Owerseb753b77c743
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.pyindex acfc0f0f1134..27b0d710a13e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_buffered_dispatch.py@@ -167,9 +167,18 @@ class TestBufferedDispatch:retire.assert_called_once()- def test_a_reset_on_a_streaming_buffered_schema_is_refused(self):- with pytest.raises(ValueError, match="cdc_mode='snapshot'"):- _dispatch(_schema(), _inputs(reset_pipeline=True))+ def test_a_reset_on_a_streaming_buffered_schema_is_handed_to_capture(self):+ hand_reset, clear = MagicMock(), MagicMock()+ schema = _schema(cdc_table_mode="both")+ inputs = _inputs(reset_pipeline=True)++ response = _dispatch(schema, inputs, hand_reset=hand_reset, clear_listing=clear)++ assert hand_reset.call_args_list == [call(schema, ANY, start_capture=False)]+ assert response.reset_handed_over is True+ assert response.lanes is None+ assert list(response.items()) == []+ clear.assert_called_once_with(inputs.job_id, inputs.team_id)@pytest.mark.parametrize("proof_days_ago, expired, reset",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex a5d4cefd91f2..ca0806aa1a43 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -118,6 +118,9 @@ class SourceResponse:a final checkpoint without opening a crash window before the pipeline flushes its last batch."""destination_reset_required: bool = False"""Whether source metadata discovered during setup requires rebuilding the destination table."""+ reset_handed_over: bool = False+ """Whether the source passed this run's reset to another process, so this run must not delete the+ destination table. Wins over `destination_reset_required` and the reset the run was asked for."""lanes: Optional[list[OutputLane]] = None"""Tables this response's items feed, when it feeds more than the one `name` alone describes.None means the single lane built from `name` and `cdc_write_mode`."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.pyindex f7784c98eaa0..bbff3b754ee3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py@@ -2102,7 +2102,7 @@ class PostgresSource("writes. Set it to 'consolidated', 'cdc_only' or 'both'.")- def no_op_tick() -> SourceResponse:+ def no_op_tick(*, reset_handed_over: bool = False) -> SourceResponse:# An empty response no-ops this tick and keeps the schedule alive. Nothing is listed and# nothing is deleted. An earlier attempt of this same job may have stamped a listing, though, and# the workflow completes the job on this response — so the stamp comes off, or a batch@@ -2117,18 +2117,20 @@ class PostgresSource(cdc_write_mode=first_lane.write_mode,# A change stream carries no seekable key, and `supports_resume` defaults to True.supports_resume=False,+ reset_handed_over=reset_handed_over,)job = ExternalDataJob.objects.filter(id=inputs.job_id, team_id=inputs.team_id).first()# A CDC reset must travel through snapshot mode, which re-seeds the table before the buffer- # replays over it; every reset writer does that. Merging the buffer into a wiped table- # instead would leave only the rows changed since.+ # replays over it. Merging the buffer into a wiped table instead would leave only the rows+ # changed since. A reset that reaches a streaming table anyway goes to capture, which puts the+ # table back into snapshot mode. Refusing it would fail every run of the table until a manual reset.+ # This run must not delete the table itself: capture waits for queued batches to land first.if inputs.reset_pipeline:- raise ValueError(- f"reset_pipeline is set on buffered CDC schema {schema.name} while cdc_mode is still "- "'streaming'. Reset it to snapshot (cdc_mode='snapshot') so the re-snapshot path runs."- )+ inputs.logger.warning("cdc_buffered_reset_handed_to_capture", schema_name=schema.name)+ hand_reset_to_capture(schema, inputs.logger, start_capture=False)+ return no_op_tick(reset_handed_over=True)if has_batches_in_flight(schema):# Reading now would stage rows alongside a delivery that is still landing: a previousdiff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex cac3f76d07ce..df8f143eeecc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -1151,7 +1151,9 @@ async def _run(on_resumable_retry_budget: bool = False,) -> PipelineResult:try:- reset_pipeline = reset_pipeline or source_response.destination_reset_required+ reset_pipeline = (+ reset_pipeline or source_response.destination_reset_required+ ) and not source_response.reset_handed_overmodels = await _get_models(job_inputs.run_id)pipeline = v3_pipeline_class(source_response)(diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 5ae680585a61..4d887cecf048 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -58,6 +58,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schUNKNOWN_RESOURCE_PREFIX,UnknownResourceError,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.util import (NonRetryableException,PostHogInternalDatabaseError,@@ -1696,6 +1697,44 @@ def test_a_scheduled_full_refresh_resets_only_while_the_schema_is_due()+ "run_reset,destination_reset_required,reset_handed_over,expected",+ [+ pytest.param(True, False, False, True, id="run_asked_for_a_reset"),+ pytest.param(False, True, False, True, id="source_asked_for_a_reset"),+ pytest.param(True, True, True, False, id="source_handed_the_reset_over"),+ ],+)+async def test_the_pipeline_deletes_the_table_only_for_a_reset_the_source_kept(+ run_reset: bool, destination_reset_required: bool, reset_handed_over: bool, expected: bool+) -> None:+ source_response = SourceResponse(+ name="users",+ items=lambda: iter(()),+ primary_keys=["id"],+ destination_reset_required=destination_reset_required,+ reset_handed_over=reset_handed_over,+ )+ pipeline_cls = mock.MagicMock()+ pipeline_cls.return_value.run = mock.AsyncMock()++ with (+ mock.patch.object(module, "_get_models", new=mock.AsyncMock()),+ mock.patch.object(module, "v3_pipeline_class", return_value=pipeline_cls),+ ):+ await module._run(+ mock.MagicMock(),+ source_response,+ mock.AsyncMock(),+ reset_pipeline=run_reset,+ shutdown_monitor=mock.MagicMock(),+ resumable_source_manager=None,+ )++ assert pipeline_cls.call_args.args[3] is expected++_STORED_WATERMARK = datetime(2026, 6, 14, 15, 33, 31, 802833)_QUEUED_UP_TO = datetime(2026, 6, 20, 8, 0, 0)