: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 stigg import source (#69364)
Tom Owers95aaef9e4d4e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b276f3c65614..9caddcce63c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -335,6 +335,7 @@ the row lists both.| square | HTTP | requests | ✅ || squarespace | HTTP | requests | ✅ || statuspage | HTTP | requests | ✅ |+| stigg | HTTP | requests | ✅ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ |@@ -706,7 +707,6 @@ doesn't conflict with concurrent PRs.- spotify_ads- spotlercrm- statsig-- stigg- stockdata- strava- streamelementsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 80fe4fee216d..537ce2b81125 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3263,7 +3263,7 @@ class StatuspageSourceConfig(config.Config):@config.configclass StiggSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/canonical_descriptions.pynew file mode 100644index 000000000000..445f9b3d61a2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/canonical_descriptions.py@@ -0,0 +1,154 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Stigg API reference (https://docs.stigg.io and the OpenAPI spec+# served at https://api.stigg.io/api/v1). Partial coverage is fine; uncovered columns fall back+# to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "customers": {+ "description": "A customer provisioned in Stigg, representing an account that can hold subscriptions and entitlements.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The customer slug, the unique identifier of the customer.",+ "name": "The name of the customer.",+ "email": "The email of the customer.",+ "billingId": "The unique identifier for the customer in the billing provider.",+ "billingCurrency": "The billing currency of the customer.",+ "couponId": "Customer level coupon applied to the customer.",+ "timezone": "Timezone to use for this customer.",+ "language": "Language to use for this customer.",+ "metadata": "Additional metadata attached to the customer.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ "archivedAt": "Timestamp of when the record was archived.",+ },+ },+ "subscriptions": {+ "description": "A subscription of a customer to a plan, including its status, billing period, prices, addons, and entitlements. The list endpoint omits subscriptionEntitlements for performance at scale.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The unique ID of the subscription.",+ "customerId": "The ID of the customer the subscription belongs to.",+ "payingCustomerId": "Paying customer ID for delegated billing.",+ "resourceId": "The ID of the resource the subscription is for, when using multiple subscriptions per product.",+ "billingId": "The unique identifier for the subscription in the billing provider.",+ "planId": "The ID of the plan the subscription is for.",+ "status": "The status of the subscription.",+ "pricingType": "The pricing type of the subscription.",+ "paymentCollection": "The payment collection status of the subscription.",+ "startDate": "The subscription start date.",+ "endDate": "The subscription end date.",+ "effectiveEndDate": "The subscription effective end date.",+ "cancellationDate": "The subscription cancellation date.",+ "trialEndDate": "The subscription trial end date.",+ "cancelReason": "The reason the subscription was cancelled.",+ "currentBillingPeriodStart": "Start of the current billing period.",+ "currentBillingPeriodEnd": "End of the current billing period.",+ "billingCycleAnchor": "Billing cycle anchor date.",+ "prices": "The prices attached to the subscription.",+ "addons": "The addons attached to the subscription.",+ "coupons": "Coupons applied to the subscription.",+ "futureUpdates": "Scheduled future updates for the subscription.",+ "metadata": "Additional metadata attached to the subscription.",+ "createdAt": "Timestamp of when the record was created.",+ },+ },+ "products": {+ "description": "A product defined in the Stigg catalog. Plans and addons belong to a product.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The unique identifier of the product.",+ "displayName": "Display name of the product.",+ "description": "Description of the product.",+ "status": "The status of the product.",+ "multipleSubscriptions": "Whether multiple subscriptions to this product are allowed.",+ "productSettings": "Product behavior settings for subscription lifecycle management.",+ "metadata": "Additional metadata attached to the product.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ },+ },+ "plans": {+ "description": "A plan (versioned package) in the Stigg catalog, including its pricing type, entitlements, and trial configuration.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The plan slug, shared by every version of the plan.",+ "versionNumber": "The version number of the plan.",+ "isLatest": "Whether this is the latest version of the plan.",+ "displayName": "The display name of the plan.",+ "description": "The description of the plan.",+ "productId": "The ID of the product the plan belongs to.",+ "status": "The status of the plan.",+ "pricingType": "The pricing type of the plan.",+ "billingId": "The unique identifier for the plan in the billing provider.",+ "entitlements": "List of entitlements of the plan.",+ "parentPlanId": "The ID of the parent plan, if applicable.",+ "defaultTrialConfig": "Default trial configuration for the plan.",+ "compatibleAddonIds": "IDs of addons compatible with the plan.",+ "metadata": "Additional metadata attached to the plan.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ },+ },+ "addons": {+ "description": "An addon (versioned package) in the Stigg catalog that can be attached to subscriptions on top of a plan.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The addon slug, shared by every version of the addon.",+ "versionNumber": "The version number of the addon.",+ "isLatest": "Whether this is the latest version of the addon.",+ "displayName": "The display name of the addon.",+ "description": "The description of the addon.",+ "productId": "The ID of the product the addon belongs to.",+ "status": "The status of the addon.",+ "pricingType": "The pricing type of the addon.",+ "billingId": "The unique identifier for the addon in the billing provider.",+ "entitlements": "List of entitlements of the addon.",+ "maxQuantity": "The maximum quantity of this addon that can be added to a subscription.",+ "dependencies": "List of addons this addon depends on.",+ "metadata": "Additional metadata attached to the addon.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ },+ },+ "features": {+ "description": "A feature in the Stigg catalog that plans and addons grant entitlements to, such as a boolean gate, a configuration value, or a metered usage limit.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The unique identifier of the feature.",+ "displayName": "The display name of the feature.",+ "description": "The description of the feature.",+ "featureType": "The type of the feature.",+ "meterType": "The meter type of the feature.",+ "featureUnits": "The units of the feature.",+ "featureUnitsPlural": "The plural units of the feature.",+ "featureStatus": "The status of the feature.",+ "unitTransformation": "Unit transformation applied to the reported usage.",+ "enumConfiguration": "The configuration data for the feature.",+ "metadata": "Additional metadata attached to the feature.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ },+ },+ "coupons": {+ "description": "A coupon that can be applied to customers or subscriptions for percentage or fixed amount discounts.",+ "docs_url": "https://docs.stigg.io",+ "columns": {+ "id": "The unique identifier of the coupon.",+ "name": "Name of the coupon.",+ "description": "Description of the coupon.",+ "type": "Type of the coupon (percentage or fixed amount).",+ "status": "Current status of the coupon.",+ "source": "The source of the coupon.",+ "percentOff": "Percentage discount off the original price.",+ "amountsOff": "Fixed amount discounts in different currencies.",+ "billingId": "The unique identifier for the coupon in the billing provider.",+ "billingLinkUrl": "The URL to the coupon in the billing provider.",+ "durationInMonths": "Duration of the coupon validity in months.",+ "metadata": "Additional metadata attached to the coupon.",+ "createdAt": "Timestamp of when the record was created.",+ "updatedAt": "Timestamp of when the record was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/settings.pynew file mode 100644index 000000000000..a5e2f94fc9ca--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/settings.py@@ -0,0 +1,44 @@+from dataclasses import dataclass, field+++@dataclass+class StiggEndpointConfig:+ name: str+ path: str+ # Most Stigg object IDs (customer/subscription/feature slugs) are unique across the+ # environment the API key scopes to, so `id` is a safe default primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp used for datetime partitioning. `createdAt` is a required+ # field on every list DTO in Stigg's OpenAPI spec and never changes after creation.+ partition_key: str = "createdAt"+++# Stigg REST API (https://api.stigg.io/api/v1) list endpoints. All are full refresh only:+# the list endpoints expose a server-side `createdAt` range filter but no updated-since+# filter, and billing objects (subscriptions, plans, customers) mutate in place — syncing+# incrementally on creation time would permanently miss those updates, so we do not+# advertise it. Change capture on Stigg's side is webhook/queue based, with manual setup+# only (no programmatic webhook management API).+STIGG_ENDPOINTS: dict[str, StiggEndpointConfig] = {+ "customers": StiggEndpointConfig(name="customers", path="/customers"),+ "subscriptions": StiggEndpointConfig(name="subscriptions", path="/subscriptions"),+ "products": StiggEndpointConfig(name="products", path="/products"),+ # Plans and addons are versioned packages: `id` is the package slug shared by every+ # version, so the composite key with `versionNumber` keeps rows unique table-wide.+ "plans": StiggEndpointConfig(+ name="plans",+ path="/plans",+ primary_keys=["id", "versionNumber"],+ ),+ "addons": StiggEndpointConfig(+ name="addons",+ path="/addons",+ primary_keys=["id", "versionNumber"],+ ),+ "features": StiggEndpointConfig(name="features", path="/features"),+ "coupons": StiggEndpointConfig(name="coupons", path="/coupons"),+}++ENDPOINTS = tuple(STIGG_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/source.pyindex 29d0324b5965..a86cac08e0ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/source.py@@ -1,19 +1,39 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import StiggSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.settings import ENDPOINTS, STIGG_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.stigg import (+ StiggResumeConfig,+ stigg_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class StiggSource(SimpleSource[StiggSourceConfig]):+class StiggSource(ResumableSource[StiggSourceConfig, StiggResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.STIGG@@ -24,7 +44,88 @@ class StiggSource(SimpleSource[StiggSourceConfig]):name=SchemaExternalDataSourceType.STIGG,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Stigg",- iconPath="/static/services/stigg.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Stigg server API key to pull your pricing, packaging, and monetization data into the PostHog Data warehouse.++You can find your server API key under **Settings → Integrations → API keys** in [Stigg](https://app.stigg.io). The key grants read access to your customers, subscriptions, products, plans, addons, features, and coupons.+""",+ iconPath="/static/services/stigg.png",+ docsUrl="https://posthog.com/docs/cdp/sources/stigg",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Server API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.stigg.io": "Your Stigg API key is invalid or has been revoked. Generate a new server API key under Settings → Integrations → API keys, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.stigg.io": "Your Stigg API key does not have access to this data. Use a server API key with read access, then reconnect.",+ }++ def get_schemas(+ self,+ config: StiggSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only. Stigg's list endpoints filter by `createdAt` but+ # expose no updated-since filter, and billing objects mutate in place, so there is no+ # incremental cursor that would also capture updates.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: StiggSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Server API keys are environment-wide, so a single probe validates access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[StiggResumeConfig]:+ return ResumableSourceManager[StiggResumeConfig](inputs, StiggResumeConfig)++ def source_for_pipeline(+ self,+ config: StiggSourceConfig,+ resumable_source_manager: ResumableSourceManager[StiggResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in STIGG_ENDPOINTS:+ raise ValueError(f"Unknown Stigg schema '{inputs.schema_name}'")++ return stigg_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/stigg.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/stigg.pynew file mode 100644index 000000000000..7d021526ab8b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/stigg.py@@ -0,0 +1,162 @@+import dataclasses+from collections.abc import Iterator+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.settings import STIGG_ENDPOINTS++STIGG_BASE_URL = "https://api.stigg.io/api/v1"+# List endpoints accept a `limit` of up to 100 (default 20); the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. Server API keys are environment-wide,+# so one probe validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/customers"+++class StiggRetryableError(Exception):+ pass+++class StiggResumeConfig:+ # Cursor for the next page: Stigg returns it as `pagination.next` and accepts it back as+ # the `after` query param. A crashed full-refresh sync resumes from the page after the last+ # one yielded; merge dedupes the re-pulled page on the primary key. `None` means start from+ # the first page.+ cursor: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-API-KEY": api_key, "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((StiggRetryableError, 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,+ path: str,+ cursor: str | None,+ limit: int,+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], str | None]:+ params: dict[str, Any] = {"limit": limit}+ if cursor is not None:+ params["after"] = cursor++ response = session.get(+ f"{STIGG_BASE_URL}{path}",+ params=params,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if response.status_code == 429 or response.status_code >= 500:+ raise StiggRetryableError(f"Stigg API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Stigg API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # Stigg list endpoints wrap records in {"data": [...], "pagination": {"next": ..., "prev": ...}}.+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):+ raise StiggRetryableError(f"Stigg returned an unexpected payload for {path}: {type(data).__name__}")++ items: list[dict[str, Any]] = data["data"]+ pagination = data.get("pagination") or {}+ next_cursor = pagination.get("next") if isinstance(pagination, dict) else None+ return items, next_cursor+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StiggResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = STIGG_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ cursor = resume.cursor if resume else None+ if resume and resume.cursor is not None:+ logger.debug(f"Stigg: resuming {endpoint} from cursor {cursor}")++ while True:+ items, next_cursor = _fetch_page(session, config.path, cursor, PAGE_SIZE, logger)+ if items:+ yield items++ # A null `pagination.next` (or an empty page) means we've reached the end of the list.+ if not next_cursor or not items:+ break++ cursor = next_cursor+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(StiggResumeConfig(cursor=cursor))+++def stigg_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[StiggResumeConfig],+) -> SourceResponse:+ config = STIGG_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{STIGG_BASE_URL}{path}", params={"limit": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Stigg: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Stigg returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Stigg API key. Use a server API key from Settings → Integrations → API keys."+ return False, message or "Could not validate Stigg API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg.pynew file mode 100644index 000000000000..84ab555bfe00--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg.py@@ -0,0 +1,266 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.stigg import stigg+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.settings import ENDPOINTS, STIGG_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.stigg import (+ PAGE_SIZE,+ StiggResumeConfig,+ StiggRetryableError,+ check_access,+ get_rows,+ stigg_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = stigg._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: StiggResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[StiggResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> StiggResumeConfig | None:+ return self._state++ def save_state(self, data: StiggResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[str | None, tuple[list[dict], str | None]],+ endpoint: str = "customers",+ ) -> list[dict]:+ def fake_fetch(+ session: Any, path: str, cursor: str | None, limit: int, logger: Any+ ) -> tuple[list[dict], str | None]:+ return pages[cursor]++ monkeypatch.setattr(stigg, "_fetch_page", fake_fetch)+ monkeypatch.setattr(stigg, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="stigg-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_null_next_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([{"id": "a"}, {"id": "b"}], None)})+ assert rows == [{"id": "a"}, {"id": "b"}]+ # pagination.next is null, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_next_cursor_until_null(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[str | None, tuple[list[dict], str | None]] = {+ None: ([{"id": "1"}, {"id": "2"}], "cursor-page-2"),+ "cursor-page-2": ([{"id": "3"}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": "1"}, {"id": "2"}, {"id": "3"}]+ # State is saved after the first page (cursor advances to pagination.next), then we stop.+ assert [s.cursor for s in manager.saved] == ["cursor-page-2"]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(StiggResumeConfig(cursor="cur-99"))+ # The initial (cursor=None) page must never be fetched on resume.+ rows = self._collect(manager, monkeypatch, {"cur-99": ([{"id": "5"}], None)})+ assert rows == [{"id": "5"}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], None)})+ assert rows == []+ assert manager.saved == []++ def test_empty_page_with_cursor_stops_without_saving(self, monkeypatch: Any) -> None:+ # Defensive: an empty page terminates even if the API still returns a next cursor,+ # so a buggy upstream cursor can't loop us forever.+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], "phantom-cursor")})+ assert rows == []+ assert manager.saved == []+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"data": [], "pagination": {"next": None}}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @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 = self._session_returning(status)+ with pytest.raises(StiggRetryableError):+ _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())++ def test_success_returns_items_and_next_cursor(self) -> None:+ body = {"data": [{"id": "1"}], "pagination": {"next": "abc", "prev": None}}+ session = self._session_returning(200, body)+ items, next_cursor = _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())+ assert items == [{"id": "1"}]+ assert next_cursor == "abc"++ def test_null_next_cursor_maps_to_none(self) -> None:+ body = {"data": [{"id": "1"}], "pagination": {"next": None, "prev": "xyz"}}+ session = self._session_returning(200, body)+ _, next_cursor = _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())+ assert next_cursor is None++ def test_missing_pagination_maps_to_none(self) -> None:+ session = self._session_returning(200, {"data": [{"id": "1"}]})+ _, next_cursor = _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())+ assert next_cursor is None++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": "1"}])+ with pytest.raises(StiggRetryableError):+ _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())++ def test_missing_data_key_is_retryable(self) -> None:+ session = self._session_returning(200, {"pagination": {"next": None}})+ with pytest.raises(StiggRetryableError):+ _fetch_page_unwrapped(session, "/customers", None, PAGE_SIZE, MagicMock())++ def test_first_page_uses_limit_without_cursor(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/plans", None, PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE}++ def test_subsequent_page_sends_after_cursor(self) -> None:+ session = self._session_returning(200)+ _fetch_page_unwrapped(session, "/plans", "cur-42", PAGE_SIZE, MagicMock())+ _, kwargs = session.get.call_args+ assert kwargs["params"] == {"limit": PAGE_SIZE, "after": "cur-42"}+++class TestCheckAccess:+ @staticmethod+ def _session(response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "Stigg returned HTTP 500"),+ ]+ )+ @patch(f"{stigg.__name__}.make_tracked_session")+ def test_status_mapping(+ self,+ _name: str,+ status: int,+ ok: bool,+ expected_status: int,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ mock_session.return_value = self._session(response)+ assert check_access("stigg-key") == (expected_status, expected_message)++ @patch(f"{stigg.__name__}.make_tracked_session")+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:+ mock_session.return_value = self._session(requests.ConnectionError("boom"))+ status, message = check_access("stigg-key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ (+ "unauthorized",+ 401,+ False,+ "Invalid Stigg API key. Use a server API key from Settings → Integrations → API keys.",+ ),+ (+ "forbidden",+ 403,+ False,+ "Invalid Stigg API key. Use a server API key from Settings → Integrations → API keys.",+ ),+ ("server_error", 500, False, "Stigg returned HTTP 500"),+ ]+ )+ @patch(f"{stigg.__name__}.make_tracked_session")+ def test_validate_credentials(+ self,+ _name: str,+ status: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: MagicMock,+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ mock_session.return_value = self._session(response)+ assert validate_credentials("stigg-key") == (expected_valid, expected_message)+++class TestStiggSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = stigg_source(+ api_key="stigg-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == STIGG_ENDPOINTS[endpoint].primary_keys+ # createdAt is required on every list DTO and never changes, so it's a stable partition key.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]++ @parameterized.expand([("plans",), ("addons",)])+ def test_versioned_packages_use_composite_primary_key(self, endpoint: str) -> None:+ # Plans and addons share their `id` slug across versions; dropping `versionNumber` from+ # the key would seed duplicate rows and multi-match every later merge.+ assert STIGG_ENDPOINTS[endpoint].primary_keys == ["id", "versionNumber"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg_source.pynew file mode 100644index 000000000000..c7c71e21f161--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stigg/tests/test_stigg_source.py@@ -0,0 +1,131 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import StiggSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.source import StiggSource+from products.warehouse_sources.backend.temporal.data_imports.sources.stigg.stigg import StiggResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestStiggSource:+ def setup_method(self) -> None:+ self.source = StiggSource()+ self.team_id = 123+ self.config = StiggSourceConfig(api_key="stigg-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.STIGG++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Stigg"+ assert config.label == "Stigg"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/stigg"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["subscriptions"])+ assert len(schemas) == 1+ assert schemas[0].name == "subscriptions"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.stigg.io/api/v1/customers?limit=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.stigg.io/api/v1/plans?limit=100"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.stigg.io/api/v1/customers",+ ),+ (+ "rate_limited",+ "429 Client Error: Too Many Requests for url: https://api.stigg.io/api/v1/plans",+ ),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.stigg.source.validate_credentials")+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:+ # The status-to-message mapping lives in stigg.validate_credentials; here we only assert the+ # source probes with the configured key and returns the delegate's verdict unchanged.+ mock_validate.return_value = (False, "Invalid Stigg API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with("stigg-key")+ assert result == (False, "Invalid Stigg API key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is StiggResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.stigg.source.stigg_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "customers"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "stigg-key"+ assert kwargs["endpoint"] == "customers"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Stigg schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)