: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(data-warehouse): implement lob import source (#65632)
Tom Owersd80f5a938a9f
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex c7d76feb5eda..01ff291a99a6 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -128,6 +128,7 @@ the row lists both.| linear | HTTP | requests | ✅ || lever | HTTP | requests | ✅ || linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |+| lob | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ || mailerlite | HTTP | requests | ✅ || mailersend | HTTP | requests | ✅ |@@ -473,7 +474,6 @@ doesn't conflict with concurrent PRs.- linkedin_pages- linkrunner- linnworks-- lob- lokalise- looker- lumadiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex f9276026cfce..6214cf3460c2 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1751,7 +1751,7 @@ class LinnworksSourceConfig(config.Config):@config.configclass LobSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/lob/canonical_descriptions.py b/posthog/temporal/data_imports/sources/lob/canonical_descriptions.pynew file mode 100644index 000000000000..6a0bce65451e--- /dev/null+++ b/posthog/temporal/data_imports/sources/lob/canonical_descriptions.py@@ -0,0 +1,140 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++_COMMON_MAILPIECE_COLUMNS = {+ "id": "Unique identifier for the mailpiece, prefixed by its type (e.g. `ltr_`, `psc_`).",+ "description": "An internal description that identifies this resource. Up to 255 characters.",+ "metadata": "A set of user-defined key/value pairs attached to the resource.",+ "to": "The recipient address object the mailpiece was sent to.",+ "from": "The sender (return) address object.",+ "url": "A signed link to the rendered PDF of the mailpiece.",+ "carrier": "The carrier used to deliver the mailpiece (e.g. USPS).",+ "tracking_events": "Tracking events recorded as the mailpiece moves through the mail stream.",+ "expected_delivery_date": "Lob's estimated delivery date for the mailpiece.",+ "send_date": "The date Lob will begin processing the mailpiece for printing and mailing.",+ "mail_type": "The USPS mail class used (e.g. `usps_first_class`, `usps_standard`).",+ "use_type": "The declared use type of the mailpiece (`marketing` or `operational`).",+ "date_created": "ISO-8601 timestamp of when the resource was created.",+ "date_modified": "ISO-8601 timestamp of when the resource was last modified.",+ "object": "The resource type string (e.g. `letter`).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "letters": {+ "description": "Letters created through Lob — printed and mailed physical letters.",+ "docs_url": "https://docs.lob.com/#tag/Letters",+ "columns": {+ **_COMMON_MAILPIECE_COLUMNS,+ "color": "Whether the letter is printed in color (`true`) or black & white (`false`).",+ "double_sided": "Whether the letter is printed on both sides of each page.",+ "address_placement": "Where the recipient address is placed (e.g. `top_first_page`).",+ "return_envelope": "Whether a return envelope was included with the letter.",+ "perforated_page": "The page number that is perforated, if any.",+ "extra_service": "Any extra USPS service applied (e.g. `certified`, `registered`).",+ "template_id": "The template used to render the letter, if any.",+ "template_version_id": "The specific template version used, if any.",+ "tracking_number": "USPS tracking number, available for trackable services.",+ },+ },+ "postcards": {+ "description": "Postcards created through Lob — printed and mailed postcards.",+ "docs_url": "https://docs.lob.com/#tag/Postcards",+ "columns": {+ **_COMMON_MAILPIECE_COLUMNS,+ "size": "The postcard size (e.g. `4x6`, `6x9`, `6x11`).",+ "front_template_id": "Template used to render the front of the postcard, if any.",+ "back_template_id": "Template used to render the back of the postcard, if any.",+ },+ },+ "checks": {+ "description": "Checks created through Lob — printed and mailed checks.",+ "docs_url": "https://docs.lob.com/#tag/Checks",+ "columns": {+ **_COMMON_MAILPIECE_COLUMNS,+ "check_number": "The check number printed on the check.",+ "amount": "The dollar amount of the check.",+ "memo": "The memo printed in the lower-left of the check.",+ "bank_account": "The bank account the check is drawn from.",+ },+ },+ "self_mailers": {+ "description": "Self mailers created through Lob — folded mailers that need no envelope.",+ "docs_url": "https://docs.lob.com/#tag/Self-Mailers",+ "columns": {+ **_COMMON_MAILPIECE_COLUMNS,+ "size": "The self mailer size (e.g. `6x18_bifold`, `12x9_bifold`).",+ "inside_template_id": "Template used to render the inside of the self mailer, if any.",+ "outside_template_id": "Template used to render the outside of the self mailer, if any.",+ },+ },+ "addresses": {+ "description": "Saved addresses in your Lob account, reusable as senders or recipients.",+ "docs_url": "https://docs.lob.com/#tag/Addresses",+ "columns": {+ "id": "Unique identifier for the address, prefixed `adr_`.",+ "description": "An internal description that identifies this address.",+ "name": "Recipient or company name on the address.",+ "company": "Company name on the address.",+ "phone": "Phone number associated with the address.",+ "email": "Email associated with the address.",+ "address_line1": "Primary number, street name and unit/box of the address.",+ "address_line2": "Secondary information such as apartment or suite number.",+ "address_city": "City of the address.",+ "address_state": "State or province of the address.",+ "address_zip": "ZIP or postal code of the address.",+ "address_country": "Country of the address.",+ "metadata": "A set of user-defined key/value pairs attached to the address.",+ "date_created": "ISO-8601 timestamp of when the address was created.",+ "date_modified": "ISO-8601 timestamp of when the address was last modified.",+ "object": "The resource type string (`address`).",+ },+ },+ "bank_accounts": {+ "description": "Bank accounts saved in your Lob account, used as the source of funds for checks.",+ "docs_url": "https://docs.lob.com/#tag/Bank-Accounts",+ "columns": {+ "id": "Unique identifier for the bank account, prefixed `bank_`.",+ "description": "An internal description that identifies this bank account.",+ "routing_number": "The ABA routing number of the bank account.",+ "account_number": "The account number of the bank account.",+ "account_type": "The type of account (`company` or `individual`).",+ "signatory": "The signatory associated with the bank account.",+ "metadata": "A set of user-defined key/value pairs attached to the bank account.",+ "verified": "Whether the bank account has been verified for use with checks.",+ "date_created": "ISO-8601 timestamp of when the bank account was created.",+ "date_modified": "ISO-8601 timestamp of when the bank account was last modified.",+ "object": "The resource type string (`bank_account`).",+ },+ },+ "templates": {+ "description": "Reusable HTML templates used to render mailpieces.",+ "docs_url": "https://docs.lob.com/#tag/Templates",+ "columns": {+ "id": "Unique identifier for the template, prefixed `tmpl_`.",+ "description": "An internal description that identifies this template.",+ "name": "The template's name.",+ "published_version": "The currently published version of the template.",+ "versions": "The list of versions belonging to this template.",+ "metadata": "A set of user-defined key/value pairs attached to the template.",+ "date_created": "ISO-8601 timestamp of when the template was created.",+ "date_modified": "ISO-8601 timestamp of when the template was last modified.",+ "object": "The resource type string (`template`).",+ },+ },+ "campaigns": {+ "description": "Lob campaigns — groups of mailpieces sent together as part of a single send.",+ "docs_url": "https://docs.lob.com/#tag/Campaigns",+ "columns": {+ "id": "Unique identifier for the campaign, prefixed `cmp_`.",+ "name": "The campaign's name.",+ "description": "An internal description that identifies this campaign.",+ "schedule_type": "How the campaign is scheduled (e.g. `immediate`, `scheduled`).",+ "send_date": "The date the campaign is scheduled to send.",+ "status": "The campaign's current status.",+ "use_type": "The declared use type of the campaign (`marketing` or `operational`).",+ "metadata": "A set of user-defined key/value pairs attached to the campaign.",+ "date_created": "ISO-8601 timestamp of when the campaign was created.",+ "date_modified": "ISO-8601 timestamp of when the campaign was last modified.",+ "object": "The resource type string (`campaign`).",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/lob/lob.py b/posthog/temporal/data_imports/sources/lob/lob.pynew file mode 100644index 000000000000..560cc5caf87b--- /dev/null+++ b/posthog/temporal/data_imports/sources/lob/lob.py@@ -0,0 +1,217 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.lob.settings import LOB_ENDPOINTS, LobEndpointConfig++LOB_BASE_URL = "https://api.lob.com/v1"++# Lob's published rate limit is 150 requests / 5s per endpoint; with a single worker per sync we+# never approach it, but transient 429/5xx still warrant a bounded retry.+PAGE_SIZE = 100 # Lob's documented maximum `limit`.+REQUEST_TIMEOUT_SECONDS = 60+++class LobRetryableError(Exception):+ pass+++class LobResumeConfig:+ # The fully-formed `next_url` returned by Lob (already carries `limit` and the `after` cursor).+ # None means "start from the first page".+ next_url: str | None = None+++def _format_date_filter_value(value: Any) -> str:+ """Format an incremental cursor value for Lob's `date_created[gt]` filter (ISO-8601)."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")+ if isinstance(value, date):+ return value.isoformat()+ return str(value)+++def _parse_date_created(value: Any) -> datetime | None:+ """Parse a Lob `date_created` string (e.g. `2019-08-08T17:09:14.514Z`) into an aware datetime."""+ if not isinstance(value, str):+ return None+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+++def _coerce_watermark(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return None+++def _build_query_string(params: dict[str, str]) -> str:+ """Build a query string with literal brackets.++ Lob filter/sort params use deepObject bracket notation (`date_created[gt]=...`,+ `sort_by[date_created]=asc`). All keys/values here are internally constructed and ASCII-safe+ (ISO datetimes only use `:` and `.`, both legal in a query component), so we emit them verbatim+ to match Lob's documented format rather than percent-encoding the brackets.+ """+ return "&".join(f"{key}={value}" for key, value in params.items())+++def _build_initial_url(+ config: LobEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, str] = {"limit": str(PAGE_SIZE)}++ if config.supports_incremental:+ # Force ascending order so the cursor only ever moves forward to newer rows. Combined with the+ # `date_created[gt]` floor below, every page stays above the watermark and pagination ends when+ # Lob runs out of newer rows (empty `next_url`).+ params["sort_by[date_created]"] = "asc"++ if should_use_incremental_field and db_incremental_field_last_value:+ params["date_created[gt]"] = _format_date_filter_value(db_incremental_field_last_value)++ return f"{LOB_BASE_URL}{config.path}?{_build_query_string(params)}"+++def _get_headers() -> dict[str, str]:+ return {"Accept": "application/json"}+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe a cheap list endpoint. Returns (is_valid, status_code)."""+ url = f"{LOB_BASE_URL}/addresses?limit=1"+ try:+ response = make_tracked_session().get(+ url, auth=(api_key, ""), headers=_get_headers(), timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False, None+ return response.status_code == 200, response.status_code+++@retry(+ retry=retry_if_exception_type((LobRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, api_key: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict:+ response = session.get(url, auth=(api_key, ""), headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise LobRetryableError(f"Lob API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Lob API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LobResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LOB_ENDPOINTS[endpoint]+ headers = _get_headers()+ # One session reused across every page so urllib3 keeps the connection alive between requests.+ session = make_tracked_session()++ watermark = (+ _coerce_watermark(db_incremental_field_last_value)+ if config.supports_incremental and should_use_incremental_field+ else None+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url: str | None = resume.next_url+ logger.debug(f"Lob: resuming from URL: {url}")+ else:+ url = _build_initial_url(config, should_use_incremental_field, db_incremental_field_last_value)++ while url:+ data = _fetch_page(session, url, api_key, headers, logger)++ items = data.get("data", [])+ if not items:+ break++ yield items++ next_url = data.get("next_url") or None++ # Defence-in-depth for incremental endpoints: Lob's `next_url` carries only `limit` + `after`,+ # so if the server were to stop honouring the ascending sort on later pages, the cursor could+ # walk backwards. Stop once an entire page predates the watermark — in the normal ascending+ # path every row is newer than the watermark, so this never triggers.+ if next_url and watermark is not None:+ page_max = max(+ (dt for item in items if (dt := _parse_date_created(item.get("date_created")))),+ default=None,+ )+ if page_max is not None and page_max <= watermark:+ logger.debug("Lob: stopping pagination, page predates incremental watermark")+ break++ if not next_url:+ break++ # Save state AFTER yielding so a crash re-yields the last page (merge dedupes on the primary+ # key) rather than skipping it. Advance before the next fetch to avoid re-fetching this page.+ resumable_source_manager.save_state(LobResumeConfig(next_url=next_url))+ url = next_url+++def lob_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LobResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = LOB_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,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # Incremental endpoints force `sort_by[date_created]=asc`; full-refresh endpoints have no+ # sort param and return Lob's default newest-first (descending) order.+ sort_mode="asc" if endpoint_config.supports_incremental else "desc",+ )diff --git a/posthog/temporal/data_imports/sources/lob/settings.py b/posthog/temporal/data_imports/sources/lob/settings.pynew file mode 100644index 000000000000..f619a1ab96b0--- /dev/null+++ b/posthog/temporal/data_imports/sources/lob/settings.py@@ -0,0 +1,75 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# Every Lob list object carries a stable, immutable `date_created` timestamp. We use it both as the+# partition key (it never changes once a resource is created) and, where the endpoint can be sorted+# ascending, as the incremental cursor via the server-side `date_created[gt]` filter.+DATE_CREATED_INCREMENTAL_FIELD: IncrementalField = {+ "label": "date_created",+ "type": IncrementalFieldType.DateTime,+ "field": "date_created",+ "field_type": IncrementalFieldType.DateTime,+}+++@dataclass+class LobEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Whether to advertise incremental sync for this endpoint. Only set when the endpoint accepts+ # `sort_by[date_created]=asc` so we can paginate forward over a server-side `date_created[gt]`+ # filter; a forward-only ascending cursor stays above the watermark on every page and terminates+ # naturally. Endpoints that only sort newest-first stay full refresh to avoid an unbounded+ # walk-back through history when the cursor drops the time filter.+ supports_incremental: bool = False+ # Field to partition by. Always a creation-time field so partitions never rewrite.+ partition_key: Optional[str] = "date_created"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++LOB_ENDPOINTS: dict[str, LobEndpointConfig] = {+ # Mailpieces: support `sort_by[date_created]` so we can force ascending order for incremental sync.+ "letters": LobEndpointConfig(+ name="letters",+ path="/letters",+ supports_incremental=True,+ incremental_fields=[DATE_CREATED_INCREMENTAL_FIELD],+ ),+ "postcards": LobEndpointConfig(+ name="postcards",+ path="/postcards",+ supports_incremental=True,+ incremental_fields=[DATE_CREATED_INCREMENTAL_FIELD],+ ),+ "checks": LobEndpointConfig(+ name="checks",+ path="/checks",+ supports_incremental=True,+ incremental_fields=[DATE_CREATED_INCREMENTAL_FIELD],+ ),+ "self_mailers": LobEndpointConfig(+ name="self_mailers",+ path="/self_mailers",+ supports_incremental=True,+ incremental_fields=[DATE_CREATED_INCREMENTAL_FIELD],+ ),+ # Addresses, bank accounts and templates expose `date_created` filtering but no `sort_by`, so they+ # only return newest-first. A descending cursor can walk past the watermark into full history if+ # the server drops the time filter on later pages, so these stay full refresh until that can be+ # verified against the live API.+ "addresses": LobEndpointConfig(name="addresses", path="/addresses"),+ "bank_accounts": LobEndpointConfig(name="bank_accounts", path="/bank_accounts"),+ "templates": LobEndpointConfig(name="templates", path="/templates"),+ # Campaigns expose no `date_created` filter at all, so full refresh is the only option.+ "campaigns": LobEndpointConfig(name="campaigns", path="/campaigns"),+}++ENDPOINTS = tuple(LOB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LOB_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/lob/source.py b/posthog/temporal/data_imports/sources/lob/source.pyindex aa25d5db88a8..84e9fd0ae3f3 100644--- a/posthog/temporal/data_imports/sources/lob/source.py+++ b/posthog/temporal/data_imports/sources/lob/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,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.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import LobSourceConfig+from posthog.temporal.data_imports.sources.lob.lob import (+ LobResumeConfig,+ lob_source,+ validate_credentials as validate_lob_credentials,+)+from posthog.temporal.data_imports.sources.lob.settings import ENDPOINTS, INCREMENTAL_FIELDS, LOB_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class LobSource(SimpleSource[LobSourceConfig]):+class LobSource(ResumableSource[LobSourceConfig, LobResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LOB@@ -25,7 +38,102 @@ class LobSource(SimpleSource[LobSourceConfig]):name=SchemaExternalDataSourceType.LOB,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Lob",- iconPath="/static/services/lob.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Lob secret API key to automatically pull your Lob data into the PostHog Data warehouse.++You can find your API keys in your [Lob dashboard](https://dashboard.lob.com/settings/api-keys). Use a **secret** key (it starts with `live_` or `test_`) — publishable keys can only access address verification.++Test and Live keys return different data, so connect the environment whose data you want to sync.""",+ iconPath="/static/services/lob.png",+ docsUrl="https://docs.lob.com/",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="live_... or test_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad key 401s; a valid key lacking access to a resource 403s. Neither is fixable by+ # retrying, so stop the sync. Match the stable status text + base host, not the per-request+ # path/query.+ "401 Client Error: Unauthorized for url: https://api.lob.com": "Your Lob API key is invalid or has been revoked. Create a new secret API key in your Lob dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.lob.com": "Your Lob API key does not have access to this resource. Check that you are using a secret key with the required permissions, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.lob.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: LobSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LOB_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=None if endpoint_config.supports_incremental else "Full refresh only",+ )++ schemas = [_build_schema(endpoint) 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: LobSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ is_valid, status_code = validate_lob_credentials(config.api_key)+ if is_valid:+ return True, None++ # A valid key can legitimately lack access to a given resource (403). Accept that at+ # source-create (schema_name is None) so users can still connect the endpoints they can read;+ # only reject a 403 when validating a specific schema.+ if status_code == 403 and schema_name is None:+ return True, None++ if status_code == 401:+ return False, "Invalid Lob API key"+ return False, "Could not validate Lob API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LobResumeConfig]:+ return ResumableSourceManager[LobResumeConfig](inputs, LobResumeConfig)++ def source_for_pipeline(+ self,+ config: LobSourceConfig,+ resumable_source_manager: ResumableSourceManager[LobResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return lob_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,)diff --git a/posthog/temporal/data_imports/sources/lob/tests/test_lob.py b/posthog/temporal/data_imports/sources/lob/tests/test_lob.pynew file mode 100644index 000000000000..b8ec4b573a3a--- /dev/null+++ b/posthog/temporal/data_imports/sources/lob/tests/test_lob.py@@ -0,0 +1,240 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from posthog.temporal.data_imports.sources.lob.lob import (+ LobResumeConfig,+ LobRetryableError,+ _build_initial_url,+ _fetch_page,+ _format_date_filter_value,+ _parse_date_created,+ get_rows,+ lob_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.lob.settings import LOB_ENDPOINTS+++def _make_response(json_body: dict[str, Any] | None = None, status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp.headers["Content-Type"] = "application/json"+ resp._content = json.dumps(json_body or {}).encode()+ return resp+++def _manager(resume: LobResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestFormatDateFilterValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000000Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000000Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("string_passthrough", "cursor", "cursor"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ assert _format_date_filter_value(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_date_filter_value(datetime(2026, 3, 4, tzinfo=UTC))+++class TestParseDateCreated:+ @parameterized.expand(+ [+ ("z_suffix", "2019-08-08T17:09:14.514Z", datetime(2019, 8, 8, 17, 9, 14, 514000, tzinfo=UTC)),+ ("offset", "2019-08-08T17:09:14+00:00", datetime(2019, 8, 8, 17, 9, 14, tzinfo=UTC)),+ ("garbage", "not-a-date", None),+ ("non_string", 12345, None),+ ]+ )+ def test_parse(self, _name: str, value: object, expected: datetime | None) -> None:+ assert _parse_date_created(value) == expected+++class TestBuildInitialUrl:+ def test_incremental_endpoint_forces_ascending_sort(self) -> None:+ url = _build_initial_url(+ LOB_ENDPOINTS["letters"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert url.startswith("https://api.lob.com/v1/letters?")+ assert "sort_by[date_created]=asc" in url+ assert "limit=100" in url+ assert "date_created[gt]" not in url++ def test_incremental_endpoint_with_watermark_adds_filter(self) -> None:+ url = _build_initial_url(+ LOB_ENDPOINTS["postcards"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ assert "sort_by[date_created]=asc" in url+ assert "date_created[gt]=2026-01-02T03:04:05.000000Z" in url++ def test_full_refresh_endpoint_has_no_sort_or_filter(self) -> None:+ url = _build_initial_url(+ LOB_ENDPOINTS["addresses"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, tzinfo=UTC),+ )+ assert "sort_by" not in url+ assert "date_created[gt]" not in url+ assert "limit=100" in url+++class TestGetRows:+ def test_paginates_following_next_url_and_saves_state_after_each_page(self) -> None:+ pages = [+ {+ "data": [{"id": "ltr_1", "date_created": "2026-01-01T00:00:00Z"}],+ "next_url": "https://api.lob.com/v1/letters?after=cursor1",+ },+ {"data": [{"id": "ltr_2", "date_created": "2026-01-02T00:00:00Z"}], "next_url": None},+ ]+ manager = _manager()+ with patch("posthog.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=pages):+ batches = list(get_rows("k", "letters", MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == ["ltr_1", "ltr_2"]+ # State saved once, after yielding the first page (which had a next_url); not after the last.+ manager.save_state.assert_called_once_with(+ LobResumeConfig(next_url="https://api.lob.com/v1/letters?after=cursor1")+ )++ def test_stops_on_empty_data(self) -> None:+ manager = _manager()+ with patch("posthog.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=[{"data": []}]):+ batches = list(get_rows("k", "letters", MagicMock(), manager))+ assert batches == []+ manager.save_state.assert_not_called()++ def test_resumes_from_saved_next_url(self) -> None:+ manager = _manager(LobResumeConfig(next_url="https://api.lob.com/v1/letters?after=saved"))+ captured: list[str] = []++ def _fetch(_session, url, *_args, **_kwargs):+ captured.append(url)+ return {"data": [{"id": "ltr_9", "date_created": "2026-01-09T00:00:00Z"}], "next_url": None}++ with patch("posthog.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=_fetch):+ list(get_rows("k", "letters", MagicMock(), manager))++ assert captured == ["https://api.lob.com/v1/letters?after=saved"]++ def test_incremental_watermark_guard_stops_when_page_predates_watermark(self) -> None:+ # Defends against the cursor dropping the time filter on later pages: every row here predates+ # the watermark, and there is still a next_url, so pagination must stop instead of walking back.+ pages = [+ {+ "data": [{"id": "ltr_old", "date_created": "2020-01-01T00:00:00Z"}],+ "next_url": "https://api.lob.com/v1/letters?after=cursor",+ },+ ]+ manager = _manager()+ with patch("posthog.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=pages):+ batches = list(+ get_rows(+ "k",+ "letters",+ MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ # The page is still yielded (merge dedupes), but we stop before following the next_url.+ assert [item["id"] for batch in batches for item in batch] == ["ltr_old"]+ manager.save_state.assert_not_called()++ def test_full_refresh_endpoint_ignores_watermark_guard(self) -> None:+ # Full-refresh endpoints have no incremental support, so the watermark guard never engages+ # even if a stale last-value is passed in.+ pages = [+ {+ "data": [{"id": "adr_1", "date_created": "2020-01-01T00:00:00Z"}],+ "next_url": "https://api.lob.com/v1/addresses?after=c",+ },+ {"data": [{"id": "adr_2", "date_created": "2019-01-01T00:00:00Z"}], "next_url": None},+ ]+ manager = _manager()+ with patch("posthog.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=pages):+ batches = list(+ get_rows(+ "k",+ "addresses",+ MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )+ assert [item["id"] for batch in batches for item in batch] == ["adr_1", "adr_2"]+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _make_response({}, status=status)+ # Call the undecorated function so a single attempt raises immediately instead of+ # exercising tenacity's exponential backoff.+ with pytest.raises(LobRetryableError):+ _fetch_page.__wrapped__(session, "https://api.lob.com/v1/letters", "k", {}, MagicMock()) # type: ignore[attr-defined]++ def test_client_error_raises_for_status(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_response({"error": {"message": "bad"}}, status=401)+ with pytest.raises(Exception):+ _fetch_page(session, "https://api.lob.com/v1/letters", "k", {}, MagicMock())++ def test_uses_http_basic_auth_with_blank_password(self) -> None:+ session = MagicMock()+ session.get.return_value = _make_response({"data": []})+ _fetch_page(session, "https://api.lob.com/v1/letters", "my_key", {}, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["auth"] == ("my_key", "")+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status: int, expected_valid: bool) -> None:+ session = MagicMock()+ session.get.return_value = _make_response({}, status=status)+ with patch("posthog.temporal.data_imports.sources.lob.lob.make_tracked_session", return_value=session):+ is_valid, status_code = validate_credentials("k")+ assert is_valid is expected_valid+ assert status_code == status++ def test_network_error_returns_false_and_none_status(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch("posthog.temporal.data_imports.sources.lob.lob.make_tracked_session", return_value=session):+ is_valid, status_code = validate_credentials("k")+ assert is_valid is False+ assert status_code is None+++class TestLobSource:+ @parameterized.expand([("letters", "asc"), ("postcards", "asc"), ("addresses", "desc"), ("campaigns", "desc")])+ def test_sort_mode_matches_incremental_support(self, endpoint: str, expected_sort: str) -> None:+ response = lob_source("k", endpoint, MagicMock(), _manager())+ assert response.sort_mode == expected_sort+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["date_created"]+ assert response.partition_mode == "datetime"diff --git a/posthog/temporal/data_imports/sources/lob/tests/test_lob_source.py b/posthog/temporal/data_imports/sources/lob/tests/test_lob_source.pynew file mode 100644index 000000000000..9148467f2700--- /dev/null+++ b/posthog/temporal/data_imports/sources/lob/tests/test_lob_source.py@@ -0,0 +1,155 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import LobSourceConfig+from posthog.temporal.data_imports.sources.lob.lob import LobResumeConfig+from posthog.temporal.data_imports.sources.lob.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.lob.source import LobSource++from products.data_warehouse.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"letters", "postcards", "checks", "self_mailers"}+FULL_REFRESH_ENDPOINTS = {"addresses", "bank_accounts", "templates", "campaigns"}+++def _inputs(schema_name: str = "letters", **overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "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-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestLobSourceConfig:+ def test_source_type(self) -> None:+ assert LobSource().source_type == ExternalDataSourceType.LOB++ def test_source_config_metadata(self) -> None:+ config = LobSource().get_source_config+ assert config.label == "Lob"+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True++ def test_source_config_has_single_secret_api_key_field(self) -> None:+ fields = LobSource().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+++class TestLobGetSchemas:+ def test_all_endpoints_present(self) -> None:+ schemas = LobSource().get_schemas(LobSourceConfig(api_key="k"), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(sorted(INCREMENTAL_ENDPOINTS))+ def test_incremental_endpoints_support_incremental(self, endpoint: str) -> None:+ schema = next(s for s in LobSource().get_schemas(LobSourceConfig(api_key="k"), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["date_created"]++ @parameterized.expand(sorted(FULL_REFRESH_ENDPOINTS))+ def test_full_refresh_endpoints_do_not_support_incremental(self, endpoint: str) -> None:+ schema = next(s for s in LobSource().get_schemas(LobSourceConfig(api_key="k"), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []+ assert schema.description == "Full refresh only"++ def test_names_filter(self) -> None:+ schemas = LobSource().get_schemas(LobSourceConfig(api_key="k"), team_id=1, names=["letters"])+ assert [s.name for s in schemas] == ["letters"]+++class TestLobValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (True, 200), None, True),+ ("unauthorized", (False, 401), None, False),+ # A 403 at source-create (no schema) is accepted — the key is real but lacks this scope.+ ("forbidden_at_create", (False, 403), None, True),+ # The same 403 when validating a specific schema is rejected.+ ("forbidden_for_schema", (False, 403), "letters", False),+ ("unknown_error", (False, None), None, False),+ ]+ )+ def test_validate(self, _name: str, probe_result, schema_name, expected_valid: bool) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.lob.source.validate_lob_credentials", return_value=probe_result+ ):+ valid, _error = LobSource().validate_credentials(+ LobSourceConfig(api_key="k"), team_id=1, schema_name=schema_name+ )+ assert valid is expected_valid+++class TestLobNonRetryableErrors:+ def test_maps_auth_errors(self) -> None:+ errors = LobSource().get_non_retryable_errors()+ keys = " ".join(errors.keys())+ assert "401" in keys+ assert "403" in keys+ assert all(v for v in errors.values())+++class TestLobResumableWiring:+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = LobSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LobResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ source = LobSource()+ manager = MagicMock()+ with patch("posthog.temporal.data_imports.sources.lob.source.lob_source") as mock_lob_source:+ source.source_for_pipeline(+ LobSourceConfig(api_key="secret"),+ manager,+ _inputs(+ schema_name="postcards",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01",+ ),+ )+ _, kwargs = mock_lob_source.call_args+ assert kwargs["api_key"] == "secret"+ assert kwargs["endpoint"] == "postcards"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"++ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:+ source = LobSource()+ with patch("posthog.temporal.data_imports.sources.lob.source.lob_source") as mock_lob_source:+ source.source_for_pipeline(+ LobSourceConfig(api_key="secret"),+ MagicMock(),+ _inputs(should_use_incremental_field=False, db_incremental_field_last_value="2026-01-01"),+ )+ _, kwargs = mock_lob_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None