: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 orb import source (#65653)
Tom Owersb9d77f21ab1c
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex d7d4f2a06323..c85a3266e7ef 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -140,6 +140,7 @@ the row lists both.| okta | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |+| orb | HTTP | requests + `rest_source.RESTClient` | ✅ || ortto | HTTP | requests | ✅ || outbrain | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ |@@ -525,7 +526,6 @@ doesn't conflict with concurrent PRs.- oracle- oracle_ebs- oracle_fusion-- orb- orbit- oura- outlookdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex f92fe07e2ed2..40c305586889 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -2158,7 +2158,7 @@ class OracleSourceConfig(config.Config):@config.configclass OrbSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/orb/canonical_descriptions.py b/posthog/temporal/data_imports/sources/orb/canonical_descriptions.pynew file mode 100644index 000000000000..fe80ab22486a--- /dev/null+++ b/posthog/temporal/data_imports/sources/orb/canonical_descriptions.py@@ -0,0 +1,109 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Descriptions sourced from the public Orb API reference (https://docs.withorb.com/api-reference).+# Keyed by the schema/endpoint name returned by `get_schemas`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Customers": {+ "description": "Your customers — the entities that subscribe to plans and receive invoices in Orb.",+ "docs_url": "https://docs.withorb.com/api-reference/customer/list-customers",+ "columns": {+ "id": "Orb-assigned unique identifier for the customer.",+ "external_customer_id": "Your own alias for the customer, unique within your Orb account.",+ "name": "The full name of the customer.",+ "email": "The email address of the customer.",+ "timezone": "The customer's IANA timezone, used for invoice scheduling. Cannot change after creation.",+ "payment_provider": "The external payment provider linked to the customer (e.g. stripe_invoice, netsuite).",+ "payment_provider_id": "The customer's ID in the linked payment provider.",+ "balance": "The customer's current account balance, in the customer's currency.",+ "currency": "The currency used for the customer's balance and invoices.",+ "auto_collection": "Whether invoices are automatically charged to the customer's payment method.",+ "created_at": "The creation time of the customer in Orb.",+ "metadata": "User-defined key/value pairs attached to the customer.",+ },+ },+ "Plans": {+ "description": "The pricing plans defined in your Orb catalog that customers can subscribe to.",+ "docs_url": "https://docs.withorb.com/api-reference/plan/list-plans",+ "columns": {+ "id": "Orb-assigned unique identifier for the plan.",+ "name": "The name of the plan.",+ "description": "The plan description.",+ "status": "The plan's lifecycle status: active, archived, or draft.",+ "external_plan_id": "Your own alias for the plan, unique within your Orb account.",+ "currency": "The currency the plan's prices are denominated in.",+ "created_at": "The creation time of the plan in Orb.",+ },+ },+ "Subscriptions": {+ "description": "Subscriptions linking a customer to a plan, which drive recurring billing and usage.",+ "docs_url": "https://docs.withorb.com/api-reference/subscription/list-subscriptions",+ "columns": {+ "id": "Orb-assigned unique identifier for the subscription.",+ "status": "The subscription's lifecycle status: active, ended, or upcoming.",+ "customer": "The customer the subscription belongs to.",+ "plan": "The plan the subscription is on.",+ "start_date": "The date the subscription's billing relationship started.",+ "end_date": "The date the subscription ended, if it has.",+ "current_billing_period_start_date": "Start of the current billing period.",+ "current_billing_period_end_date": "End of the current billing period.",+ "created_at": "The creation time of the subscription in Orb.",+ },+ },+ "Invoices": {+ "description": "Invoices issued to customers. Note: incremental sync is keyed on invoice_date, "+ "the only server-side timestamp filter this endpoint exposes.",+ "docs_url": "https://docs.withorb.com/api-reference/invoice/list-invoices",+ "columns": {+ "id": "Orb-assigned unique identifier for the invoice.",+ "status": "The invoice status: issued, paid, synced, void, or draft.",+ "invoice_number": "The auto-generated, customer-facing invoice number.",+ "customer": "The customer the invoice was issued to.",+ "subscription": "The subscription the invoice was generated for, if any.",+ "invoice_date": "The scheduled date of the invoice.",+ "due_date": "The date payment for the invoice is due.",+ "amount_due": "The total amount due on the invoice, in the invoice's currency.",+ "total": "The total amount of the invoice, including line items and adjustments.",+ "currency": "The currency the invoice is denominated in.",+ "created_at": "The creation time of the invoice in Orb.",+ },+ },+ "CreditNotes": {+ "description": "Credit notes that adjust or refund amounts on previously issued invoices.",+ "docs_url": "https://docs.withorb.com/api-reference/credit-note/list-credit-notes",+ "columns": {+ "id": "The Orb id of this credit note.",+ "credit_note_number": "The customer-facing credit note number.",+ "type": "The type of credit note (e.g. refund or adjustment).",+ "reason": "The reason the credit note was issued.",+ "total": "The total amount of the credit note.",+ "customer": "The customer the credit note was issued to.",+ "created_at": "The creation time of the credit note in Orb.",+ "voided_at": "The time the credit note was voided, if it has been.",+ },+ },+ "Items": {+ "description": "Items represent the things being billed for and link usage/prices to your catalog. "+ "Full refresh only — the list endpoint exposes no server-side timestamp filter.",+ "docs_url": "https://docs.withorb.com/api-reference/item/list-items",+ "columns": {+ "id": "The Orb-assigned unique identifier for the item.",+ "name": "The name of the item.",+ "external_connections": "Links between this item and external accounting/billing systems.",+ "created_at": "The time at which the item was created.",+ },+ },+ "Coupons": {+ "description": "Coupons offering discounts that can be redeemed against subscriptions. "+ "Full refresh only — the list endpoint exposes no server-side timestamp filter.",+ "docs_url": "https://docs.withorb.com/api-reference/coupon/list-coupons",+ "columns": {+ "id": "The Orb-assigned unique identifier for the coupon.",+ "redemption_code": "The code customers enter to redeem the coupon.",+ "discount": "The discount the coupon applies (percentage or amount).",+ "times_redeemed": "How many times the coupon has been redeemed.",+ "duration_in_months": "How many months the discount applies for; null means forever.",+ "max_redemptions": "The maximum number of times the coupon can be redeemed.",+ "archived_at": "The time the coupon was archived, if it has been.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/orb/orb.py b/posthog/temporal/data_imports/sources/orb/orb.pynew file mode 100644index 000000000000..aece5ddb947d--- /dev/null+++ b/posthog/temporal/data_imports/sources/orb/orb.py@@ -0,0 +1,181 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Request++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.rest_source import RESTAPIConfig, rest_api_resource+from posthog.temporal.data_imports.sources.common.rest_source.paginators import JSONResponseCursorPaginator+from posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.orb.settings import DEFAULT_PAGE_SIZE, ORB_API_BASE_URL, ORB_ENDPOINTS+++class OrbResumeConfig:+ next_cursor: str+++def _format_incremental_value(value: Any) -> Optional[str]:+ """Format an incremental cursor value for Orb's `<field>[gt]` filters.++ Orb expects RFC 3339 date-times. The incremental field is always a datetime, but `date` and+ `str` are handled defensively. `None` (initial sync, no watermark yet) returns `None` so the+ REST client drops the param and the first sync walks the full history.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _incremental_param_config(incremental_field: str) -> dict[str, Any]:+ return {+ "type": "incremental",+ "cursor_path": incremental_field,+ "initial_value": None,+ "convert": _format_incremental_value,+ }+++class OrbCursorPaginator(JSONResponseCursorPaginator):+ """Cursor pagination over Orb's `pagination_metadata.next_cursor`, with resume support.++ Orb returns `{"data": [...], "pagination_metadata": {"has_more": bool, "next_cursor": str|null}}`+ and the cursor is passed back as the `cursor` query param. The opaque cursor encodes the full+ query (filters + sort), so any `created_at[gt]` filter set on the first request stays applied+ across pages and pagination terminates naturally once `has_more` is false — there's no+ unbounded walk-back past the incremental watermark.+ """++ def __init__(self) -> None:+ super().__init__(cursor_path="pagination_metadata.next_cursor", cursor_param="cursor")++ def init_request(self, request: Request) -> None:+ # Seed a resumed cursor onto the very first request.+ if self._cursor_value is not None:+ if request.params is None:+ request.params = {}+ request.params[self.cursor_param] = self._cursor_value++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._cursor_value is not None and self._has_next_page:+ return {"next_cursor": self._cursor_value}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ next_cursor = state.get("next_cursor")+ if next_cursor is not None:+ self._cursor_value = str(next_cursor)+ self._has_next_page = True+++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ cfg = ORB_ENDPOINTS[name]++ incremental = (+ should_use_incremental_field and cfg.incremental_param is not None and cfg.incremental_field is not None+ )++ params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}+ if incremental:+ assert cfg.incremental_param is not None and cfg.incremental_field is not None+ params[cfg.incremental_param] = _incremental_param_config(cfg.incremental_field)++ return {+ "name": cfg.name,+ "table_name": cfg.table_name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if incremental else "replace",+ "endpoint": {+ "data_selector": "data",+ "path": cfg.path,+ "params": params,+ },+ "table_format": "delta",+ }+++def orb_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[OrbResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ cfg = ORB_ENDPOINTS[endpoint]++ config: RESTAPIConfig = {+ "client": {+ "base_url": ORB_API_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "paginator": OrbCursorPaginator(),+ },+ "resource_defaults": None,+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"next_cursor": resume_config.next_cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page exists; the Redis TTL cleans up on completion. Saving+ # after each yielded batch means a crash re-yields the last page (merge dedupes on the+ # primary key) rather than skipping it.+ if state and state.get("next_cursor"):+ resumable_source_manager.save_state(OrbResumeConfig(next_cursor=str(state["next_cursor"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=cfg.primary_keys,+ column_hints=resource.column_hints,+ # Orb has no sort param — list endpoints always return newest-created first.+ sort_mode="desc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if cfg.partition_key else None,+ partition_format="week" if cfg.partition_key else None,+ partition_keys=[cfg.partition_key] if cfg.partition_key else None,+ )+++def validate_credentials(api_key: str) -> bool:+ """Cheap probe against `/customers` to confirm the Bearer token is genuine.++ Returns False only for auth failures (401/403). Transient or unexpected statuses+ (429, 5xx, …) are raised via `raise_for_status()` so they surface as a real error+ rather than being misreported to the user as an invalid API key.+ """+ response = make_tracked_session().get(+ f"{ORB_API_BASE_URL}/customers",+ params={"limit": 1},+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=30,+ )+ if response.status_code in (401, 403):+ return False+ response.raise_for_status()+ return Truediff --git a/posthog/temporal/data_imports/sources/orb/settings.py b/posthog/temporal/data_imports/sources/orb/settings.pynew file mode 100644index 000000000000..54526bdbd1eb--- /dev/null+++ b/posthog/temporal/data_imports/sources/orb/settings.py@@ -0,0 +1,104 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++ORB_API_BASE_URL = "https://api.withorb.com/v1"++# Orb caps list endpoints at 100 items per page (default 20).+DEFAULT_PAGE_SIZE = 100+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class OrbEndpointConfig:+ name: str+ path: str+ table_name: str+ # Query-param key for the server-side "strictly greater than" timestamp filter used for+ # incremental syncs (e.g. "created_at[gt]"). None => the endpoint has no server-side time+ # filter, so it is full-refresh only.+ incremental_param: Optional[str] = None+ # Object field the incremental_param filters on (e.g. "created_at"). Drives INCREMENTAL_FIELDS.+ incremental_field: Optional[str] = None+ # Stable datetime field to partition by. Must never change after creation, so always a+ # creation-style field (created_at), never a mutable one.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Top-level Orb list endpoints. All return `{"data": [...], "pagination_metadata": {...}}`, are+# cursor-paginated, and sort newest-first by creation time. Incremental endpoints expose a+# server-side `<field>[gt]` timestamp filter; the rest are full-refresh only.+#+# Invoices is the odd one out: it has no `created_at` filter, only `invoice_date[gt]`, so its+# incremental cursor is `invoice_date` while it still partitions on the stable `created_at`.+ORB_ENDPOINTS: dict[str, OrbEndpointConfig] = {+ "Customers": OrbEndpointConfig(+ name="Customers",+ path="/customers",+ table_name="customers",+ incremental_param="created_at[gt]",+ incremental_field="created_at",+ partition_key="created_at",+ ),+ "Plans": OrbEndpointConfig(+ name="Plans",+ path="/plans",+ table_name="plans",+ incremental_param="created_at[gt]",+ incremental_field="created_at",+ partition_key="created_at",+ ),+ "Subscriptions": OrbEndpointConfig(+ name="Subscriptions",+ path="/subscriptions",+ table_name="subscriptions",+ incremental_param="created_at[gt]",+ incremental_field="created_at",+ partition_key="created_at",+ ),+ "Invoices": OrbEndpointConfig(+ name="Invoices",+ path="/invoices",+ table_name="invoices",+ incremental_param="invoice_date[gt]",+ incremental_field="invoice_date",+ partition_key="created_at",+ ),+ "CreditNotes": OrbEndpointConfig(+ name="CreditNotes",+ path="/credit_notes",+ table_name="credit_notes",+ incremental_param="created_at[gt]",+ incremental_field="created_at",+ partition_key="created_at",+ ),+ "Items": OrbEndpointConfig(+ name="Items",+ path="/items",+ table_name="items",+ partition_key="created_at",+ ),+ "Coupons": OrbEndpointConfig(+ name="Coupons",+ path="/coupons",+ table_name="coupons",+ ),+}++ENDPOINTS = tuple(ORB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [_datetime_field(cfg.incremental_field)]+ for name, cfg in ORB_ENDPOINTS.items()+ if cfg.incremental_field is not None+}diff --git a/posthog/temporal/data_imports/sources/orb/source.py b/posthog/temporal/data_imports/sources/orb/source.pyindex e3aeba2462fa..292c41e66546 100644--- a/posthog/temporal/data_imports/sources/orb/source.py+++ b/posthog/temporal/data_imports/sources/orb/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 OrbSourceConfig+from posthog.temporal.data_imports.sources.orb.orb import (+ OrbResumeConfig,+ orb_source,+ validate_credentials as validate_orb_credentials,+)+from posthog.temporal.data_imports.sources.orb.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class OrbSource(SimpleSource[OrbSourceConfig]):+class OrbSource(ResumableSource[OrbSourceConfig, OrbResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ORB@@ -25,7 +38,90 @@ class OrbSource(SimpleSource[OrbSourceConfig]):name=SchemaExternalDataSourceType.ORB,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Orb",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Orb API key to automatically pull your Orb billing data into the PostHog Data warehouse.++You can create an API key in your [Orb account settings](https://app.withorb.com/settings). A read-only key is sufficient.""",iconPath="/static/services/orb.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/orb",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked key surfaces as an HTTPError when the REST client calls+ # raise_for_status(). Retrying can never satisfy a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://api.withorb.com": "Your Orb API key is invalid or has been revoked. Create a new API key in your Orb account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.withorb.com": "Your Orb API key does not have permission to read this data. Check the key's permissions in your Orb account settings, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.orb.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: OrbSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ incremental_fields=INCREMENTAL_FIELDS.get(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: OrbSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_orb_credentials(config.api_key):+ return True, None++ return False, "Invalid Orb API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OrbResumeConfig]:+ return ResumableSourceManager[OrbResumeConfig](inputs, OrbResumeConfig)++ def source_for_pipeline(+ self,+ config: OrbSourceConfig,+ resumable_source_manager: ResumableSourceManager[OrbResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return orb_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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/orb/tests/test_orb.py b/posthog/temporal/data_imports/sources/orb/tests/test_orb.pynew file mode 100644index 000000000000..dddb750b674f--- /dev/null+++ b/posthog/temporal/data_imports/sources/orb/tests/test_orb.py@@ -0,0 +1,269 @@+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests.exceptions import HTTPError++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.orb.orb import (+ OrbCursorPaginator,+ OrbResumeConfig,+ _format_incremental_value,+ get_resource,+ orb_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.orb.settings import ENDPOINTS, ORB_ENDPOINTS+++def _response(body: dict[str, Any]) -> MagicMock:+ response = MagicMock()+ response.json.return_value = body+ return response+++class TestOrbCursorPaginator:+ def test_initial_state(self) -> None:+ paginator = OrbCursorPaginator()+ # BasePaginator starts has_next_page=True so the first request always runs.+ assert paginator.has_next_page is True+ assert paginator._cursor_value is None+ assert paginator.cursor_param == "cursor"++ def test_update_state_has_more(self) -> None:+ paginator = OrbCursorPaginator()+ paginator.update_state(+ _response({"data": [{"id": "c1"}], "pagination_metadata": {"has_more": True, "next_cursor": "cursor-1"}})+ )+ assert paginator._cursor_value == "cursor-1"+ assert paginator.has_next_page is True++ def test_update_state_terminal_page(self) -> None:+ paginator = OrbCursorPaginator()+ paginator.update_state(+ _response({"data": [{"id": "c1"}], "pagination_metadata": {"has_more": False, "next_cursor": None}})+ )+ assert paginator.has_next_page is False++ def test_update_request_adds_cursor_param(self) -> None:+ paginator = OrbCursorPaginator()+ paginator.update_state(+ _response({"data": [], "pagination_metadata": {"has_more": True, "next_cursor": "cursor-2"}})+ )+ request = MagicMock()+ request.params = {"limit": 100}+ paginator.update_request(request)+ assert request.params["cursor"] == "cursor-2"++ @parameterized.expand([("fresh", None), ("resumed", "cursor-99")])+ def test_init_request_honours_seeded_cursor(self, _label: str, seeded_cursor: str | None) -> None:+ paginator = OrbCursorPaginator()+ if seeded_cursor is not None:+ paginator.set_resume_state({"next_cursor": seeded_cursor})++ request = MagicMock()+ request.params = {"limit": 100}+ paginator.init_request(request)++ if seeded_cursor is None:+ assert "cursor" not in request.params+ else:+ assert request.params["cursor"] == seeded_cursor+ assert paginator.has_next_page is True++ def test_resume_state_round_trip(self) -> None:+ paginator = OrbCursorPaginator()+ paginator.update_state(+ _response({"data": [], "pagination_metadata": {"has_more": True, "next_cursor": "cursor-3"}})+ )+ assert paginator.get_resume_state() == {"next_cursor": "cursor-3"}++ def test_no_resume_state_on_terminal_page(self) -> None:+ paginator = OrbCursorPaginator()+ paginator.update_state(_response({"data": [], "pagination_metadata": {"has_more": False, "next_cursor": None}}))+ # No next page => nothing to resume to.+ assert paginator.get_resume_state() is None+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("none_passthrough", None, None),+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("string_passthrough", "some-cursor", "some-cursor"),+ ]+ )+ def test_format(self, _label: str, value: object, expected: object) -> None:+ assert _format_incremental_value(value) == expected+++class TestGetResource:+ @staticmethod+ def _params(resource: Any) -> dict[str, Any]:+ endpoint = cast(dict[str, Any], resource["endpoint"])+ return cast(dict[str, Any], endpoint["params"])++ @parameterized.expand(list(ENDPOINTS))+ def test_resource_shape(self, endpoint: str) -> None:+ cfg = ORB_ENDPOINTS[endpoint]+ resource = get_resource(endpoint, should_use_incremental_field=False)+ endpoint_config = cast(dict[str, Any], resource["endpoint"])+ params = self._params(resource)++ assert resource["name"] == cfg.name+ assert resource["table_name"] == cfg.table_name+ assert resource["table_format"] == "delta"+ assert endpoint_config["path"] == cfg.path+ assert endpoint_config["data_selector"] == "data"+ assert params["limit"] == 100+ # Non-incremental call never sets a timestamp filter and replaces the table.+ assert resource["write_disposition"] == "replace"+ if cfg.incremental_param is not None:+ assert cfg.incremental_param not in params++ @parameterized.expand([e for e in ENDPOINTS if ORB_ENDPOINTS[e].incremental_param is not None])+ def test_incremental_resource_sets_filter_and_merges(self, endpoint: str) -> None:+ cfg = ORB_ENDPOINTS[endpoint]+ assert cfg.incremental_param is not None+ resource = get_resource(endpoint, should_use_incremental_field=True)++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ param = cast(dict[str, Any], self._params(resource)[cfg.incremental_param])+ assert param["type"] == "incremental"+ assert param["cursor_path"] == cfg.incremental_field+ assert param["convert"] is _format_incremental_value++ @parameterized.expand([e for e in ENDPOINTS if ORB_ENDPOINTS[e].incremental_param is None])+ def test_full_refresh_endpoint_ignores_incremental_flag(self, endpoint: str) -> None:+ # Items / Coupons have no server-side time filter: even with incremental requested they+ # stay full-refresh (replace) so we never silently emit a bogus filter param.+ resource = get_resource(endpoint, should_use_incremental_field=True)+ assert resource["write_disposition"] == "replace"+ assert set(self._params(resource).keys()) == {"limit"}++ def test_invoices_uses_invoice_date_filter(self) -> None:+ resource = get_resource("Invoices", should_use_incremental_field=True)+ params = self._params(resource)+ assert "invoice_date[gt]" in params+ assert "created_at[gt]" not in params+++class TestOrbSource:+ def _manager(self, *, can_resume: bool, state: OrbResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager++ @patch("posthog.temporal.data_imports.sources.orb.orb.rest_api_resource")+ def test_source_response_fields(self, mock_rest: MagicMock) -> None:+ mock_resource = MagicMock()+ mock_resource.name = "Customers"+ mock_resource.column_hints = None+ mock_rest.return_value = mock_resource++ response = orb_source(+ api_key="key",+ endpoint="Customers",+ team_id=1,+ job_id="job",+ resumable_source_manager=self._manager(can_resume=False),+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ )++ assert response.name == "Customers"+ assert response.primary_keys == ["id"]+ # Orb always returns newest-first.+ assert response.sort_mode == "desc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ @patch("posthog.temporal.data_imports.sources.orb.orb.rest_api_resource")+ def test_coupons_has_no_partitioning(self, mock_rest: MagicMock) -> None:+ mock_resource = MagicMock()+ mock_resource.name = "Coupons"+ mock_resource.column_hints = None+ mock_rest.return_value = mock_resource++ response = orb_source(+ api_key="key",+ endpoint="Coupons",+ team_id=1,+ job_id="job",+ resumable_source_manager=self._manager(can_resume=False),+ db_incremental_field_last_value=None,+ )+ # Coupons exposes no stable created_at field, so it can't be partitioned.+ assert response.partition_mode is None+ assert response.partition_keys is None++ @patch("posthog.temporal.data_imports.sources.orb.orb.rest_api_resource")+ def test_seeds_initial_paginator_state_from_saved_cursor(self, mock_rest: MagicMock) -> None:+ mock_rest.return_value = MagicMock(name="Customers", column_hints=None)+ manager = self._manager(can_resume=True, state=OrbResumeConfig(next_cursor="saved-cursor"))++ orb_source(+ api_key="key",+ endpoint="Customers",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )++ _, kwargs = mock_rest.call_args+ assert kwargs["initial_paginator_state"] == {"next_cursor": "saved-cursor"}++ @patch("posthog.temporal.data_imports.sources.orb.orb.rest_api_resource")+ def test_resume_hook_saves_state_after_batch(self, mock_rest: MagicMock) -> None:+ mock_rest.return_value = MagicMock(name="Customers", column_hints=None)+ manager = self._manager(can_resume=False)++ orb_source(+ api_key="key",+ endpoint="Customers",+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=None,+ )++ _, kwargs = mock_rest.call_args+ resume_hook = kwargs["resume_hook"]++ # A page with a next cursor persists; a terminal page (no cursor) saves nothing.+ resume_hook({"next_cursor": "next-1"})+ manager.save_state.assert_called_once_with(OrbResumeConfig(next_cursor="next-1"))++ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ @patch("posthog.temporal.data_imports.sources.orb.orb.make_tracked_session")+ def test_status_mapping(self, _label: str, status_code: int, expected: bool, mock_session: MagicMock) -> None:+ response = MagicMock()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("key") is expected++ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ @patch("posthog.temporal.data_imports.sources.orb.orb.make_tracked_session")+ def test_transient_errors_raise(self, _label: str, status_code: int, mock_session: MagicMock) -> None:+ # Transient/unexpected statuses must not be reported as an invalid API key — they raise.+ response = MagicMock()+ response.status_code = status_code+ response.raise_for_status.side_effect = HTTPError+ mock_session.return_value.get.return_value = response++ with pytest.raises(HTTPError):+ validate_credentials("key")diff --git a/posthog/temporal/data_imports/sources/orb/tests/test_orb_source.py b/posthog/temporal/data_imports/sources/orb/tests/test_orb_source.pynew file mode 100644index 000000000000..45071fefc509--- /dev/null+++ b/posthog/temporal/data_imports/sources/orb/tests/test_orb_source.py@@ -0,0 +1,130 @@+from typing import Any, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import OrbSourceConfig+from posthog.temporal.data_imports.sources.orb.orb import OrbResumeConfig+from posthog.temporal.data_imports.sources.orb.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.orb.source import OrbSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config() -> OrbSourceConfig:+ return OrbSourceConfig(api_key="orb-key")+++class TestOrbSourceConfig:+ def test_source_type(self) -> None:+ assert OrbSource().source_type == ExternalDataSourceType.ORB++ def test_get_source_config(self) -> None:+ config = OrbSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.ORB+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Shipped behind the unreleased flag while in alpha.+ assert config.unreleasedSource is True++ def test_single_secret_api_key_field(self) -> None:+ fields = OrbSource().get_source_config.fields+ assert fields is not None+ assert len(fields) == 1+ api_key_field = fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True+++class TestGetSchemas:+ def test_returns_all_endpoints(self) -> None:+ schemas = OrbSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(list(ENDPOINTS))+ def test_incremental_support_matches_settings(self, endpoint: str) -> None:+ schema = next(s for s in OrbSource().get_schemas(_config(), team_id=1) if s.name == endpoint)+ expected = endpoint in INCREMENTAL_FIELDS+ assert schema.supports_incremental is expected+ assert schema.supports_append is expected+ if expected:+ assert schema.incremental_fields == INCREMENTAL_FIELDS[endpoint]++ def test_names_filter(self) -> None:+ schemas = OrbSource().get_schemas(_config(), team_id=1, names=["Customers", "Coupons"])+ assert {s.name for s in schemas} == {"Customers", "Coupons"}+++class TestValidateCredentials:+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ @patch("posthog.temporal.data_imports.sources.orb.source.validate_orb_credentials")+ def test_validate(self, _label: str, api_result: bool, expected_ok: bool, mock_validate: MagicMock) -> None:+ mock_validate.return_value = api_result+ ok, error = OrbSource().validate_credentials(_config(), team_id=1)+ assert ok is expected_ok+ assert (error is None) is expected_ok+++class TestSourceWiring:+ def test_non_retryable_errors_cover_auth(self) -> None:+ errors = OrbSource().get_non_retryable_errors()+ keys = " ".join(errors.keys())+ assert "401" in keys+ assert "403" in keys++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = OrbSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OrbResumeConfig++ def test_canonical_descriptions_present(self) -> None:+ descriptions = OrbSource().get_canonical_descriptions()+ # Keyed by schema name; every documented key must be a real endpoint.+ assert "Customers" in descriptions+ assert set(descriptions.keys()).issubset(set(ENDPOINTS))++ @patch("posthog.temporal.data_imports.sources.orb.source.orb_source")+ def test_source_for_pipeline_plumbing(self, mock_orb_source: MagicMock) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = MagicMock()+ inputs.schema_name = "Customers"+ inputs.team_id = 7+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00+00:00"++ OrbSource().source_for_pipeline(_config(), manager, inputs)++ kwargs = cast(dict[str, Any], mock_orb_source.call_args.kwargs)+ assert kwargs["api_key"] == "orb-key"+ assert kwargs["endpoint"] == "Customers"+ assert kwargs["team_id"] == 7+ assert kwargs["job_id"] == "job-1"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"+ assert kwargs["resumable_source_manager"] is manager++ @patch("posthog.temporal.data_imports.sources.orb.source.orb_source")+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_orb_source: MagicMock) -> None:+ inputs = MagicMock()+ inputs.schema_name = "Items"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "should-be-ignored"++ OrbSource().source_for_pipeline(_config(), MagicMock(spec=ResumableSourceManager), inputs)++ assert mock_orb_source.call_args.kwargs["db_incremental_field_last_value"] is None