: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): let dub sync workspaces without a partner program (#103795)
Tom Owers8990167dbfdf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.pyindex dd64a5f968e0..8fa99649627b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/dub.py@@ -18,12 +18,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (Endpoint,EndpointResource,+ ResponseAction,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import (DUB_BASE_URL,DUB_ENDPOINTS,+ PARTNER_PROGRAM_ENDPOINTS,DubEndpointConfig,)@@ -31,6 +33,15 @@ REQUEST_TIMEOUT_SECONDS = 30# /folders rejects a larger page with a 422.FOLDERS_PAGE_SIZE = 50+NO_PARTNER_PROGRAM_MESSAGE = (+ "This Dub workspace has no partner program, so there is nothing to sync here. "+ "Set up Dub Partners in your workspace, then refresh this table list."+)++# A workspace without a partner program answers the whole table with 404, which is an empty+# table rather than a broken sync. Let the run finish so the workspace's other tables still land.+_PARTNER_PROGRAM_404_IGNORE: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]+@frozenclass DubResumeConfig:@@ -263,6 +274,9 @@ def get_resource("paginator": _build_paginator(config, folder_ids or []),}+ if endpoint in PARTNER_PROGRAM_ENDPOINTS:+ endpoint_config["response_actions"] = _PARTNER_PROGRAM_404_IGNORE+return {"name": config.name,"table_name": config.name,@@ -393,8 +407,9 @@ def _error_message(res: Response) -> str:def check_endpoint_access(api_key: str, endpoint: str) -> str | None:"""Probe one endpoint; return None when reachable, or a short reason when access is denied.- Only a real denial (401/403) counts as unreachable — throttles, 5xx, and network blips- are treated as reachable so a transient error never hides a table from the schema picker.+ Only a real denial (401/403, plus the partner-program 404) counts as unreachable — throttles,+ 5xx, and network blips are treated as reachable so a transient error never hides a table from+ the schema picker."""config = DUB_ENDPOINTS[endpoint]try:@@ -407,6 +422,10 @@ def check_endpoint_access(api_key: str, endpoint: str) -> str | None:)if res.status_code in (401, 403):return _error_message(res)+ if res.status_code == 404 and endpoint in PARTNER_PROGRAM_ENDPOINTS:+ # Dub's own copy here is a bare "Program not found", which reads as a bug to a user+ # who never had a program.+ return NO_PARTNER_PROGRAM_MESSAGEreturn Noneexcept Exception:return Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.pyindex ab56dff6a7fa..b21e67f54c40 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/settings.py@@ -93,3 +93,8 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {# /payouts needs a Business partner-program plan, and /partners + /commissions require a# partner program. Used by get_endpoint_permissions to surface per-table reachability.PLAN_GATED_ENDPOINTS = ("click_events", "lead_events", "sale_events", "partners", "commissions", "payouts")++# These three resolve the workspace's default partner program before they read anything, so a+# workspace without Dub Partners gets 404 not_found on the list endpoint itself rather than a+# plan error. Their paths are static and always valid, so a 404 here can only mean "no program".+PARTNER_PROGRAM_ENDPOINTS = ("partners", "commissions", "payouts")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.pyindex dcac5c223813..b814f3ede25e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub.py@@ -7,10 +7,12 @@ import pytestfrom unittest.mock import MagicMock, patchfrom requests import Request, Response+from requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub import (+ NO_PARTNER_PROGRAM_MESSAGE,DubCursorPaginator,DubLinksScopePaginator,DubResumeConfig,@@ -21,7 +23,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub imget_resource,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import DUB_ENDPOINTS, ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import (+ DUB_ENDPOINTS,+ ENDPOINTS,+ PARTNER_PROGRAM_ENDPOINTS,+)def _rows(n: int, prefix: str = "row") -> list[dict[str, Any]]:@@ -235,6 +241,42 @@ class TestScrubLinkPassword:assert _scrub_link_password(row) == row+def _drive_source(+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> tuple[list[dict[str, Any]], list[Any]]:+ """Drive ``dub_source`` with a mocked HTTP session; returns per-request params and yielded rows."""+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = dub_source(+ api_key="dub_test",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ rows = list(cast(Iterable[Any], source_response.items()))+ return sent_params, rows++class TestDubSourceResumeBehavior:def _drive(self,@@ -244,33 +286,14 @@ class TestDubSourceResumeBehavior:should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,) -> list[dict[str, Any]]:- """Drive ``dub_source`` with a mocked HTTP session; returns per-request params."""- sent_params: list[dict[str, Any]] = []- response_iter = iter(responses)-- def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:- sent_params.append(dict(request.params or {}))- return next(response_iter)-- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"- ) as MockSession:- mock_session = MockSession.return_value- mock_session.headers = {}- mock_session.prepare_request.side_effect = lambda req: req- mock_session.send.side_effect = fake_send-- source_response = dub_source(- api_key="dub_test",- endpoint=endpoint,- team_id=1,- job_id="job",- resumable_source_manager=manager,- should_use_incremental_field=should_use_incremental_field,- db_incremental_field_last_value=db_incremental_field_last_value,- )- list(cast(Iterable[Any], source_response.items()))- return sent_params+ sent_params, _ = _drive_source(+ endpoint,+ manager,+ responses,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ return sent_paramsdef test_cursor_endpoint_saves_cursor_after_each_non_terminal_page(self) -> None:manager = MagicMock(spec=ResumableSourceManager)@@ -361,6 +384,31 @@ class TestDubSourceResumeBehavior:assert sent_params[0]["page"] == 7+class TestPartnerProgramTablesWithoutAProgram:+ # Dub resolves the workspace's default partner program before reading any of these lists,+ # so a workspace without one gets this 404 on the table's own list endpoint.+ _NOT_FOUND = {"error": {"code": "not_found", "message": "Program not found"}}++ @pytest.mark.parametrize("endpoint", PARTNER_PROGRAM_ENDPOINTS)+ def test_404_ends_the_table_instead_of_failing_the_sync(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, rows = _drive_source(endpoint, manager, [_make_http_response(self._NOT_FOUND, 404)])++ assert len(sent_params) == 1+ assert rows == []++ def test_404_elsewhere_still_fails(self) -> None:+ # The tolerance is scoped to the partner-program tables; a 404 anywhere else is a real+ # error and must not be swallowed into an empty table.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with pytest.raises(HTTPError):+ _drive_source("customers", manager, [_make_http_response(self._NOT_FOUND, 404)])++class TestMakeSession:def test_disables_sample_capture(self) -> None:# Every Dub path (sync + both credential probes) builds its session here. Dub payloads@@ -432,6 +480,25 @@ class TestCredentialValidation:):assert check_endpoint_access("dub_test", "click_events") == "Requires a Business plan or higher."+ @pytest.mark.parametrize("endpoint", PARTNER_PROGRAM_ENDPOINTS)+ def test_check_endpoint_access_reads_404_on_partner_tables_as_no_program(self, endpoint: str) -> None:+ # Dub answers these with a bare "Program not found", which reads as a broken connector+ # to a user who never had a partner program.+ response = _make_http_response({"error": {"code": "not_found", "message": "Program not found"}}, 404)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session",+ return_value=self._mock_session(response),+ ):+ assert check_endpoint_access("dub_test", endpoint) == NO_PARTNER_PROGRAM_MESSAGE++ def test_check_endpoint_access_leaves_other_tables_reachable_on_404(self) -> None:+ response = _make_http_response({"error": {"code": "not_found", "message": "Program not found"}}, 404)+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session",+ return_value=self._mock_session(response),+ ):+ assert check_endpoint_access("dub_test", "customers") is None+@pytest.mark.parametrize("status_code", [200, 429, 500])def test_check_endpoint_access_only_denials_block(self, status_code: int) -> None:# A throttle or transient 5xx must never hide a table from the schema picker.