: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-warehouse): scope convex resume cursors per endpoint (#67012)
Luke Belton72d33fa914a3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.pyindex b14acfccb58b..ea506406ed34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py@@ -20,11 +20,23 @@ class ResumableSourceManager(Generic[ResumableData]):_inputs: SourceInputs_data_class: type[ResumableData]_logger: FilteringBoundLogger+ _namespace: str | None- def __init__(self, inputs: SourceInputs, data_class: type[ResumableData]):+ def __init__(self, inputs: SourceInputs, data_class: type[ResumableData], namespace: str | None = None):self._inputs = inputsself._data_class = data_classself._logger = inputs.logger+ self._namespace = namespace++ def with_namespace(self, namespace: str) -> "ResumableSourceManager[ResumableData]":+ """Return a sibling manager whose Redis state is isolated under `namespace`.++ A source that reaches more than one endpoint within a single job — where each+ endpoint stores an incompatible cursor format — uses this to keep their resume+ state in separate slots. Without it a retry that switches endpoints could load a+ cursor the other endpoint wrote and replay it against an API that can't parse it.+ """+ return ResumableSourceManager(self._inputs, self._data_class, namespace=namespace)@contextmanagerdef _get_redis(self):@@ -40,7 +52,8 @@ class ResumableSourceManager(Generic[ResumableData]):@propertydef _key(self) -> str:- return f"posthog:data_warehouse:resumable_source:{self._inputs.team_id}:{self._inputs.job_id}"+ base = f"posthog:data_warehouse:resumable_source:{self._inputs.team_id}:{self._inputs.job_id}"+ return f"{base}:{self._namespace}" if self._namespace else basedef _dump_json(self, data: ResumableData) -> str:data_dict = dataclasses.asdict(data)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.pyindex 520f5b1a527b..40562f0d0ff3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py@@ -32,9 +32,17 @@ _CONVEX_RETRY = DEFAULT_RETRY.new()+# list_snapshot cursors are opaque {tablet, id} strings; document_deltas cursors are integer+# `_ts` timestamps. The two are not interchangeable, so each endpoint's resume state is kept+# under its own Redis namespace (see convex_source) to stop a retry that flips between them+# from replaying one endpoint's cursor against the other.+_SNAPSHOT_RESUME_NAMESPACE = "list_snapshot"+_DELTAS_RESUME_NAMESPACE = "document_deltas"++@dataclasses.dataclassclass ConvexResumeConfig:- cursor: int+ cursor: int | strsnapshot: int | None = None@@ -110,7 +118,8 @@ def list_snapshot(which can be used as the starting cursor for document_deltas."""base_url = f"{deploy_url.rstrip('/')}/api/list_snapshot"- cursor: int | None = None+ # Convex returns the snapshot cursor as an opaque {tablet, id} string, not an integer.+ cursor: int | str | None = Nonesnapshot: int | None = Noneresume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None@@ -170,8 +179,19 @@ def document_deltas(current_cursor = cursorresume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ # Only trust an integer resume cursor — document_deltas requires an integer `_ts`. A+ # non-integer here means stale or cross-endpoint state; ignore it and restart from the+ # DB watermark rather than replaying a cursor Convex would reject with a 400.if resume_config is not None:- current_cursor = resume_config.cursor+ if isinstance(resume_config.cursor, int):+ current_cursor = resume_config.cursor+ else:+ # Namespacing should keep this from happening; if it does, surface it rather than+ # silently dropping the saved cursor.+ logger.warning(+ "Discarding non-integer document_deltas resume cursor for table '%s'; restarting from the DB watermark",+ table_name,+ )while True:params: dict[str, Any] = {"tableName": table_name, "cursor": current_cursor, "format": "json"}@@ -254,10 +274,12 @@ def convex_source(def items_generator():if should_use_incremental_field and db_incremental_field_last_value is not None:cursor = int(db_incremental_field_last_value)- for batch in document_deltas(clean_url, deploy_key, table_name, cursor, resumable_source_manager):+ deltas_manager = resumable_source_manager.with_namespace(_DELTAS_RESUME_NAMESPACE)+ for batch in document_deltas(clean_url, deploy_key, table_name, cursor, deltas_manager):yield _normalize_timestamps(batch)else:- for batch in list_snapshot(clean_url, deploy_key, table_name, resumable_source_manager):+ snapshot_manager = resumable_source_manager.with_namespace(_SNAPSHOT_RESUME_NAMESPACE)+ for batch in list_snapshot(clean_url, deploy_key, table_name, snapshot_manager):yield _normalize_timestamps(batch)return SourceResponse(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.pyindex 85da71915f3b..b8938a837d34 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py@@ -34,6 +34,9 @@ def _make_manager(can_resume: bool = False, state: ConvexResumeConfig | None = Nmanager = MagicMock(spec=ResumableSourceManager)manager.can_resume.return_value = can_resumemanager.load_state.return_value = state+ # Endpoint scoping returns a sibling manager; resolve it back to this mock so call+ # assertions still observe the same object.+ manager.with_namespace.return_value = managerreturn manager@@ -217,6 +220,25 @@ class TestDocumentDeltasResumable:assert first_params["cursor"] == 25manager.save_state.assert_not_called()+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")+ def test_non_integer_resume_cursor_is_ignored(self, mock_get: Mock) -> None:+ # A list_snapshot resume cursor ({tablet, id}) leaking into document_deltas must not be+ # replayed — document_deltas requires an integer _ts and Convex 400s on the malformed+ # cursor. Fall back to the db watermark instead.+ saved = ConvexResumeConfig(cursor='{"tablet":"-cxKinhlnLuQp","id":"v9769ybsnjbhc9"}')+ manager = _make_manager(can_resume=True, state=saved)+ mock_get.return_value.get.return_value = _make_response(+ {"values": [{"_id": "b"}], "cursor": 30, "hasMore": False}+ )++ batches = list(document_deltas("https://x.convex.cloud", "key", "t", 10, manager))++ assert batches == [[{"_id": "b"}]]+ first_params = mock_get.return_value.get.call_args_list[0].kwargs["params"]+ assert first_params["cursor"] == 10+ # Discarding a poisoned cursor must not persist new state off the back of it.+ manager.save_state.assert_not_called()+class TestConvexRetryPolicy:@parameterized.expand(