: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(braze): sync campaign, canvas, event and workspace KPI analytics (#100171)
Tom Owers5fc3f96d3b11
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 0f6f5580993a..66b68b8dc8c3 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@@ -928,14 +928,14 @@ Note: Source uses the Braintree GraphQL API (payments.braintree-api.com/graphql)## Braze — gaps-Today (6): `campaigns`, `canvases`, `content_blocks`, `email_templates`, `events`, `segments`+Today (13): `campaign_analytics`, `campaigns`, `canvas_analytics`, `canvases`, `content_blocks`, `email_templates`, `event_analytics`, `events`, `kpi_dau`, `kpi_mau`, `kpi_new_users`, `kpi_uninstalls`, `segments`Diffed against: <https://www.braze.com/docs/sitemap.xml>-- [ ] `/campaigns/data_series` — per-campaign per-day sends, opens, clicks, conversions — Braze's headline metric (high)-- [ ] `/canvas/data_series` — per-canvas per-step time series; the canvases table is unusable analytically without it (high)-- [ ] `/events/data_series` — custom event occurrence time series for the event names already synced (high)-- [ ] `/kpi/dau/data_series, /kpi/mau/data_series, /kpi/new_users/data_series, /kpi/uninstalls/data_series` — workspace-level DAU/MAU/new users/uninstalls trends (high)+- [x] `/campaigns/data_series` — per-campaign per-day sends, opens, clicks, conversions — Braze's headline metric (high)+- [x] `/canvas/data_series` — per-canvas per-step time series; the canvases table is unusable analytically without it (high)+- [x] `/events/data_series` — custom event occurrence time series for the event names already synced (high)+- [x] `/kpi/dau/data_series, /kpi/mau/data_series, /kpi/new_users/data_series, /kpi/uninstalls/data_series` — workspace-level DAU/MAU/new users/uninstalls trends (high)- [ ] `/segments/data_series` — segment size over time, the only way to trend audience growth (high)- [ ] `/campaigns/details` — enriches the campaign list with message variants, channels, tags and conversion behaviors (high)- [ ] `/canvas/details` — canvas step and variant structure needed to attribute canvas analytics (high)@@ -945,7 +945,7 @@ Diffed against: <https://www.braze.com/docs/sitemap.xml>- [ ] `/email/unsubscribes and /email/hard_bounces` — deliverability events joinable to campaigns (medium)- [ ] `/catalogs and /catalogs/{catalog_name}/items` — lookup tables resolving catalog item ids referenced in personalization and purchases (medium)-Note: Braze has no OpenAPI/llms.txt (llms.txt 404s), so I enumerated every /docs/api/endpoints/\* page from the docs sitemap and then opened the individual pages to read the literal REST paths (confirmed /campaigns/data_series, /canvas/data_series, /segments/data_series, /events/data_series, /sends/data_series, /kpi/dau/data_series, /sessions/data_series, /purchases/revenue_series, /email/unsubscribes, /canvas/details, /catalogs, /custom_attributes). Today the connector syncs only the six `list` endpoints — every analytics (`data\_series`) endpoint, which is what Braze users actually report on, is missing.+Note: Braze has no OpenAPI/llms.txt (llms.txt 404s), so I enumerated every /docs/api/endpoints/\* page from the docs sitemap and then opened the individual pages to read the literal REST paths (confirmed /campaigns/data_series, /canvas/data_series, /segments/data_series, /events/data_series, /sends/data_series, /kpi/dau/data_series, /sessions/data_series, /purchases/revenue_series, /email/unsubscribes, /canvas/details, /catalogs, /custom_attributes). The connector now syncs the campaign, Canvas, custom event and workspace KPI `data\_series` endpoints alongside the six `list` endpoints; the remaining analytics gaps are listed above.## Breezometer — adequatediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/braze.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/braze.pyindex d000ea7aa1db..9e3535075925 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/braze.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/braze.py@@ -1,19 +1,26 @@import re+import jsonimport dataclasses-from collections.abc import Iterator-from datetime import UTC, date, datetime+from collections.abc import Callable, Iterable, Iterator+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import urlparsefrom requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import (+ BRAZE_DATA_SERIES_ENDPOINTS,BRAZE_ENDPOINTS,+ DATA_SERIES_HISTORY_DAYS,+ DEFAULT_PROBE_TARGET,+ BrazeDataSeriesConfig,BrazeEndpointConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ Resource,RESTAPIConfig,rest_api_resource,)@@ -121,9 +128,9 @@ class BrazeOffsetPaginator(BasePaginator):def validate_credentials(- api_key: str, base_url: str, path: str = "/campaigns/list", team_id: int | None = None+ api_key: str, base_url: str, probe_target: str = DEFAULT_PROBE_TARGET, team_id: int | None = None) -> tuple[bool, str | None]:- """Probe a Braze list endpoint to confirm the REST API key is valid.+ """Probe a Braze endpoint to confirm the REST API key is valid.Braze keys are scoped per endpoint, so a 403 means the key is genuine butlacks the probed scope — the caller decides whether to accept that.@@ -135,7 +142,7 @@ def validate_credentials(if not host_ok:return False, host_err or HOST_NOT_ALLOWED_ERROR- url = f"{normalize_base_url(base_url)}{path}?page=0"+ url = f"{normalize_base_url(base_url)}{probe_target}"ok, status = validate_via_probe(# No redirects: keep the probe pinned to the validated host (SSRF hardening).lambda: make_tracked_session(allow_redirects=False, redact_values=(api_key,)),@@ -153,30 +160,24 @@ def validate_credentials(return False, f"Braze API returned status {status}"-def braze_source(+def _paginator_for(config: BrazeEndpointConfig) -> tuple[BasePaginator, str]:+ if config.pagination == "page":+ return PageNumberPaginator(base_page=0), "page"+ return BrazeOffsetPaginator(limit=config.page_size), "offset"+++def _list_resource(api_key: str,base_url: str,- endpoint: str,+ config: BrazeEndpointConfig,team_id: int,job_id: str,- resumable_source_manager: ResumableSourceManager[BrazeResumeConfig],- should_use_incremental_field: bool = False,+ paginator: BasePaginator,+ params: Optional[dict[str, Any]] = None,db_incremental_field_last_value: Optional[Any] = None,-) -> SourceResponse:- config = BRAZE_ENDPOINTS[endpoint]-- params: dict[str, Any] = {}- if config.modified_after_param and should_use_incremental_field and db_incremental_field_last_value:- params[config.modified_after_param] = _format_modified_after(db_incremental_field_last_value)-- paginator: BasePaginator- if config.pagination == "page":- paginator = PageNumberPaginator(base_page=0)- state_key = "page"- else:- paginator = BrazeOffsetPaginator(limit=config.page_size)- state_key = "offset"-+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,+ initial_paginator_state: Optional[dict[str, Any]] = None,+) -> Resource:rest_config: RESTAPIConfig = {"client": {"base_url": normalize_base_url(base_url),@@ -191,10 +192,10 @@ def braze_source("resource_defaults": None,"resources": [{- "name": endpoint,+ "name": config.name,"endpoint": {"path": config.path,- "params": params,+ "params": params or {},# Braze omits the data key when there is nothing to return, so a missing# key is a normal end-of-data page — don't set data_selector_required."data_selector": config.data_key,@@ -203,6 +204,217 @@ def braze_source(],}+ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+++def _to_date(value: Any) -> Optional[date]:+ parsed = parse_datetime_value(value)+ return parsed.date() if parsed is not None else None+++def _series_span_days(+ should_use_incremental_field: bool, db_incremental_field_last_value: Optional[Any], today: date+) -> int:+ """Days of history a run asks for, measured back from today."""+ watermark = _to_date(db_incremental_field_last_value) if should_use_incremental_field else None+ if watermark is None:+ return DATA_SERIES_HISTORY_DAYS+ # The watermark day is re-read rather than skipped: Braze can still be restating it.+ return max(1, min((today - watermark).days + 1, DATA_SERIES_HISTORY_DAYS))+++def _series_windows(max_length_days: int, span_days: int, now: datetime) -> list[tuple[datetime, int]]:+ """Split a span into (ending_at, length) windows Braze accepts, oldest first.++ Braze caps `length` per endpoint — 14 days on Canvas, 100 elsewhere — so a longer span is+ covered by stepping `ending_at` back one whole window at a time.+ """+ windows: list[tuple[datetime, int]] = []+ ending = now+ remaining = span_days+ while remaining > 0:+ length = min(remaining, max_length_days)+ windows.append((ending, length))+ remaining -= length+ ending -= timedelta(days=length)+ return list(reversed(windows))+++def _encode_json_fields(row: dict[str, Any], json_fields: tuple[str, ...]) -> dict[str, Any]:+ for name in json_fields:+ row[name] = json.dumps(row.get(name) or {})+ return row+++def _canvas_series_rows(config: BrazeDataSeriesConfig, canvas_id: Optional[str], data: Any) -> list[dict[str, Any]]:+ if not isinstance(data, dict):+ return []+ rows: list[dict[str, Any]] = []+ for point in data.get("stats") or []:+ if not isinstance(point, dict):+ continue+ total_stats = point.get("total_stats")+ row: dict[str, Any] = {+ "canvas_id": canvas_id,+ "canvas_name": data.get("name"),+ "time": point.get("time"),+ **(total_stats if isinstance(total_stats, dict) else {}),+ "variant_stats": point.get("variant_stats"),+ "step_stats": point.get("step_stats"),+ }+ rows.append(_encode_json_fields(row, config.json_fields))+ return rows+++def _series_rows(config: BrazeDataSeriesConfig, parent_id: Optional[str], body: Any) -> list[dict[str, Any]]:+ data = body.get("data") if isinstance(body, dict) else None+ if config.shape == "canvas":+ return _canvas_series_rows(config, parent_id, data)+ if not isinstance(data, list):+ return []+ rows: list[dict[str, Any]] = []+ for point in data:+ if not isinstance(point, dict):+ continue+ row = dict(point)+ if config.parent_id_column is not None:+ row[config.parent_id_column] = parent_id+ rows.append(_encode_json_fields(row, config.json_fields))+ return rows+++def _iter_parent_ids(+ api_key: str, base_url: str, config: BrazeDataSeriesConfig, team_id: int, job_id: str+) -> Iterator[str]:+ assert config.parent is not None and config.parent_id_field is not None+ parent_config = BRAZE_ENDPOINTS[config.parent]+ paginator, _ = _paginator_for(parent_config)+ resource = _list_resource(api_key, base_url, parent_config, team_id, job_id, paginator)+ for page in resource:+ for item in _normalize_items(parent_config, page):+ value = item.get(config.parent_id_field)+ if isinstance(value, str) and value:+ yield value+++def _data_series_rows(+ api_key: str,+ base_url: str,+ config: BrazeDataSeriesConfig,+ team_id: int,+ job_id: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Iterator[list[dict[str, Any]]]:+ now = datetime.now(tz=UTC)+ span_days = _series_span_days(should_use_incremental_field, db_incremental_field_last_value, now.date())+ windows = _series_windows(config.max_length_days, span_days, now)++ session = make_tracked_session(+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ # No redirects: the base URL is customer-supplied, so keep traffic pinned+ # to the validated host (SSRF hardening).+ allow_redirects=False,+ redact_values=(api_key,),+ )+ url = f"{normalize_base_url(base_url)}{config.path}"++ parent_ids: Iterable[Optional[str]] = (+ _iter_parent_ids(api_key, base_url, config, team_id, job_id) if config.parent else [None]+ )+ for parent_id in parent_ids:+ for ending_at, length in windows:+ params: dict[str, Any] = {"length": length, "ending_at": ending_at.isoformat(), **config.params}+ if config.parent_id_param is not None:+ params[config.parent_id_param] = parent_id+ response = session.get(url, params=params)+ response.raise_for_status()+ rows = _series_rows(config, parent_id, response.json())+ if rows:+ yield rows+++def _braze_data_series_source(+ api_key: str,+ base_url: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ config = BRAZE_DATA_SERIES_ENDPOINTS[endpoint]++ def get_rows() -> Iterator[list[dict[str, Any]]]:+ # Re-check at run time (not just at source-create) in case the URL was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)+ if not host_ok:+ raise BrazeHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ # No resume checkpoint: a fan-out is only resumable from a stable parent ordering, and+ # Braze's list endpoints order by last edit time, which moves between pages.+ yield from _data_series_rows(+ api_key,+ base_url,+ config,+ team_id,+ job_id,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ return SourceResponse(+ name=endpoint,+ items=get_rows,+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Rows arrive grouped by parent and then by window, so `time` never runs monotonically+ # across the whole stream.+ sort_mode=None,+ )+++def braze_source(+ api_key: str,+ base_url: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[BrazeResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ if endpoint in BRAZE_DATA_SERIES_ENDPOINTS:+ return _braze_data_series_source(+ api_key,+ base_url,+ endpoint,+ team_id,+ job_id,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ config = BRAZE_ENDPOINTS[endpoint]++ params: dict[str, Any] = {}+ if config.modified_after_param and should_use_incremental_field and db_incremental_field_last_value:+ params[config.modified_after_param] = _format_modified_after(db_incremental_field_last_value)++ paginator, state_key = _paginator_for(config)+initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()@@ -215,11 +427,15 @@ def braze_source(if state and state.get(state_key) is not None:resumable_source_manager.save_state(BrazeResumeConfig(cursor=int(state[state_key])))- resource = rest_api_resource(- rest_config,+ resource = _list_resource(+ api_key,+ base_url,+ config,team_id,job_id,- db_incremental_field_last_value if should_use_incremental_field else None,+ paginator,+ params=params,+ db_incremental_field_last_value=db_incremental_field_last_value if should_use_incremental_field else None,resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/canonical_descriptions.pyindex 57da4b206af9..75b96dbb54c6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/canonical_descriptions.py@@ -71,4 +71,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_edited": "Time at which the Content Block was last edited.",},},+ "campaign_analytics": {+ "description": "A daily series of send, engagement and conversion stats for one campaign.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/campaigns/get_campaign_analytics/",+ "columns": {+ "campaign_id": "Identifier of the campaign the row describes.",+ "time": "Date the stats cover, as an ISO 8601 date.",+ "unique_recipients": "Number of unique users who received a message from the campaign.",+ "revenue": "Revenue attributed to the campaign, in US dollars.",+ "conversions": "Conversions of the campaign's primary conversion event.",+ "conversions_by_send_time": "Primary conversions attributed to the date the campaign was sent.",+ "conversions1": "Conversions of the campaign's second conversion event.",+ "conversions2": "Conversions of the campaign's third conversion event.",+ "conversions3": "Conversions of the campaign's fourth conversion event.",+ "messages": "Per-channel, per-variation message stats, JSON-encoded because the channels present vary per campaign.",+ },+ },+ "canvas_analytics": {+ "description": "A daily series of entry, conversion and revenue stats for one Canvas.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/canvas/get_canvas_analytics/",+ "columns": {+ "canvas_id": "Identifier of the Canvas the row describes.",+ "canvas_name": "Name of the Canvas.",+ "time": "Date the stats cover, as an ISO 8601 date.",+ "entries": "Number of users who entered the Canvas.",+ "conversions": "Conversions of the Canvas's primary conversion event.",+ "conversions_by_entry_time": "Primary conversions attributed to the date the user entered the Canvas.",+ "revenue": "Revenue attributed to the Canvas, in US dollars.",+ "variant_stats": "Per-variant stats keyed by variant API identifier, JSON-encoded.",+ "step_stats": "Per-step stats and message stats keyed by step API identifier, JSON-encoded.",+ },+ },+ "event_analytics": {+ "description": "A daily series of how often one custom event occurred.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/custom_events/get_custom_events_analytics/",+ "columns": {+ "event_name": "Name of the custom event the row describes.",+ "time": "Date the count covers, as an ISO 8601 date.",+ "count": "Number of occurrences of the custom event.",+ },+ },+ "kpi_dau": {+ "description": "A daily series of the number of daily active users across the workspace.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/kpi/get_kpi_dau_date/",+ "columns": {+ "time": "Date the count covers, as an ISO 8601 date.",+ "dau": "Number of daily active users.",+ },+ },+ "kpi_mau": {+ "description": "A daily series of unique active users over a rolling 30-day window.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/kpi/get_kpi_mau_30_days/",+ "columns": {+ "time": "Date the rolling window ends on, as an ISO 8601 date.",+ "mau": "Number of unique active users in the 30 days ending on this date.",+ },+ },+ "kpi_new_users": {+ "description": "A daily series of the number of new users across the workspace.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/kpi/get_kpi_daily_new_users_date/",+ "columns": {+ "time": "Date the count covers, as an ISO 8601 date.",+ "new_users": "Number of new users first seen on this date.",+ },+ },+ "kpi_uninstalls": {+ "description": "A daily series of the number of app uninstalls across the workspace.",+ "docs_url": "https://www.braze.com/docs/api/endpoints/export/kpi/get_kpi_uninstalls_date/",+ "columns": {+ "time": "Date the count covers, as an ISO 8601 date.",+ "uninstalls": "Number of uninstalls recorded on this date.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/settings.pyindex 20331c00a57b..8752021d59b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/settings.py@@ -1,6 +1,8 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Braze list endpoints paginate either with a 0-indexed ``page`` param@@ -102,8 +104,142 @@ BRAZE_ENDPOINTS: dict[str, BrazeEndpointConfig] = {),}-ENDPOINTS = tuple(BRAZE_ENDPOINTS.keys())+# Braze's analytics endpoints (`/*/data_series`) return a daily series instead of a page of+# rows. Each takes a window — `ending_at` plus a `length` in days capped per endpoint — and the+# campaign/canvas/event series also need an id from the matching list endpoint, so those fan out+# one request per parent row.+DataSeriesShape = Literal["list", "canvas"]++# How far back a first sync (or a full refresh) of a data series reaches. Braze caps `length` at+# 100 days, so a longer span would only mean more requests per parent for older history.+DATA_SERIES_HISTORY_DAYS = 100++# Braze restates recent days as conversions attribute back to the send date, so incremental runs+# re-read a trailing window rather than resuming at the last day already stored.+DATA_SERIES_LOOKBACK_SECONDS = 14 * 24 * 60 * 60+++def _date_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.Date,+ "field": name,+ "field_type": IncrementalFieldType.Date,+ }+++DATA_SERIES_INCREMENTAL_FIELDS: list[IncrementalField] = [_date_field("time")]+++@frozen+class BrazeDataSeriesConfig:+ name: str+ path: str+ primary_keys: list[str]+ # Braze's documented maximum for this endpoint's `length` param, in days.+ max_length_days: int+ # The list endpoint supplying the required id, the row field holding it, the query param it+ # goes in, and the column it lands in. All None for the workspace-level KPI series.+ parent: Optional[str] = None+ parent_id_field: Optional[str] = None+ parent_id_param: Optional[str] = None+ parent_id_column: Optional[str] = None+ # /canvas/data_series nests its series under `data.stats`; every other series returns `data`+ # as a flat list.+ shape: DataSeriesShape = "list"+ params: dict[str, str] = field(default_factory=dict)+ # Response fields whose keys vary per row — the per-channel `messages` map, the variant and+ # step maps keyed by API identifier. JSON-encoded so the column keeps one type across rows.+ json_fields: tuple[str, ...] = ()+ # `time` is the day the row describes, so it never moves once written.+ partition_key: Optional[str] = None+++BRAZE_DATA_SERIES_ENDPOINTS: dict[str, BrazeDataSeriesConfig] = {+ "campaign_analytics": BrazeDataSeriesConfig(+ name="campaign_analytics",+ path="/campaigns/data_series",+ primary_keys=["campaign_id", "time"],+ max_length_days=100,+ parent="campaigns",+ parent_id_field="id",+ parent_id_param="campaign_id",+ parent_id_column="campaign_id",+ json_fields=("messages",),+ partition_key="time",+ ),+ "canvas_analytics": BrazeDataSeriesConfig(+ name="canvas_analytics",+ path="/canvas/data_series",+ primary_keys=["canvas_id", "time"],+ max_length_days=14,+ parent="canvases",+ parent_id_field="id",+ parent_id_param="canvas_id",+ parent_id_column="canvas_id",+ shape="canvas",+ params={"include_variant_breakdown": "true", "include_step_breakdown": "true"},+ json_fields=("variant_stats", "step_stats"),+ partition_key="time",+ ),+ "event_analytics": BrazeDataSeriesConfig(+ name="event_analytics",+ path="/events/data_series",+ primary_keys=["event_name", "time"],+ max_length_days=100,+ parent="events",+ parent_id_field="event_name",+ parent_id_param="event",+ parent_id_column="event_name",+ partition_key="time",+ ),+ "kpi_dau": BrazeDataSeriesConfig(+ name="kpi_dau",+ path="/kpi/dau/data_series",+ primary_keys=["time"],+ max_length_days=100,+ ),+ "kpi_mau": BrazeDataSeriesConfig(+ name="kpi_mau",+ path="/kpi/mau/data_series",+ primary_keys=["time"],+ max_length_days=100,+ ),+ "kpi_new_users": BrazeDataSeriesConfig(+ name="kpi_new_users",+ path="/kpi/new_users/data_series",+ primary_keys=["time"],+ max_length_days=100,+ ),+ "kpi_uninstalls": BrazeDataSeriesConfig(+ name="kpi_uninstalls",+ path="/kpi/uninstalls/data_series",+ primary_keys=["time"],+ max_length_days=100,+ ),+}+++def _probe_target(config: BrazeDataSeriesConfig) -> str:+ # A data series rejects a request missing its required params, so probe with enough of one to+ # get a 200/401/403 back. The fan-out series need a parent id we don't have before syncing,+ # so they probe the list endpoint their fan-out walks — a permission the sync needs anyway.+ if config.parent is not None:+ return f"{BRAZE_ENDPOINTS[config.parent].path}?page=0"+ return f"{config.path}?length=1"+++# Request each endpoint's credential probe sends, path and query.+BRAZE_PROBE_TARGETS: dict[str, str] = {+ **{name: f"{config.path}?page=0" for name, config in BRAZE_ENDPOINTS.items()},+ **{name: _probe_target(config) for name, config in BRAZE_DATA_SERIES_ENDPOINTS.items()},+}++DEFAULT_PROBE_TARGET = BRAZE_PROBE_TARGETS["campaigns"]++ENDPOINTS = tuple(BRAZE_ENDPOINTS.keys()) + tuple(BRAZE_DATA_SERIES_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {- name: config.incremental_fields for name, config in BRAZE_ENDPOINTS.items()+ **{name: config.incremental_fields for name, config in BRAZE_ENDPOINTS.items()},+ **dict.fromkeys(BRAZE_DATA_SERIES_ENDPOINTS, DATA_SERIES_INCREMENTAL_FIELDS),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/source.pyindex ffa3bd3a35c9..d4f3f7347e45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/source.py@@ -16,7 +16,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.braze.brazvalidate_credentials as validate_braze_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import (- BRAZE_ENDPOINTS,+ BRAZE_DATA_SERIES_ENDPOINTS,+ BRAZE_PROBE_TARGETS,+ DATA_SERIES_LOOKBACK_SECONDS,+ DEFAULT_PROBE_TARGET,ENDPOINTS,INCREMENTAL_FIELDS,)@@ -62,9 +65,16 @@ class BrazeSource(ResumableSource[BrazeSourceConfig, BrazeResumeConfig]):You can create a REST API key in your Braze dashboard under **Settings → API Keys**. Grant the following endpoint permissions for the data you want to sync:- `campaigns.list`+- `campaigns.data_series`- `canvas.list`+- `canvas.data_series`- `segments.list`- `events.list`+- `events.data_series`+- `kpi.dau.data_series`+- `kpi.mau.data_series`+- `kpi.new_users.data_series`+- `kpi.uninstalls.data_series`- `templates.email.list`- `content_blocks.list`@@ -115,15 +125,21 @@ Your REST endpoint must match your Braze dashboard's region — see [Braze's APIforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ schemas = build_endpoint_schemas(+ ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=tuple(BRAZE_DATA_SERIES_ENDPOINTS)+ )+ for schema in schemas:+ if schema.name in BRAZE_DATA_SERIES_ENDPOINTS:+ schema.default_incremental_lookback_seconds = DATA_SERIES_LOOKBACK_SECONDS+ return schemasdef validate_credentials(self, config: BrazeSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None) -> tuple[bool, str | None]:- if schema_name is not None and schema_name not in BRAZE_ENDPOINTS:+ if schema_name is not None and schema_name not in BRAZE_PROBE_TARGETS:return False, f"Unknown Braze schema: {schema_name!r}"- path = BRAZE_ENDPOINTS[schema_name].path if schema_name is not None else "/campaigns/list"- valid, error = validate_braze_credentials(config.api_key, config.url, path, team_id)+ probe_target = BRAZE_PROBE_TARGETS[schema_name] if schema_name is not None else DEFAULT_PROBE_TARGET+ valid, error = validate_braze_credentials(config.api_key, config.url, probe_target, team_id)# A scoped key may legitimately lack the probe endpoint's permission at# source-create time; only enforce per-endpoint scope when validating adiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze.pyindex c0b5026989fe..c3908812f507 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze.py@@ -1,23 +1,32 @@import jsonfrom collections.abc import Iterable-from datetime import UTC, date, datetime+from datetime import UTC, date, datetime, timedeltafrom typing import Any, castimport pytestfrom unittest import mockfrom requests import Response+from requests.exceptions import HTTPErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.braze.braze import (BrazeHostNotAllowedError,BrazeResumeConfig,+ _canvas_series_rows,_format_modified_after,_normalize_items,+ _series_rows,+ _series_span_days,+ _series_windows,braze_source,normalize_base_url,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import BRAZE_ENDPOINTS, ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import (+ BRAZE_DATA_SERIES_ENDPOINTS,+ BRAZE_ENDPOINTS,+ DATA_SERIES_HISTORY_DAYS,+)BASE_URL = "https://rest.iad-01.braze.com"@@ -384,7 +393,7 @@ class TestGetRows:class TestBrazeSourceResponse:- @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ @pytest.mark.parametrize("endpoint", list(BRAZE_ENDPOINTS))def test_response_metadata_per_endpoint(self, endpoint):config = BRAZE_ENDPOINTS[endpoint]response = _source(endpoint)@@ -403,3 +412,280 @@ class TestBrazeSourceResponse:# Partition keys must be immutable creation timestamps, never updated/last-edit fields.if config.partition_key:assert config.partition_key == "created_at"+++def _series_response(data: Any) -> Response:+ return _response({"message": "success", "data": data})+++class TestSeriesSpanDays:+ def test_full_refresh_asks_for_the_default_history(self):+ assert _series_span_days(False, date(2026, 3, 1), date(2026, 3, 10)) == DATA_SERIES_HISTORY_DAYS++ def test_no_watermark_asks_for_the_default_history(self):+ assert _series_span_days(True, None, date(2026, 3, 10)) == DATA_SERIES_HISTORY_DAYS++ @pytest.mark.parametrize(+ "watermark, expected",+ [+ # The watermark day itself is re-read, so a same-day watermark still asks for a day.+ (date(2026, 3, 10), 1),+ (date(2026, 3, 5), 6),+ (datetime(2026, 3, 5, 13, 30, tzinfo=UTC), 6),+ ("2026-03-05", 6),+ # A watermark older than the history cap is clamped to it.+ (date(2020, 1, 1), DATA_SERIES_HISTORY_DAYS),+ # A watermark in the future can only mean a clock skew; never ask for zero days.+ (date(2026, 3, 20), 1),+ ],+ )+ def test_spans_back_to_the_watermark(self, watermark, expected):+ assert _series_span_days(True, watermark, date(2026, 3, 10)) == expected++ def test_unparseable_watermark_falls_back_to_the_default_history(self):+ assert _series_span_days(True, "not-a-date", date(2026, 3, 10)) == DATA_SERIES_HISTORY_DAYS+++class TestSeriesWindows:+ def test_span_within_the_cap_is_one_window(self):+ now = datetime(2026, 3, 10, 12, tzinfo=UTC)++ assert _series_windows(100, 30, now) == [(now, 30)]++ def test_longer_span_steps_ending_at_back_a_window_at_a_time(self):+ # Canvas caps `length` at 14 days, so 100 days of history needs 8 requests per Canvas.+ now = datetime(2026, 3, 10, 12, tzinfo=UTC)++ windows = _series_windows(14, DATA_SERIES_HISTORY_DAYS, now)++ assert sum(length for _, length in windows) == DATA_SERIES_HISTORY_DAYS+ assert all(length <= 14 for _, length in windows)+ # Oldest window first, and each window ends where the next one begins.+ endings = [ending for ending, _ in windows]+ assert endings == sorted(endings)+ assert endings[-1] == now+ for (ending, _), (next_ending, next_length) in zip(windows, windows[1:]):+ assert next_ending - timedelta(days=next_length) == ending+++class TestSeriesRows:+ def test_injects_the_parent_id_and_encodes_varying_shapes(self):+ config = BRAZE_DATA_SERIES_ENDPOINTS["campaign_analytics"]++ rows = _series_rows(+ config,+ "campaign-1",+ {"data": [{"time": "2026-03-09", "conversions": 3, "messages": {"email": [{"sent": 5}]}}]},+ )++ assert rows == [+ {+ "time": "2026-03-09",+ "conversions": 3,+ "messages": '{"email": [{"sent": 5}]}',+ "campaign_id": "campaign-1",+ }+ ]++ def test_missing_json_field_still_gets_a_column(self):+ # Braze omits `messages` for a campaign with no sends; the column must keep one type.+ config = BRAZE_DATA_SERIES_ENDPOINTS["campaign_analytics"]++ rows = _series_rows(config, "campaign-1", {"data": [{"time": "2026-03-09"}]})++ assert rows[0]["messages"] == "{}"++ def test_workspace_series_rows_pass_through(self):+ config = BRAZE_DATA_SERIES_ENDPOINTS["kpi_dau"]++ rows = _series_rows(config, None, {"data": [{"time": "2026-03-09", "dau": 42}]})++ assert rows == [{"time": "2026-03-09", "dau": 42}]++ @pytest.mark.parametrize("body", [{"message": "success"}, {"data": None}, {"data": "nonsense"}, "nonsense"])+ def test_missing_or_unexpected_data_yields_nothing(self, body):+ assert _series_rows(BRAZE_DATA_SERIES_ENDPOINTS["kpi_dau"], None, body) == []++ def test_canvas_rows_flatten_totals_and_encode_breakdowns(self):+ config = BRAZE_DATA_SERIES_ENDPOINTS["canvas_analytics"]++ rows = _canvas_series_rows(+ config,+ "canvas-1",+ {+ "name": "Welcome",+ "stats": [+ {+ "time": "2026-03-09",+ "total_stats": {"revenue": 1.5, "conversions": 2, "entries": 7},+ "variant_stats": {"variant-1": {"name": "A", "entries": 7}},+ "step_stats": {"step-1": {"name": "Email", "messages": {"email": [{"sent": 7}]}}},+ }+ ],+ },+ )++ assert rows == [+ {+ "canvas_id": "canvas-1",+ "canvas_name": "Welcome",+ "time": "2026-03-09",+ "revenue": 1.5,+ "conversions": 2,+ "entries": 7,+ "variant_stats": '{"variant-1": {"name": "A", "entries": 7}}',+ "step_stats": '{"step-1": {"name": "Email", "messages": {"email": [{"sent": 7}]}}}',+ }+ ]++ def test_canvas_rows_without_a_breakdown_keep_the_columns(self):+ config = BRAZE_DATA_SERIES_ENDPOINTS["canvas_analytics"]++ rows = _canvas_series_rows(config, "canvas-1", {"name": "Welcome", "stats": [{"time": "2026-03-09"}]})++ assert rows[0]["variant_stats"] == "{}"+ assert rows[0]["step_stats"] == "{}"++ @pytest.mark.parametrize("data", [None, [], {"name": "Welcome"}])+ def test_canvas_rows_tolerate_a_missing_series(self, data):+ assert _canvas_series_rows(BRAZE_DATA_SERIES_ENDPOINTS["canvas_analytics"], "canvas-1", data) == []+++class TestDataSeriesRequests:+ @mock.patch(SESSION_PATCH)+ def test_workspace_series_requests_one_window(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [_series_response([{"time": "2026-03-09", "dau": 42}])]++ rows = _rows(_source("kpi_dau"))++ assert rows == [{"time": "2026-03-09", "dau": 42}]+ url, kwargs = session.get.call_args.args[0], session.get.call_args.kwargs+ assert url == f"{BASE_URL}/kpi/dau/data_series"+ assert kwargs["params"]["length"] == DATA_SERIES_HISTORY_DAYS+ # `ending_at` is the moment of the request, never a future date Braze would reject.+ assert datetime.fromisoformat(kwargs["params"]["ending_at"]) <= datetime.now(tz=UTC)++ @mock.patch(SESSION_PATCH)+ def test_incremental_narrows_the_window_to_the_watermark(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [_series_response([])]++ _rows(+ _source(+ "kpi_dau",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime.now(tz=UTC) - timedelta(days=4),+ )+ )++ assert session.get.call_args.kwargs["params"]["length"] == 5++ @mock.patch(SESSION_PATCH)+ def test_full_refresh_ignores_a_stored_watermark(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [_series_response([])]++ _rows(_source("kpi_dau", db_incremental_field_last_value=datetime.now(tz=UTC) - timedelta(days=4)))++ assert session.get.call_args.kwargs["params"]["length"] == DATA_SERIES_HISTORY_DAYS++ @mock.patch(SESSION_PATCH)+ def test_campaign_series_fans_out_over_the_campaign_list(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response({"campaigns": [{"id": "c1"}, {"id": "c2"}]}), _response({"campaigns": []})])+ session.get.side_effect = [+ _series_response([{"time": "2026-03-09", "conversions": 1}]),+ _series_response([{"time": "2026-03-09", "conversions": 2}]),+ ]++ rows = _rows(_source("campaign_analytics"))++ assert [row["campaign_id"] for row in rows] == ["c1", "c2"]+ assert [call.kwargs["params"]["campaign_id"] for call in session.get.call_args_list] == ["c1", "c2"]++ @mock.patch(SESSION_PATCH)+ def test_event_series_fans_out_over_the_event_names(self, MockSession):+ # /events/list returns bare strings, so the fan-out reads the wrapped `event_name`.+ session = MockSession.return_value+ _wire(session, [_response({"events": ["purchase"]}), _response({"events": []})])+ session.get.side_effect = [_series_response([{"time": "2026-03-09", "count": 4}])]++ rows = _rows(_source("event_analytics"))++ assert rows == [{"time": "2026-03-09", "count": 4, "event_name": "purchase"}]+ assert session.get.call_args.kwargs["params"]["event"] == "purchase"++ @mock.patch(SESSION_PATCH)+ def test_canvas_series_requests_every_window_per_canvas(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response({"canvases": [{"id": "cv1"}]}), _response({"canvases": []})])+ windows = _series_windows(+ BRAZE_DATA_SERIES_ENDPOINTS["canvas_analytics"].max_length_days,+ DATA_SERIES_HISTORY_DAYS,+ datetime.now(tz=UTC),+ )+ session.get.side_effect = [_series_response({"name": "Welcome", "stats": []}) for _ in windows]++ _rows(_source("canvas_analytics"))++ params = [call.kwargs["params"] for call in session.get.call_args_list]+ assert [p["length"] for p in params] == [length for _, length in windows]+ assert all(p["canvas_id"] == "cv1" for p in params)+ # The breakdowns are what make the table usable per step and per variant.+ assert all(p["include_step_breakdown"] == "true" and p["include_variant_breakdown"] == "true" for p in params)++ @mock.patch(SESSION_PATCH)+ def test_uses_no_redirect_session_with_redacted_key(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [_series_response([])]++ _rows(_source("kpi_dau"))++ assert MockSession.call_args.kwargs["allow_redirects"] is False+ assert "key" in MockSession.call_args.kwargs["redact_values"]++ @mock.patch(SESSION_PATCH)+ def test_raises_on_an_error_status(self, MockSession):+ # raise_for_status keeps the 403 wording get_non_retryable_errors matches on.+ session = MockSession.return_value+ session.get.side_effect = [_response({"message": "forbidden"}, status_code=403)]++ with pytest.raises(HTTPError, match="403 Client Error"):+ _rows(_source("kpi_dau"))++ @mock.patch(HOST_SAFE_PATCH)+ @mock.patch(SESSION_PATCH)+ def test_raises_when_host_not_allowed(self, MockSession, mock_host_safe):+ mock_host_safe.return_value = (False, "host not allowed")++ response = braze_source(+ "key",+ "https://10.0.0.1",+ "kpi_dau",+ team_id=42,+ job_id="job",+ resumable_source_manager=_make_manager(),+ )+ with pytest.raises(BrazeHostNotAllowedError):+ list(cast("Iterable[Any]", response.items()))++ MockSession.return_value.get.assert_not_called()+++class TestBrazeDataSeriesSourceResponse:+ @pytest.mark.parametrize("config", list(BRAZE_DATA_SERIES_ENDPOINTS.values()))+ def test_primary_keys_are_unique_table_wide(self, config):+ # A fan-out child aggregates every parent's series, so `time` alone repeats across parents.+ assert "time" in config.primary_keys+ if config.parent_id_column:+ assert config.parent_id_column in config.primary_keys++ @mock.patch(SESSION_PATCH)+ def test_series_rows_are_never_declared_sorted(self, MockSession):+ # Rows arrive grouped by parent and then by window, so the watermark cannot checkpoint+ # mid-stream on `time`.+ session = MockSession.return_value+ session.get.side_effect = [_series_response([])]++ assert _source("kpi_dau").sort_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze_source.pyindex b86ec8a0d458..b62ed61e00b9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/braze/tests/test_braze_source.py@@ -1,7 +1,11 @@import pytestfrom unittest import mock-from products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.braze.settings import (+ BRAZE_DATA_SERIES_ENDPOINTS,+ DATA_SERIES_LOOKBACK_SECONDS,+ ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.braze.source import BrazeSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.braze import BrazeSourceConfig@@ -45,8 +49,19 @@ class TestBrazeSource:assert {schema.name for schema in schemas} == set(ENDPOINTS)incremental = {schema.name for schema in schemas if schema.supports_incremental}- # Only templates/content blocks expose Braze's server-side `modified_after` filter.- assert incremental == {"email_templates", "content_blocks"}+ # Templates/content blocks expose Braze's server-side `modified_after` filter; every data+ # series is bounded by its own `ending_at`/`length` window.+ assert incremental == {"email_templates", "content_blocks", *BRAZE_DATA_SERIES_ENDPOINTS}++ def test_data_series_schemas_re_read_a_trailing_window_and_never_append(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ for name in BRAZE_DATA_SERIES_ENDPOINTS:+ # Braze restates recent days, so appending them would duplicate rather than correct.+ assert schemas[name].supports_append is False+ assert schemas[name].default_incremental_lookback_seconds == DATA_SERIES_LOOKBACK_SECONDS+ assert schemas["email_templates"].supports_append is True+ assert schemas["email_templates"].default_incremental_lookback_seconds is None@pytest.mark.parametrize("mock_return, expected_valid, expected_message",@@ -65,19 +80,32 @@ class TestBrazeSource:assert is_valid is expected_validassert error_message == expected_message- mock_validate.assert_called_once_with(self.config.api_key, self.config.url, "/campaigns/list", self.team_id)+ mock_validate.assert_called_once_with(+ self.config.api_key, self.config.url, "/campaigns/list?page=0", self.team_id+ )+ @pytest.mark.parametrize(+ "schema_name, expected_probe",+ [+ ("email_templates", "/templates/email/list?page=0"),+ # A workspace series can be probed directly; `length` is all Braze requires.+ ("kpi_dau", "/kpi/dau/data_series?length=1"),+ # A fan-out series needs a parent id we do not have yet, so it probes the list+ # endpoint its fan-out walks — a permission the sync needs either way.+ ("campaign_analytics", "/campaigns/list?page=0"),+ ("canvas_analytics", "/canvas/list?page=0"),+ ("event_analytics", "/events/list?page=0"),+ ],+ )@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.braze.source.validate_braze_credentials")- def test_validate_credentials_probes_schema_specific_path(self, mock_validate):+ def test_validate_credentials_probes_schema_specific_path(self, mock_validate, schema_name, expected_probe):mock_validate.return_value = (True, None)- self.source.validate_credentials(self.config, self.team_id, schema_name="email_templates")+ self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)- mock_validate.assert_called_once_with(- self.config.api_key, self.config.url, "/templates/email/list", self.team_id- )+ mock_validate.assert_called_once_with(self.config.api_key, self.config.url, expected_probe, self.team_id)@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.braze.source.validate_braze_credentials"