: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): add lob billing groups, qr code analytics and uploads tables (#114900)
Tom Owersfbe9e3130259
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 3e0de0899d3a..ba7d6ecd6ec4 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -765,7 +765,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/logz_io/logz_io.py1 products/warehouse_sources/backend/temporal/data_imports/sources/loop_returns/loop_returns.py1 products/warehouse_sources/backend/temporal/data_imports/sources/loops/loops.pydiff --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 8957fa67b5ab..4c3f36c8921d 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@@ -5259,10 +5259,10 @@ Today (8): `addresses`, `bank_accounts`, `campaigns`, `checks`, `letters`, `postDiffed against: <https://raw.githubusercontent.com/lob/lob-openapi/main/lob-api-public.yml>-- [ ] `GET /qr_code_analytics` — QR scan events — the only real engagement/response metric Lob exposes for mail (high)-- [ ] `GET /creatives` — lookup resolving the creative id referenced by campaigns we already sync (high)-- [ ] `GET /billing_groups` — lookup resolving billing_group_id present on every mailpiece, needed for cost attribution (high)-- [ ] `GET /uploads and /uploads/{upl_id}/report` — campaign audience uploads plus per-upload success/failure report (high)+- [x] `GET /qr_code_analytics` — QR scan events — the only real engagement/response metric Lob exposes for mail (high). Added as `qr_code_analytics` (full refresh: scans keep landing on old rows).+- [ ] `GET /creatives` — lookup resolving the creative id referenced by campaigns we already sync (high). Skipped: the API has no list operation for creatives, only create and get-by-id.+- [x] `GET /billing_groups` — lookup resolving billing_group_id present on every mailpiece, needed for cost attribution (high). Added as `billing_groups`.+- [x] `GET /uploads and /uploads/{upl_id}/report` — campaign audience uploads plus per-upload success/failure report (high). Added `uploads`. `/uploads/{upl_id}/report` skipped: Lob gates it behind a per-account feature flag, and its rows echo the raw audience CSV.- [ ] `GET /snap_packs` — a first-class mailpiece type missing alongside letters/postcards/self_mailers (medium)- [ ] `GET /booklets` — a first-class mailpiece type missing from the current set (medium)- [ ] `GET /cards and /cards/{card_id}/orders` — card inventory plus order line items (spend and quantity) (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/canonical_descriptions.pyindex 2ca0bd976b78..c27ac2798620 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/canonical_descriptions.py@@ -139,4 +139,49 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"object": "The resource type string (`campaign`).",},},+ "billing_groups": {+ "description": "Lob billing groups — labels attached to mailpieces so their costs can be split across teams or clients.",+ "docs_url": "https://docs.lob.com/#tag/Billing-Groups",+ "columns": {+ "id": "Unique identifier for the billing group, prefixed `bg_`. Mailpieces reference it in `billing_group_id`.",+ "name": "The billing group's name.",+ "description": "An internal description that identifies this billing group.",+ "date_created": "ISO-8601 timestamp of when the billing group was created.",+ "date_modified": "ISO-8601 timestamp of when the billing group was last modified.",+ "object": "The resource type string (`billing_group`).",+ },+ },+ "qr_code_analytics": {+ "description": "QR code scan analytics, one row per mailpiece that carries a Lob QR code.",+ "docs_url": "https://docs.lob.com/#tag/QR-Codes",+ "columns": {+ "resource_id": "The ID of the mailpiece the QR code is printed on (e.g. `ltr_`, `psc_`, `sfm_`).",+ "date_created": "ISO-8601 timestamp of when the mailpiece was created.",+ "number_of_scans": "How many times the mailpiece's QR code was scanned.",+ "scans": "Each scan of the QR code, with its `scan_date` and `ip_location`.",+ },+ },+ "uploads": {+ "description": "Audience CSV files uploaded to Lob campaigns, with their processing state and counts.",+ "docs_url": "https://docs.lob.com/#tag/Uploads",+ "columns": {+ "id": "Unique identifier for the upload, prefixed `upl_`.",+ "accountId": "The ID of the account that made the upload.",+ "campaignId": "The ID of the campaign the upload belongs to.",+ "mode": "The environment the mailpieces were created in (`test` or `live`).",+ "originalFilename": "The filename of the uploaded CSV.",+ "state": "The processing state of the upload (e.g. `Draft`, `Validating`, `Scheduled`, `Errored`).",+ "totalMailpieces": "The total number of recipients in the upload.",+ "failedMailpieces": "The number of mailpieces that failed to create.",+ "validatedMailpieces": "The number of mailpieces created successfully.",+ "bytesProcessed": "The number of bytes of the CSV processed so far.",+ "failuresUrl": "A URL where the failed rows of the upload can be retrieved.",+ "requiredAddressColumnMapping": "Maps the required Lob address fields to columns in the CSV.",+ "optionalAddressColumnMapping": "Maps the optional Lob address fields to columns in the CSV.",+ "mergeVariableColumnMapping": "Maps template merge variables to columns in the CSV.",+ "metadata": "Upload metadata, including the CSV's column names.",+ "dateCreated": "ISO-8601 timestamp of when the upload was created.",+ "dateModified": "ISO-8601 timestamp of when the upload was last modified.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.pyindex 9d407fd0d158..bc4729976e07 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py@@ -2,6 +2,7 @@ import dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional+from urllib.parse import parse_qsl, urlsplitimport requestsfrom structlog.types import FilteringBoundLogger@@ -78,6 +79,9 @@ def _build_initial_url(should_use_incremental_field: bool,db_incremental_field_last_value: Any,) -> str:+ if config.pagination == "none":+ return f"{LOB_BASE_URL}{config.path}"+params: dict[str, str] = {"limit": str(PAGE_SIZE)}if config.supports_incremental:@@ -92,6 +96,17 @@ def _build_initial_url(return f"{LOB_BASE_URL}{config.path}?{_build_query_string(params)}"+def _next_offset_url(url: str, page_item_count: int) -> str | None:+ # Offset-paged lists carry no `next_url`, so a short page is the only end-of-list signal. The+ # filters stay in the URL we build, so every page keeps the `date_created[gt]` floor.+ if page_item_count < PAGE_SIZE:+ return None+ parts = urlsplit(url)+ params = dict(parse_qsl(parts.query))+ params["offset"] = str(int(params.get("offset", "0")) + page_item_count)+ return f"{parts.scheme}://{parts.netloc}{parts.path}?{_build_query_string(params)}"++def _get_headers() -> dict[str, str]:return {"Accept": "application/json"}@@ -116,7 +131,7 @@ def validate_credentials(api_key: str) -> tuple[bool, int | None]:)def _fetch_page(session: requests.Session, url: str, api_key: str, headers: dict[str, str], logger: FilteringBoundLogger-) -> dict:+) -> dict[str, Any] | list[dict[str, Any]]:response = session.get(url, auth=(api_key, ""), headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)if response.status_code == 429 or response.status_code >= 500:@@ -158,13 +173,18 @@ def get_rows(while url:data = _fetch_page(session, url, api_key, headers, logger)- items = data.get("data", [])+ items = data if isinstance(data, list) else data.get("data", [])if not items:breakyield items- next_url = data.get("next_url") or None+ if config.pagination == "none" or isinstance(data, list):+ next_url = None+ elif config.pagination == "offset":+ next_url = _next_offset_url(url, len(items))+ else:+ 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 coulddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.pyindex 94ac1241f602..8d91f42858fd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/settings.py@@ -1,5 +1,5 @@from dataclasses import dataclass, field-from typing import Optional+from typing import Literal, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -14,7 +14,7 @@ DATE_CREATED_INCREMENTAL_FIELD: IncrementalField = {}-@dataclass+@dataclass(frozen=True)class LobEndpointConfig:name: strpath: str@@ -29,6 +29,9 @@ class LobEndpointConfig:partition_key: Optional[str] = "date_created"primary_keys: list[str] = field(default_factory=lambda: ["id"])should_sync_default: bool = True+ # Most Lob lists page with a `next_url` cursor; a few only accept `offset`, and `/uploads` returns+ # every row in a single bare array.+ pagination: Literal["cursor", "offset", "none"] = "cursor"LOB_ENDPOINTS: dict[str, LobEndpointConfig] = {@@ -66,6 +69,23 @@ LOB_ENDPOINTS: dict[str, LobEndpointConfig] = {"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"),+ "billing_groups": LobEndpointConfig(+ name="billing_groups",+ path="/billing_groups",+ supports_incremental=True,+ incremental_fields=[DATE_CREATED_INCREMENTAL_FIELD],+ pagination="offset",+ ),+ # One row per QR-coded mailpiece, ordered by most recent scan. Scans keep landing on old rows and+ # there is no sort or scan-date filter, so full refresh is the only way to pick them up.+ "qr_code_analytics": LobEndpointConfig(+ name="qr_code_analytics",+ path="/qr_code_analytics",+ primary_keys=["resource_id"],+ pagination="offset",+ ),+ # Uploads use camelCase fields, unlike the rest of the Lob API.+ "uploads": LobEndpointConfig(name="uploads", path="/uploads", partition_key="dateCreated", pagination="none"),}ENDPOINTS = tuple(LOB_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/tests/test_lob.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/tests/test_lob.pyindex 709b549908a2..ebb37752a1cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lob/tests/test_lob.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lob/tests/test_lob.py@@ -141,6 +141,58 @@ class TestGetRows:)assert [item["id"] for batch in batches for item in batch] == ["adr_1", "adr_2"]+ @parameterized.expand(+ [+ (+ "offset_walk_keeps_filters_and_stops_on_short_page",+ "billing_groups",+ [+ {"data": [{"id": f"bg_{i}"} for i in range(100)]},+ {"data": [{"id": "bg_last"}]},+ ],+ [+ "https://api.lob.com/v1/billing_groups?limit=100&sort_by[date_created]=asc"+ "&date_created[gt]=2026-01-01T00:00:00.000000Z",+ "https://api.lob.com/v1/billing_groups?limit=100&sort_by[date_created]=asc"+ "&date_created[gt]=2026-01-01T00:00:00.000000Z&offset=100",+ ],+ 101,+ ),+ (+ "bare_array_is_a_single_page",+ "uploads",+ [[{"id": "upl_1"}, {"id": "upl_2"}]],+ ["https://api.lob.com/v1/uploads"],+ 2,+ ),+ ]+ )+ def test_pagination_modes(+ self, _name: str, endpoint: str, pages: list[Any], expected_urls: list[str], expected_rows: int+ ) -> None:+ captured: list[str] = []++ def _fetch(_session, url, *_args, **_kwargs):+ captured.append(url)+ return pages[len(captured) - 1]++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.lob.lob._fetch_page", side_effect=_fetch+ ):+ batches = list(+ get_rows(+ "k",+ endpoint,+ MagicMock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ assert captured == expected_urls+ assert sum(len(batch) for batch in batches) == expected_rows+class TestFetchPage:@parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])