: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
feat(warehouse-sources): add dub analytics and partner program tables (#106633)
Tom Owers99374c33d91e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 6fe1c7aae332..d4ea575efa39 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2681,18 +2681,20 @@ Note: Spec has 36 paths; the only other GETs are file downloads, embedded URL ge## Dub — gaps-Today (11): `click_events`, `commissions`, `customers`, `domains`, `folders`, `lead_events`, `links`, `partners`, `payouts`, `sale_events`, `tags`+Today (23): `analytics_browsers`, `analytics_cities`, `analytics_continents`, `analytics_countries`, `analytics_devices`, `analytics_os`, `analytics_referers`, `analytics_regions`, `analytics_timeseries`, `analytics_triggers`, `click_events`, `commissions`, `customers`, `domains`, `folders`, `lead_events`, `links`, `partner_analytics_timeseries`, `partner_applications`, `partners`, `payouts`, `sale_events`, `tags`Diffed against: <https://spec.speakeasy.com/dub/dub/dub-with-code-samples>-- [ ] `GET /analytics` — Dub's headline metric endpoint - clicks/leads/sales aggregated by timeseries, countries, cities, regions, continents, devices, browsers, os, referers, top_links, top_urls, trigger; none of these breakdown dimensions are reachable from the raw event tables today (high)-- [ ] `GET /partners/analytics` — per-partner clicks/leads/sales/earnings rollup, the core affiliate-program metric (medium)-- [ ] `GET /partners/applications` — pending partner applications for partner-acquisition funnel analysis (medium)+- [x] `GET /analytics` — Dub's headline metric endpoint - clicks/leads/sales aggregated by timeseries, countries, cities, regions, continents, devices, browsers, os, referers, top_links, top_urls, trigger; none of these breakdown dimensions are reachable from the raw event tables today (high)+- [x] `GET /partners/analytics` — per-partner clicks/leads/sales/earnings rollup, the core affiliate-program metric (medium)+- [x] `GET /partners/applications` — pending partner applications for partner-acquisition funnel analysis (medium)- [ ] `GET /bounties/{bountyId}/submissions` — bounty submission records and their approval state (low)- [ ] `GET /links/count` — link counts grouped by domain/tag/folder/userId without paging all links (low)Note: api.dub.co/openapi.json 404s; the live spec is served from spec.speakeasy.com. Coverage of the object model (links, tags, folders, domains, customers, partners, commissions, payouts, and the three event types) is essentially complete - the gap is the aggregation layer.+Note on the aggregation endpoints, added 2026-09-25: `/analytics` is imported as one table per `groupBy` breakdown, because each groupBy returns a different row shape. The `top_links` and `top_urls` breakdowns were deliberately left out - `links` already carries every link's destination URL alongside its lifetime clicks, leads and sales, so both are a grouping over a table we already sync. `/partners/analytics` has no program-wide mode: its handler rejects a request that names neither `partnerId` nor `tenantId`, even though the published spec marks both optional. It is therefore imported by walking every enrolled partner and stamping the partner id onto each row. The per-bucket `earnings` column is what it adds; `/partners` already reports each partner's lifetime totals (`totalClicks`, `totalLeads`, `totalSaleAmount`, `totalCommissions`). `/bounties/{bountyId}/submissions` is not syncable: the spec exposes no endpoint that lists bounties (`GET /bounties` does not exist, and no other response carries a `bountyId`), so there is no way to enumerate the parent IDs to fan out over.+## Dynatrace — gapsToday (20): `applications`, `audit_logs`, `cloud_applications`, `custom_devices`, `databases`, `disks`, `events`, `hosts`, `kubernetes_clusters`, `kubernetes_nodes`, `metric_data_points`, `metrics`, `problems`, `process_groups`, `queues`, `security_problems`, `services`, `slos`, `synthetic_executions`, `synthetic_monitors`diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.pyindex 93f789ec202f..c3ba5fd5fcfe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/canonical_descriptions.py@@ -187,4 +187,143 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"partner": "The partner receiving the payout, embedded as an object.",},},+ "analytics_timeseries": {+ "description": "Workspace-wide clicks, leads, and sales bucketed over time. The bucket size is chosen by Dub from the length of the reporting window.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "start": "The starting timestamp of the interval.",+ "clicks": "The number of clicks in the interval.",+ "leads": "The number of leads in the interval.",+ "sales": "The number of sales in the interval.",+ "saleAmount": "The total amount of sales in the interval, in cents.",+ },+ },+ "analytics_continents": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the continent the visitor came from.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "continent": "The 2-letter code of the continent.",+ "clicks": "The number of clicks from this continent.",+ "leads": "The number of leads from this continent.",+ "sales": "The number of sales from this continent.",+ "saleAmount": "The total amount of sales from this continent, in cents.",+ },+ },+ "analytics_countries": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the country the visitor came from.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "country": "The 2-letter ISO 3166-1 code of the country.",+ "region": 'Always "*" on this table; use analytics_regions for the region breakdown.',+ "city": 'Always "*" on this table; use analytics_cities for the city breakdown.',+ "clicks": "The number of clicks from this country.",+ "leads": "The number of leads from this country.",+ "sales": "The number of sales from this country.",+ "saleAmount": "The total amount of sales from this country, in cents.",+ },+ },+ "analytics_regions": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the region the visitor came from.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "country": "The 2-letter ISO 3166-1 code of the country.",+ "region": "The ISO 3166-2 code of the region.",+ "city": 'Always "*" on this table; use analytics_cities for the city breakdown.',+ "clicks": "The number of clicks from this region.",+ "leads": "The number of leads from this region.",+ "sales": "The number of sales from this region.",+ "saleAmount": "The total amount of sales from this region, in cents.",+ },+ },+ "analytics_cities": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the city the visitor came from.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "country": "The 2-letter ISO 3166-1 code of the country.",+ "region": "The ISO 3166-2 code of the region.",+ "city": "The name of the city.",+ "clicks": "The number of clicks from this city.",+ "leads": "The number of leads from this city.",+ "sales": "The number of sales from this city.",+ "saleAmount": "The total amount of sales from this city, in cents.",+ },+ },+ "analytics_devices": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the visitor's device type.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "device": "The type of device (e.g. desktop, mobile, tablet).",+ "clicks": "The number of clicks from this device.",+ "leads": "The number of leads from this device.",+ "sales": "The number of sales from this device.",+ "saleAmount": "The total amount of sales from this device, in cents.",+ },+ },+ "analytics_browsers": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the visitor's browser.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "browser": "The name of the browser.",+ "clicks": "The number of clicks from this browser.",+ "leads": "The number of leads from this browser.",+ "sales": "The number of sales from this browser.",+ "saleAmount": "The total amount of sales from this browser, in cents.",+ },+ },+ "analytics_os": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the visitor's operating system.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "os": "The name of the operating system.",+ "clicks": "The number of clicks from this operating system.",+ "leads": "The number of leads from this operating system.",+ "sales": "The number of sales from this operating system.",+ "saleAmount": "The total amount of sales from this operating system, in cents.",+ },+ },+ "analytics_referers": {+ "description": "Workspace-wide clicks, leads, and sales broken down by the referring domain.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "referer": 'The domain the visitor arrived from, or "(direct)" when there was no referrer.',+ "clicks": "The number of clicks from this referer.",+ "leads": "The number of leads from this referer.",+ "sales": "The number of sales from this referer.",+ "saleAmount": "The total amount of sales from this referer, in cents.",+ },+ },+ "analytics_triggers": {+ "description": "Workspace-wide clicks, leads, and sales broken down by how the short link was opened.",+ "docs_url": "https://dub.co/docs/api-reference/analytics/retrieve-analytics",+ "columns": {+ "trigger": "How the link was triggered (link for a normal visit, qr for a QR code scan).",+ "clicks": "The number of clicks from this trigger.",+ "leads": "The number of leads from this trigger.",+ "sales": "The number of sales from this trigger.",+ "saleAmount": "The total amount of sales from this trigger, in cents.",+ },+ },+ "partner_analytics_timeseries": {+ "description": "One enrolled partner's clicks, leads, sales, and earnings bucketed over time. One row per partner per interval. Requires a Dub partner program.",+ "docs_url": "https://dub.co/docs/api-reference/partners/retrieve-analytics",+ "columns": {+ "partnerId": "The unique ID of the partner the interval belongs to.",+ "start": "The starting timestamp of the interval.",+ "clicks": "The number of clicks in the interval.",+ "leads": "The number of leads in the interval.",+ "sales": "The number of sales in the interval.",+ "saleAmount": "The total amount of sales in the interval, in cents.",+ "earnings": "The total partner earnings in the interval, in cents.",+ },+ },+ "partner_applications": {+ "description": "A pending application to join the workspace's partner program. Requires a Dub partner program.",+ "docs_url": "https://dub.co/docs/api-reference/partners/list-partner-applications",+ "columns": {+ "id": "The unique ID of the application.",+ "createdAt": "The date the application was submitted.",+ "partner": "The partner who applied, embedded as an object with their profile and social handles.",+ "applicationFormData": "The answers the partner gave on the program's application form, as label and value pairs.",+ },+ },}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 8fa99649627b..01299781a4e6 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@@ -1,3 +1,4 @@+from collections.abc import Iteratorfrom datetime import date, datetimefrom typing import Any, Optional@@ -14,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BasePaginator,PageNumberPaginator,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (Endpoint,@@ -47,7 +49,8 @@ _PARTNER_PROGRAM_404_IGNORE: list[ResponseAction] = [{"status_code": 404, "actioclass DubResumeConfig:page: Optional[int] = Nonestarting_after: Optional[str] = None- # Which /links scope the cursor belongs to; see DubLinksScopePaginator.+ # Which scope the walk reached: a /links folder (DubLinksScopePaginator) or the next+ # partner to read (_partner_analytics_rows).scope_index: Optional[int] = None@@ -206,6 +209,79 @@ def _fetch_folder_ids(api_key: str) -> list[str]:page += 1+def _fetch_partner_ids(api_key: str) -> list[str]:+ """Every partner enrolled in the program, so /partners/analytics can be read per partner."""+ config = DUB_ENDPOINTS["partners"]+ session = _make_session(api_key)+ partner_ids: list[str] = []+ page = 1++ while True:+ params: dict[str, Any] = {**config.params, "page": page, config.page_size_param: config.page_size}+ res = session.get(+ f"{DUB_BASE_URL}{config.path}",+ params=params,+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if res.status_code in (401, 403, 404):+ # Same gating as the partners table itself: no program, or a plan that cannot+ # reach it, leaves nothing to walk.+ return partner_ids+ res.raise_for_status()++ rows = res.json()+ if not isinstance(rows, list) or not rows:+ return partner_ids++ partner_ids.extend(str(row["id"]) for row in rows if isinstance(row, dict) and row.get("id"))+ if len(rows) < config.page_size:+ return partner_ids+ page += 1+++def _partner_analytics_rows(+ api_key: str,+ config: DubEndpointConfig,+ resumable_source_manager: ResumableSourceManager[DubResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Read /partners/analytics once per enrolled partner.++ Dub rejects the request unless it names a partner, so the endpoint has no program-wide+ mode and the table is the union of the per-partner series. The response repeats only the+ bucket timestamp, so each row carries the partner it came from to keep the key unique.+ """+ partner_ids = _fetch_partner_ids(api_key)++ start_index = 0+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.scope_index is not None:+ start_index = min(resume.scope_index, len(partner_ids))++ session = _make_session(api_key)+ for index in range(start_index, len(partner_ids)):+ partner_id = partner_ids[index]+ res = session.get(+ f"{DUB_BASE_URL}{config.path}",+ params={**config.params, "partnerId": partner_id},+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if res.status_code == 404:+ # A partner can leave the program between the list call and this one.+ continue+ res.raise_for_status()++ rows = res.json()+ if not isinstance(rows, list) or not rows:+ continue++ # Staged before the yield it covers, so a crash resumes at the next unwritten partner.+ resumable_source_manager.save_state(DubResumeConfig(scope_index=index + 1))+ yield [{**row, "partnerId": partner_id} for row in rows if isinstance(row, dict)]++def _format_timestamp(value: Any) -> str:if isinstance(value, datetime | date):return value.isoformat()@@ -215,6 +291,8 @@ def _format_timestamp(value: Any) -> str:def _build_paginator(config: DubEndpointConfig, folder_ids: list[str]) -> BasePaginator:if config.folder_scoped:return DubLinksScopePaginator(page_size=config.page_size, folder_ids=folder_ids)+ if config.pagination == "single":+ return SinglePagePaginator()if config.pagination == "cursor":return DubCursorPaginator(page_size=config.page_size)return PageNumberPaginator(base_page=1, page_param="page", total_path=None)@@ -255,7 +333,9 @@ def get_resource() -> EndpointResource:config = DUB_ENDPOINTS[endpoint]- params: dict[str, Any] = {**config.params, config.page_size_param: config.page_size}+ params: dict[str, Any] = {**config.params}+ if config.pagination != "single":+ params[config.page_size_param] = config.page_sizeif config.event_type is not None:if should_use_incremental_field and db_incremental_field_last_value is not None:@@ -335,6 +415,17 @@ def dub_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:endpoint_config = DUB_ENDPOINTS[endpoint]++ if endpoint_config.partner_scoped:+ return SourceResponse(+ name=endpoint,+ items=lambda: _partner_analytics_rows(api_key, endpoint_config, resumable_source_manager),+ primary_keys=list(endpoint_config.primary_keys),+ partition_count=1,+ partition_size=1,+ sort_mode=endpoint_config.sort_mode,+ )+folder_ids = _fetch_folder_ids(api_key) if endpoint_config.folder_scoped else []config: RESTAPIConfig = {@@ -379,7 +470,7 @@ def dub_source(return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=[endpoint_config.primary_key],+ primary_keys=list(endpoint_config.primary_keys),partition_count=1,partition_size=1,partition_mode="datetime" if endpoint_config.partition_key else None,@@ -390,8 +481,10 @@ def dub_source(def _probe_params(config: DubEndpointConfig) -> dict[str, Any]:- params: dict[str, Any] = {**config.params, config.page_size_param: 1}- if config.event_type is not None:+ params: dict[str, Any] = {**config.params}+ if config.pagination != "single":+ params[config.page_size_param] = 1+ if config.event_type is not None or "interval" in params:# Keep the probe cheap — a 24h window is enough to establish plan access.params["interval"] = "24h"return paramsdiff --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 b21e67f54c40..a6b80d7cf0a4 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@@ -14,11 +14,12 @@ DUB_BASE_URL = "https://api.dub.co"class DubEndpointConfig:name: strpath: str- # "cursor" = startingAfter cursor pagination; "page" = 1-based page-number pagination.- pagination: Literal["cursor", "page"]+ # "cursor" = startingAfter cursor pagination; "page" = 1-based page-number pagination;+ # "single" = the whole table arrives in one response, as the aggregate endpoints do.+ pagination: Literal["cursor", "page", "single"]page_size: int = 100page_size_param: str = "pageSize"- primary_key: str = "id"+ primary_keys: tuple[str, ...] = ("id",)partition_key: Optional[str] = "createdAt"partition_format: PartitionFormat = "month"sort_mode: SortMode = "desc"@@ -28,6 +29,8 @@ class DubEndpointConfig:# /links returns only the links sitting outside a folder unless `folderId` is passed, so# this endpoint has to be walked once per folder as well to import the whole workspace.folder_scoped: bool = False+ # Walked once per enrolled partner by a custom iterator; see _partner_analytics_rows.+ partner_scoped: bool = Falsedef _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpointConfig:@@ -39,7 +42,7 @@ def _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpoint# Dub's stricter per-second analytics rate limits.page_size=500,page_size_param="limit",- primary_key=primary_key,+ primary_keys=(primary_key,),partition_key="timestamp",partition_format="week",sort_mode="asc",@@ -48,6 +51,19 @@ def _event_endpoint(name: str, event_type: str, primary_key: str) -> DubEndpoint)+# /analytics answers a 24h window of clicks only unless both defaults are widened, and each+# groupBy returns a different row shape, so every breakdown is imported as its own table.+def _analytics_endpoint(name: str, group_by: str, primary_keys: tuple[str, ...]) -> DubEndpointConfig:+ return DubEndpointConfig(+ name=name,+ path="/analytics",+ pagination="single",+ primary_keys=primary_keys,+ partition_key=None,+ params={"groupBy": group_by, "event": "composite", "interval": "all"},+ )++DUB_ENDPOINTS: dict[str, DubEndpointConfig] = {"links": DubEndpointConfig(name="links", path="/links", pagination="cursor", folder_scoped=True),"click_events": _event_endpoint("click_events", "clicks", primary_key="click_id"),@@ -74,6 +90,33 @@ DUB_ENDPOINTS: dict[str, DubEndpointConfig] = {),"commissions": DubEndpointConfig(name="commissions", path="/commissions", pagination="cursor"),"payouts": DubEndpointConfig(name="payouts", path="/payouts", pagination="page"),+ "partner_applications": DubEndpointConfig(+ name="partner_applications", path="/partners/applications", pagination="page"+ ),+ # Dub rejects a /partners/analytics request that names no partner, so there is no+ # program-wide series to read: the table is the union of each partner's series. It carries+ # earnings per bucket, which neither /partners nor the workspace-level /analytics reports.+ "partner_analytics_timeseries": DubEndpointConfig(+ name="partner_analytics_timeseries",+ path="/partners/analytics",+ pagination="single",+ primary_keys=("partnerId", "start"),+ partition_key=None,+ params={"groupBy": "timeseries", "interval": "all"},+ partner_scoped=True,+ ),+ "analytics_timeseries": _analytics_endpoint("analytics_timeseries", "timeseries", ("start",)),+ "analytics_continents": _analytics_endpoint("analytics_continents", "continents", ("continent",)),+ "analytics_countries": _analytics_endpoint("analytics_countries", "countries", ("country",)),+ # Dub repeats the whole geo path on every row, and region and city names recur across+ # countries, so the narrower cuts need the parent columns in the key to stay unique.+ "analytics_regions": _analytics_endpoint("analytics_regions", "regions", ("country", "region")),+ "analytics_cities": _analytics_endpoint("analytics_cities", "cities", ("country", "region", "city")),+ "analytics_devices": _analytics_endpoint("analytics_devices", "devices", ("device",)),+ "analytics_browsers": _analytics_endpoint("analytics_browsers", "browsers", ("browser",)),+ "analytics_os": _analytics_endpoint("analytics_os", "os", ("os",)),+ "analytics_referers": _analytics_endpoint("analytics_referers", "referers", ("referer",)),+ "analytics_triggers": _analytics_endpoint("analytics_triggers", "triggers", ("trigger",)),}ENDPOINTS = tuple(DUB_ENDPOINTS.keys())@@ -92,9 +135,24 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {# Endpoints gated by Dub plan or product setup: /events needs a Business plan or higher,# /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")+PLAN_GATED_ENDPOINTS = (+ "click_events",+ "lead_events",+ "sale_events",+ "partners",+ "commissions",+ "payouts",+ "partner_applications",+ "partner_analytics_timeseries",+)-# These three resolve the workspace's default partner program before they read anything, so a+# These 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")+PARTNER_PROGRAM_ENDPOINTS = (+ "partners",+ "commissions",+ "payouts",+ "partner_applications",+ "partner_analytics_timeseries",+)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 b814f3ede25e..18b15210ad4c 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@@ -29,6 +29,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settinPARTNER_PROGRAM_ENDPOINTS,)+ANALYTICS_ENDPOINTS = tuple(name for name, config in DUB_ENDPOINTS.items() if config.path == "/analytics")+SINGLE_PAGE_ENDPOINTS = tuple(+ name for name, config in DUB_ENDPOINTS.items() if config.pagination == "single" and not config.partner_scoped+)+# partner_analytics_timeseries is walked by a custom iterator, not by paginating one path,+# so the shared request-shaping tests do not apply to it.+PAGINATED_PARTNER_PROGRAM_ENDPOINTS = tuple(+ name for name in PARTNER_PROGRAM_ENDPOINTS if not DUB_ENDPOINTS[name].partner_scoped+)+def _rows(n: int, prefix: str = "row") -> list[dict[str, Any]]:return [{"id": f"{prefix}-{i}", "createdAt": "2026-01-01T00:00:00.000Z"} for i in range(n)]@@ -205,7 +215,21 @@ class TestGetResource:assert resource["write_disposition"] == "replace"params = _params(resource)config = DUB_ENDPOINTS[endpoint]- assert params[config.page_size_param] == config.page_size+ if config.pagination == "single":+ # The aggregate endpoints reject an unknown page-size param with a 422.+ assert config.page_size_param not in params+ else:+ assert params[config.page_size_param] == config.page_size++ @pytest.mark.parametrize("endpoint", ANALYTICS_ENDPOINTS)+ def test_analytics_endpoints_widen_both_dub_defaults(self, endpoint: str) -> None:+ # /analytics defaults to a 24h window and to clicks-only metrics. Leaving either+ # default in place still returns a well-formed table, just a near-empty one.+ params = _params(get_resource(endpoint, False, None))++ assert params["interval"] == "all"+ assert params["event"] == "composite"+ assert params["groupBy"] == DUB_ENDPOINTS[endpoint].params["groupBy"]def test_incremental_run_uses_merge_disposition(self) -> None:resource = get_resource("sale_events", True, None)@@ -384,12 +408,113 @@ class TestDubSourceResumeBehavior:assert sent_params[0]["page"] == 7+class TestSinglePageEndpoints:+ @pytest.mark.parametrize("endpoint", SINGLE_PAGE_ENDPOINTS)+ def test_aggregate_endpoints_stop_after_one_request(self, endpoint: str) -> None:+ # These return the whole table in one body with no next-page marker, so a paginator+ # that kept asking would re-import the same rows until the run was killed.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent_params, pages = _drive_source(endpoint, manager, [_make_http_response(_rows(3))])++ assert len(sent_params) == 1+ assert pages == [_rows(3)]+ assert DUB_ENDPOINTS[endpoint].page_size_param not in sent_params[0]++ def test_composite_primary_keys_all_reach_the_source_response(self) -> None:+ # The geo breakdowns repeat region and city names across countries, so a key that+ # kept only the leaf dimension would merge unrelated rows on top of each other.+ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"):+ response = dub_source(+ api_key="dub_test",+ endpoint="analytics_cities",+ team_id=1,+ job_id="job",+ resumable_source_manager=MagicMock(spec=ResumableSourceManager),+ )++ expected = list(DUB_ENDPOINTS["analytics_cities"].primary_keys)+ assert len(expected) > 1+ assert response.primary_keys == expected+++class TestPartnerAnalyticsWalk:+ def _drive(self, manager: MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[Any]]:+ sent: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_get(_url: str, **kwargs: Any) -> Response:+ sent.append(dict(kwargs.get("params") or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.dub.dub.make_tracked_session"+ ) as MockSession:+ MockSession.return_value.get.side_effect = fake_get+ response = dub_source(+ api_key="dub_test",+ endpoint="partner_analytics_timeseries",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )+ return sent, list(cast(Iterable[Any], response.items()))++ def test_every_request_names_a_partner_and_rows_carry_it(self) -> None:+ # Dub rejects a /partners/analytics request that names no partner, so a walk that+ # skipped the partnerId would fail every import. The response repeats only the bucket+ # timestamp, so unstamped rows from two partners would also collide on the key.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ sent, pages = self._drive(+ manager,+ [+ _make_http_response([{"id": "pn_a"}, {"id": "pn_b"}]),+ _make_http_response([{"start": "2026-01-01", "clicks": 1}]),+ _make_http_response([{"start": "2026-01-01", "clicks": 2}]),+ ],+ )++ analytics_requests = sent[1:]+ assert [p["partnerId"] for p in analytics_requests] == ["pn_a", "pn_b"]+ assert all(p["groupBy"] == "timeseries" and p["interval"] == "all" for p in analytics_requests)+ assert [row["partnerId"] for page in pages for row in page] == ["pn_a", "pn_b"]++ def test_walk_resumes_at_the_partner_after_the_last_written_one(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = DubResumeConfig(scope_index=1)++ sent, pages = self._drive(+ manager,+ [+ _make_http_response([{"id": "pn_a"}, {"id": "pn_b"}]),+ _make_http_response([{"start": "2026-01-01", "clicks": 2}]),+ ],+ )++ assert [p.get("partnerId") for p in sent[1:]] == ["pn_b"]+ assert [call.args[0] for call in manager.save_state.call_args_list] == [DubResumeConfig(scope_index=2)]++ def test_workspace_without_a_partner_program_yields_no_rows(self) -> None:+ # /partners answers 404 without a program, which is an empty table rather than a+ # broken sync, so the walk must not raise.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, pages = self._drive(manager, [_make_http_response({"error": {"message": "Program not found"}}, 404)])++ assert pages == []++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)+ @pytest.mark.parametrize("endpoint", PAGINATED_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 = Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.pyindex 92d219c36464..bfd202bbd52d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dub/tests/test_dub_source.py@@ -1,7 +1,10 @@import pytestfrom unittest.mock import patch-from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.dub.settings import (+ ENDPOINTS,+ PLAN_GATED_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.dub.source import DubSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.dub import DubSourceConfig@@ -63,7 +66,7 @@ class TestDubSource:probed = [call.args[1] for call in mock_check.call_args_list]assert len([e for e in probed if e in EVENT_ENDPOINTS]) == 1- assert set(probed) - set(EVENT_ENDPOINTS) == {"partners", "commissions", "payouts"}+ assert set(probed) - set(EVENT_ENDPOINTS) == set(PLAN_GATED_ENDPOINTS) - set(EVENT_ENDPOINTS)for endpoint in EVENT_ENDPOINTS:assert permissions[endpoint] == "Business plan required"assert permissions["links"] is None