Skip to content

: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.

feat(data-warehouse): implement brevo import source (#61153)

Tom Owers3cbcc18f6e0b
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 1422ec2d36eb..8e7e32404dc1 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -49,6 +49,7 @@ the row lists both.
| bamboohr | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
+| brevo | HTTP | requests | ✅ |
| buildbetter | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -150,7 +151,6 @@ doesn't conflict with concurrent PRs.
- box
- braintree
- braze
-- brevo
- campaign_monitor
- circleci
- clickup
diff --git a/posthog/temporal/data_imports/sources/brevo/api_inventory.md b/posthog/temporal/data_imports/sources/brevo/api_inventory.md
new file mode 100644
index 000000000000..8a553b88f25f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/brevo/api_inventory.md
@@ -0,0 +1,44 @@
+# Brevo (v3) endpoint inventory
+
+Base URL: `https://api.brevo.com/v3`
+Auth: `api-key` request header (account-wide API key).
+Pagination: `limit` + `offset` (offset is a record index, not a page number — confirmed via the
+official `getbrevo/brevo-python` SDK docs).
+Sorting: every list endpoint only sorts by **record creation date** via `sort=asc|desc` (default `desc`).
+We always request `sort=asc` for stable pagination boundaries and monotonic `createdAt` ordering.
+
+| Schema | Path | Array key | Page size | Incremental | Partition key |
+| ------------------ | -------------------- | ----------- | --------- | -------------------------------- | ------------- |
+| `contacts` | `/contacts` | `contacts` | 1000 | `createdSince` / `modifiedSince` | `createdAt` |
+| `contact_lists` | `/contacts/lists` | `lists` | 50 | — (full refresh) | — |
+| `contact_folders` | `/contacts/folders` | `folders` | 50 | — (full refresh) | — |
+| `contact_segments` | `/contacts/segments` | `segments` | 50 | — (full refresh) | — |
+| `email_campaigns` | `/emailCampaigns` | `campaigns` | 100 | — (full refresh) | `createdAt` |
+| `sms_campaigns` | `/smsCampaigns` | `campaigns` | 100 | — (full refresh) | `createdAt` |
+| `email_templates` | `/smtp/templates` | `templates` | 100 | — (full refresh) | — |
+| `senders` | `/senders` | `senders` | n/a | — (full refresh, single request) | — |
+
+## Incremental notes
+
+Only `/contacts` exposes genuine server-side timestamp filters (`createdSince`, `modifiedSince`,
+both `YYYY-MM-DDTHH:mm:ss.SSSZ`). All other list endpoints accept `sort` but no `*Since` filter, so
+they ship as full refresh. `email_campaigns` has `startDate`/`endDate`, but they only filter _sent_
+campaigns by send date — not a general modification cursor — so it stays full refresh.
+
+`/contacts` sorts by creation date only. With `sort=asc` a `createdAt` cursor is strictly monotonic.
+A `modifiedAt` cursor is not strictly ordered within a page, but the source is resumable on `offset`,
+so a crashed sync resumes mid-stream rather than re-deriving its position from the watermark — the
+per-batch watermark commit therefore can't skip rows in practice.
+
+## Rate limits
+
+Brevo enforces tight per-endpoint limits (≈10 req/s on `/contacts`, ≈100 req/hour on most others).
+We retry `429`/`5xx` with exponential backoff + jitter (`tenacity`, 5 attempts). Large page sizes
+keep request counts low (a 100k-contact account is ~100 requests at `limit=1000`).
+
+## Not yet verified against the live API
+
+Endpoint behavior was sourced from the current public docs and the official `getbrevo/brevo-python`
+SDK; it was **not** smoke-tested with curl because no API key was available in the build environment.
+The response array keys and field names are taken from the SDK model definitions and should be
+re-confirmed against a real account before promoting past `alpha`.
diff --git a/posthog/temporal/data_imports/sources/brevo/brevo.py b/posthog/temporal/data_imports/sources/brevo/brevo.py
new file mode 100644
index 000000000000..31434e5c9f17
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/brevo/brevo.py
@@ -0,0 +1,184 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.brevo.settings import BREVO_ENDPOINTS, BrevoEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+BREVO_BASE_URL = "https://api.brevo.com/v3"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class BrevoRetryableError(Exception):
+ pass
+
+
+class BrevoResumeConfig:
+ # Offset (record index) of the next page to fetch within the current sync.
+ offset: int
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "api-key": api_key,
+ "accept": "application/json",
+ }
+
+
+def _format_datetime(value: Any) -> str:
+ """Format a value as Brevo's expected UTC date-time (YYYY-MM-DDTHH:mm:ss.SSSZ).
+
+ Brevo rejects the +00:00 offset produced by isoformat(), so we emit the Z suffix.
+ """
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return _format_datetime(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ return str(value)
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Cheap probe to confirm the API key is genuine."""
+ try:
+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+ response = session.get(f"{BREVO_BASE_URL}/account", timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _build_base_params(
+ config: BrevoEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: Optional[str],
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ # Brevo only sorts by record creation date. Sorting ascending keeps pagination boundaries
+ # stable as new rows are inserted mid-sync and makes createdAt-based incremental monotonic.
+ if config.paginate:
+ params["sort"] = "asc"
+
+ if should_use_incremental_field and incremental_field and db_incremental_field_last_value:
+ param_name = config.incremental_param_map.get(incremental_field)
+ if param_name:
+ params[param_name] = _format_datetime(db_incremental_field_last_value)
+
+ return params
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BrevoResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: Optional[str] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BREVO_ENDPOINTS[endpoint]
+ base_params = _build_base_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume_config.offset if resume_config else 0
+ if resume_config is not None:
+ logger.debug(f"Brevo: resuming {endpoint} from offset {offset}")
+
+ # One session reused across all pages (TCP/connection reuse). `tenacity` below is the sole
+ # retry mechanism, so disable the transport's built-in urllib3 retries to avoid nested backoff.
+ # `redact_values` masks the api-key header value in logs and sample capture.
+ session = make_tracked_session(headers=_get_headers(api_key), retry=Retry(total=0), redact_values=(api_key,))
+
+ @retry(
+ retry=retry_if_exception_type((BrevoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, Any]) -> dict[str, Any]:
+ url = f"{BREVO_BASE_URL}{config.path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BrevoRetryableError(f"Brevo API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Brevo API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ try:
+ while True:
+ params = dict(base_params)
+ if config.paginate:
+ params["limit"] = config.page_size
+ params["offset"] = offset
+
+ data = fetch_page(params)
+ # Fail loudly if the expected envelope key is missing (e.g. an API-shape change),
+ # rather than silently reporting a successful sync of zero rows.
+ items = data[config.data_key]
+
+ if items:
+ yield items
+
+ if not config.paginate or len(items) < config.page_size:
+ break
+
+ offset += config.page_size
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on primary key)
+ # rather than skipping it.
+ resumable_source_manager.save_state(BrevoResumeConfig(offset=offset))
+ finally:
+ session.close()
+
+
+def brevo_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BrevoResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: Optional[str] = None,
+) -> SourceResponse:
+ config = BREVO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=["id"],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/brevo/settings.py b/posthog/temporal/data_imports/sources/brevo/settings.py
new file mode 100644
index 000000000000..7d2d5c59f3a7
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/brevo/settings.py
@@ -0,0 +1,102 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class BrevoEndpointConfig:
+ name: str
+ path: str
+ # Key wrapping the array in the JSON response, e.g. {"contacts": [...], "count": N}.
+ data_key: str
+ incremental_fields: list[IncrementalField]
+ # Stable creation field used for datetime partitioning. Never use a "modified" field here.
+ partition_key: Optional[str] = None
+ page_size: int = 100
+ # A few endpoints (e.g. /senders) return the full list in one shot with no limit/offset.
+ paginate: bool = True
+ # Maps a user-selected incremental field to the server-side query param that filters on it.
+ incremental_param_map: dict[str, str] = field(default_factory=dict)
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+# Brevo (v3) endpoint catalog. Only `contacts` exposes genuine server-side timestamp filters
+# (`createdSince` / `modifiedSince`); every other list endpoint sorts by creation date but offers
+# no incremental filter, so those ship as full refresh.
+BREVO_ENDPOINTS: dict[str, BrevoEndpointConfig] = {
+ "contacts": BrevoEndpointConfig(
+ name="contacts",
+ path="/contacts",
+ data_key="contacts",
+ page_size=1000, # max allowed by the API
+ partition_key="createdAt",
+ incremental_fields=[_datetime_field("createdAt"), _datetime_field("modifiedAt")],
+ incremental_param_map={"createdAt": "createdSince", "modifiedAt": "modifiedSince"},
+ ),
+ "contact_lists": BrevoEndpointConfig(
+ name="contact_lists",
+ path="/contacts/lists",
+ data_key="lists",
+ page_size=50, # max for the contacts list endpoints
+ incremental_fields=[],
+ ),
+ "contact_folders": BrevoEndpointConfig(
+ name="contact_folders",
+ path="/contacts/folders",
+ data_key="folders",
+ page_size=50,
+ incremental_fields=[],
+ ),
+ "contact_segments": BrevoEndpointConfig(
+ name="contact_segments",
+ path="/contacts/segments",
+ data_key="segments",
+ page_size=50,
+ incremental_fields=[],
+ ),
+ "email_campaigns": BrevoEndpointConfig(
+ name="email_campaigns",
+ path="/emailCampaigns",
+ data_key="campaigns",
+ page_size=100,
+ partition_key="createdAt",
+ incremental_fields=[],
+ ),
+ "sms_campaigns": BrevoEndpointConfig(
+ name="sms_campaigns",
+ path="/smsCampaigns",
+ data_key="campaigns",
+ page_size=100,
+ partition_key="createdAt",
+ incremental_fields=[],
+ ),
+ "email_templates": BrevoEndpointConfig(
+ name="email_templates",
+ path="/smtp/templates",
+ data_key="templates",
+ page_size=100,
+ incremental_fields=[],
+ ),
+ "senders": BrevoEndpointConfig(
+ name="senders",
+ path="/senders",
+ data_key="senders",
+ paginate=False,
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(BREVO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BREVO_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/posthog/temporal/data_imports/sources/brevo/source.py b/posthog/temporal/data_imports/sources/brevo/source.py
index 205ecf7d1dae..7435502a223a 100644
--- a/posthog/temporal/data_imports/sources/brevo/source.py
+++ b/posthog/temporal/data_imports/sources/brevo/source.py
@@ -1,29 +1,116 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.brevo.brevo import (
+ BrevoResumeConfig,
+ brevo_source,
+ validate_credentials as validate_brevo_credentials,
+)
+from posthog.temporal.data_imports.sources.brevo.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import BrevoSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BrevoSource(SimpleSource[BrevoSourceConfig]):
+class BrevoSource(ResumableSource[BrevoSourceConfig, BrevoResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BREVO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Brevo authentication failed. Your API key is invalid or expired - please generate a new key and reconnect.",
+ "403 Client Error: Forbidden for url": "Your Brevo API key does not have the required permissions. Please check the key and reconnect.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BREVO,
label="Brevo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Brevo API key to automatically pull your Brevo (formerly Sendinblue) data into the PostHog Data warehouse.
+
+You can create an API key in your [Brevo account settings](https://app.brevo.com/settings/keys/api).""",
iconPath="/static/services/brevo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/brevo",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="xkeysib-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: BrevoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,
+ supports_append=fields is not None,
+ incremental_fields=fields or [],
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: BrevoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_brevo_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Brevo API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrevoResumeConfig]:
+ return ResumableSourceManager[BrevoResumeConfig](inputs, BrevoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BrevoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BrevoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return brevo_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/brevo/tests/test_brevo.py b/posthog/temporal/data_imports/sources/brevo/tests/test_brevo.py
new file mode 100644
index 000000000000..3efd0c272158
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/brevo/tests/test_brevo.py
@@ -0,0 +1,295 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+from requests.exceptions import HTTPError
+
+from posthog.temporal.data_imports.sources.brevo.brevo import (
+ BREVO_BASE_URL,
+ BrevoResumeConfig,
+ _build_base_params,
+ _format_datetime,
+ brevo_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.brevo.settings import BREVO_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+def _make_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.url = f"{BREVO_BASE_URL}/contacts"
+ resp.reason = "OK" if status_code == 200 else "Client Error"
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlsplit(url).query)
+
+
+def _drive_get_rows(
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ **kwargs: Any,
+) -> tuple[list[str], list[list[dict[str, Any]]]]:
+ sent_urls: list[str] = []
+ response_iter = iter(responses)
+
+ def fake_get(url: str, headers: Any = None, timeout: Any = None) -> Response:
+ sent_urls.append(url)
+ return next(response_iter)
+
+ with patch("posthog.temporal.data_imports.sources.brevo.brevo.make_tracked_session") as MockSession:
+ MockSession.return_value.get.side_effect = fake_get
+ rows = list(
+ get_rows(
+ api_key="test-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+ return sent_urls, rows
+
+
+class TestFormatDatetime:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("already-a-string", "already-a-string"),
+ ],
+ )
+ def test_format_datetime(self, value: object, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+ def test_no_plus_offset(self) -> None:
+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestBuildBaseParams:
+ def test_paginated_endpoint_sorts_ascending(self) -> None:
+ params = _build_base_params(BREVO_ENDPOINTS["contacts"], False, None, None)
+ assert params == {"sort": "asc"}
+
+ def test_non_paginated_endpoint_has_no_sort(self) -> None:
+ params = _build_base_params(BREVO_ENDPOINTS["senders"], False, None, None)
+ assert params == {}
+
+ @pytest.mark.parametrize(
+ ("incremental_field", "expected_param"),
+ [("createdAt", "createdSince"), ("modifiedAt", "modifiedSince")],
+ )
+ def test_incremental_field_maps_to_server_param(self, incremental_field: str, expected_param: str) -> None:
+ params = _build_base_params(
+ BREVO_ENDPOINTS["contacts"],
+ True,
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field,
+ )
+ assert params[expected_param] == "2026-03-04T02:58:14.000Z"
+
+ def test_no_filter_on_first_sync(self) -> None:
+ params = _build_base_params(BREVO_ENDPOINTS["contacts"], True, None, "modifiedAt")
+ assert "modifiedSince" not in params
+ assert "createdSince" not in params
+
+ def test_unknown_incremental_field_is_ignored(self) -> None:
+ params = _build_base_params(BREVO_ENDPOINTS["contacts"], True, datetime(2026, 3, 4, tzinfo=UTC), "nonexistent")
+ assert params == {"sort": "asc"}
+
+
+class TestGetRowsPagination:
+ def test_offset_advances_and_terminates_on_short_page(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(BREVO_ENDPOINTS["contacts"], "page_size", 2)
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_response({"contacts": [{"id": 1}, {"id": 2}], "count": 3}),
+ _make_response({"contacts": [{"id": 3}], "count": 3}),
+ ]
+ sent_urls, rows = _drive_get_rows("contacts", manager, responses)
+
+ offsets = [_query(u).get("offset", [None])[0] for u in sent_urls]
+ assert offsets == ["0", "2"]
+ assert rows == [[{"id": 1}, {"id": 2}], [{"id": 3}]]
+
+ def test_saves_state_after_each_non_terminal_page(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(BREVO_ENDPOINTS["contacts"], "page_size", 2)
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_response({"contacts": [{"id": 1}, {"id": 2}]}),
+ _make_response({"contacts": [{"id": 3}]}),
+ ]
+ _drive_get_rows("contacts", manager, responses)
+
+ saved = [saved_call.args[0] for saved_call in manager.save_state.call_args_list]
+ assert saved == [BrevoResumeConfig(offset=2)]
+
+ def test_single_terminal_page_does_not_save_state(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(BREVO_ENDPOINTS["contacts"], "page_size", 1000)
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_response({"contacts": [{"id": 1}]})]
+ _drive_get_rows("contacts", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_starting_offset(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(BREVO_ENDPOINTS["contacts"], "page_size", 2)
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BrevoResumeConfig(offset=4)
+
+ responses = [_make_response({"contacts": [{"id": 5}]})]
+ sent_urls, _ = _drive_get_rows("contacts", manager, responses)
+
+ assert _query(sent_urls[0])["offset"] == ["4"]
+ manager.load_state.assert_called_once()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_response({"contacts": [{"id": 1}]})]
+ _drive_get_rows("contacts", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_empty_page_yields_nothing(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_response({"contacts": [], "count": 0})]
+ _, rows = _drive_get_rows("contacts", manager, responses)
+
+ assert rows == []
+
+
+class TestGetRowsNonPaginated:
+ def test_senders_fetched_once_without_pagination_params(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_response({"senders": [{"id": 1}, {"id": 2}]})]
+ sent_urls, rows = _drive_get_rows("senders", manager, responses)
+
+ assert len(sent_urls) == 1
+ assert urlsplit(sent_urls[0]).query == ""
+ assert rows == [[{"id": 1}, {"id": 2}]]
+ manager.save_state.assert_not_called()
+
+
+class TestGetRowsErrors:
+ def test_non_retryable_status_raises(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_response({"message": "Key not found", "code": "unauthorized"}, status_code=401)]
+ with pytest.raises(HTTPError):
+ _drive_get_rows("contacts", manager, responses)
+
+ def test_missing_envelope_key_raises(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ # 200 OK with an unexpected body shape must fail loudly, not sync zero rows.
+ responses = [_make_response({"unexpected": []})]
+ with pytest.raises(KeyError):
+ _drive_get_rows("contacts", manager, responses)
+
+
+class TestGetRowsSession:
+ def test_session_disables_transport_retry_and_redacts_key(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with patch("posthog.temporal.data_imports.sources.brevo.brevo.make_tracked_session") as MockSession:
+ MockSession.return_value.get.return_value = _make_response({"contacts": [{"id": 1}]})
+ list(
+ get_rows(
+ api_key="test-key",
+ endpoint="contacts",
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ kwargs = MockSession.call_args.kwargs
+ assert kwargs["retry"].total == 0
+ assert kwargs["redact_values"] == ("test-key",)
+ assert kwargs["headers"]["api-key"] == "test-key"
+ # Session is created once and reused across the sync.
+ MockSession.assert_called_once()
+ MockSession.return_value.close.assert_called_once()
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_validate_credentials_status_mapping(self, status_code: int, expected: bool) -> None:
+ with patch("posthog.temporal.data_imports.sources.brevo.brevo.make_tracked_session") as MockSession:
+ MockSession.return_value.get.return_value = _make_response({}, status_code=status_code)
+ assert validate_credentials("test-key") is expected
+
+ def test_validate_credentials_network_error_returns_false(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.brevo.brevo.make_tracked_session") as MockSession:
+ MockSession.return_value.get.side_effect = Exception("network down")
+ assert validate_credentials("test-key") is False
+
+
+class TestBrevoSourceResponse:
+ @pytest.mark.parametrize(
+ ("endpoint", "expects_partition"),
+ [
+ ("contacts", True),
+ ("email_campaigns", True),
+ ("sms_campaigns", True),
+ ("contact_lists", False),
+ ("contact_folders", False),
+ ("contact_segments", False),
+ ("email_templates", False),
+ ("senders", False),
+ ],
+ )
+ def test_source_response_shape(self, endpoint: str, expects_partition: bool) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ response = brevo_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+
+ if expects_partition:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+ assert response.partition_format == "week"
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/posthog/temporal/data_imports/sources/brevo/tests/test_brevo_source.py b/posthog/temporal/data_imports/sources/brevo/tests/test_brevo_source.py
new file mode 100644
index 000000000000..29711b556ee1
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/brevo/tests/test_brevo_source.py
@@ -0,0 +1,139 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.brevo.brevo import BrevoResumeConfig
+from posthog.temporal.data_imports.sources.brevo.source import BrevoSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import BrevoSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _config() -> BrevoSourceConfig:
+ return BrevoSourceConfig(api_key="test-key")
+
+
+def _source_inputs(schema_name: str = "contacts", **overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 1,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestBrevoSource:
+ def test_source_type(self) -> None:
+ assert BrevoSource().source_type == ExternalDataSourceType.BREVO
+
+ def test_source_config_basics(self) -> None:
+ config = BrevoSource().get_source_config
+ assert config.label == "Brevo"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == "alpha"
+ assert config.iconPath == "/static/services/brevo.png"
+
+ def test_source_config_has_api_key_password_field(self) -> None:
+ fields = BrevoSource().get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = BrevoSource().get_schemas(_config(), team_id=1)
+ names = {s.name for s in schemas}
+ assert names == {
+ "contacts",
+ "contact_lists",
+ "contact_folders",
+ "contact_segments",
+ "email_campaigns",
+ "sms_campaigns",
+ "email_templates",
+ "senders",
+ }
+
+ def test_only_contacts_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in BrevoSource().get_schemas(_config(), team_id=1)}
+ assert schemas["contacts"].supports_incremental is True
+ assert {f["field"] for f in schemas["contacts"].incremental_fields} == {"createdAt", "modifiedAt"}
+ for name in ["contact_lists", "email_campaigns", "sms_campaigns", "senders"]:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = BrevoSource().get_schemas(_config(), team_id=1, names=["contacts", "senders"])
+ assert {s.name for s in schemas} == {"contacts", "senders"}
+
+ @pytest.mark.parametrize(
+ ("valid", "expected_ok", "expected_msg"),
+ [(True, True, None), (False, False, "Invalid Brevo API key")],
+ )
+ def test_validate_credentials(self, valid: bool, expected_ok: bool, expected_msg: str | None) -> None:
+ with patch("posthog.temporal.data_imports.sources.brevo.source.validate_brevo_credentials", return_value=valid):
+ ok, msg = BrevoSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected_ok
+ assert msg == expected_msg
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = BrevoSource().get_resumable_source_manager(_source_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BrevoResumeConfig
+
+ def test_get_non_retryable_errors_covers_auth(self) -> None:
+ errors = BrevoSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = _source_inputs(
+ schema_name="contacts",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",
+ incremental_field="modifiedAt",
+ )
+ with patch("posthog.temporal.data_imports.sources.brevo.source.brevo_source") as mock_brevo_source:
+ mock_brevo_source.return_value = MagicMock(spec=SourceResponse)
+ BrevoSource().source_for_pipeline(_config(), manager, inputs)
+
+ _, kwargs = mock_brevo_source.call_args
+ assert kwargs["api_key"] == "test-key"
+ assert kwargs["endpoint"] == "contacts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00.000Z"
+ assert kwargs["incremental_field"] == "modifiedAt"
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = _source_inputs(
+ schema_name="contacts",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00.000Z",
+ )
+ with patch("posthog.temporal.data_imports.sources.brevo.source.brevo_source") as mock_brevo_source:
+ mock_brevo_source.return_value = MagicMock(spec=SourceResponse)
+ BrevoSource().source_for_pipeline(_config(), manager, inputs)
+
+ _, kwargs = mock_brevo_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index b8216161d7b8..3458c8714ee3 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -194,7 +194,7 @@ class BrazeSourceConfig(config.Config):
@config.config
class BrevoSourceConfig(config.Config):
- pass
+ api_key: str
@config.config