Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement lago import source (#65625)

Tom Owers7eb4a5a92a46
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index c907051c0891..ecfeae679dae 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -124,6 +124,7 @@ the row lists both.
| jira | HTTP | requests | ✅ |
| jotform | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
+| lago | HTTP | requests | ✅ |
| launchdarkly | HTTP | requests | ✅ |
| kustomer | HTTP | requests | ✅ |
| lattice | HTTP | requests | ✅ |
@@ -466,7 +467,6 @@ doesn't conflict with concurrent PRs.
- klaus
- knock
- kyve
-- lago
- leadfeeder
- leexi
- lemlist
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index c86a531a2c9c..89db4ac5b1ce 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1685,7 +1685,8 @@ class KustomerSourceConfig(config.Config):
@config.config
class LagoSourceConfig(config.Config):
- pass
+ api_key: str
+ api_url: str | None = None
@config.config
diff --git a/posthog/temporal/data_imports/sources/lago/canonical_descriptions.py b/posthog/temporal/data_imports/sources/lago/canonical_descriptions.py
new file mode 100644
index 000000000000..d6ce992cf15d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lago/canonical_descriptions.py
@@ -0,0 +1,131 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the public Lago API reference (https://docs.getlago.com/api-reference). Partial
+# coverage is fine — any endpoint, column, or table-level description not listed here falls back to
+# LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "customers": {
+ "description": "A customer billed through Lago, including billing configuration and address.",
+ "docs_url": "https://docs.getlago.com/api-reference/customers/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the customer.",
+ "external_id": "The customer identifier from your own system.",
+ "name": "Display name of the customer.",
+ "email": "Primary billing email address of the customer.",
+ "currency": "Default billing currency for the customer (ISO 4217).",
+ "country": "Two-letter ISO country code for the customer's billing address.",
+ "created_at": "Timestamp at which the customer was created in Lago.",
+ },
+ },
+ "subscriptions": {
+ "description": "A customer's subscription to a plan, tracking its lifecycle and billing period.",
+ "docs_url": "https://docs.getlago.com/api-reference/subscriptions/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the subscription.",
+ "external_id": "The subscription identifier from your own system.",
+ "external_customer_id": "Identifier of the subscribed customer in your system.",
+ "plan_code": "Code of the plan the customer is subscribed to.",
+ "status": "Lifecycle status of the subscription (e.g. active, pending, terminated, canceled).",
+ "started_at": "Timestamp at which the subscription started.",
+ "created_at": "Timestamp at which the subscription was created in Lago.",
+ },
+ },
+ "invoices": {
+ "description": "An invoice issued to a customer for a billing period, with totals and status.",
+ "docs_url": "https://docs.getlago.com/api-reference/invoices/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the invoice.",
+ "number": "Human-readable invoice number.",
+ "issuing_date": "Date the invoice was issued.",
+ "payment_status": "Payment status of the invoice (e.g. pending, succeeded, failed).",
+ "status": "Finalization status of the invoice (e.g. draft, finalized, voided).",
+ "currency": "Currency of the invoice (ISO 4217).",
+ "total_amount_cents": "Total amount due on the invoice, in the currency's smallest unit.",
+ "created_at": "Timestamp at which the invoice was created in Lago.",
+ },
+ },
+ "plans": {
+ "description": "A pricing plan defining how customers subscribed to it are charged.",
+ "docs_url": "https://docs.getlago.com/api-reference/plans/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the plan.",
+ "code": "Unique code used to reference the plan.",
+ "name": "Display name of the plan.",
+ "interval": "Billing interval of the plan (e.g. weekly, monthly, quarterly, yearly).",
+ "amount_cents": "Recurring plan amount, in the currency's smallest unit.",
+ "amount_currency": "Currency of the plan amount (ISO 4217).",
+ "created_at": "Timestamp at which the plan was created in Lago.",
+ },
+ },
+ "billable_metrics": {
+ "description": "A metric definition describing how usage events are aggregated for billing.",
+ "docs_url": "https://docs.getlago.com/api-reference/billable-metrics/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the billable metric.",
+ "code": "Unique code used to reference the billable metric.",
+ "name": "Display name of the billable metric.",
+ "aggregation_type": "How matching events are aggregated (e.g. count_agg, sum_agg, max_agg).",
+ "field_name": "Event property aggregated when the aggregation type requires one.",
+ "created_at": "Timestamp at which the billable metric was created in Lago.",
+ },
+ },
+ "coupons": {
+ "description": "A discount that can be applied to a customer's invoices.",
+ "docs_url": "https://docs.getlago.com/api-reference/coupons/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the coupon.",
+ "code": "Unique code used to reference the coupon.",
+ "name": "Display name of the coupon.",
+ "coupon_type": "Whether the coupon applies a fixed amount or a percentage discount.",
+ "created_at": "Timestamp at which the coupon was created in Lago.",
+ },
+ },
+ "applied_coupons": {
+ "description": "A coupon applied to a specific customer, tracking the remaining discount.",
+ "docs_url": "https://docs.getlago.com/api-reference/applied-coupons/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the applied coupon.",
+ "lago_coupon_id": "Identifier of the coupon that was applied.",
+ "external_customer_id": "Identifier of the customer the coupon was applied to, in your system.",
+ "status": "Whether the applied coupon is still active or has been fully consumed.",
+ "created_at": "Timestamp at which the coupon was applied.",
+ },
+ },
+ "add_ons": {
+ "description": "A one-off charge that can be added to a customer's invoice.",
+ "docs_url": "https://docs.getlago.com/api-reference/add-ons/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the add-on.",
+ "code": "Unique code used to reference the add-on.",
+ "name": "Display name of the add-on.",
+ "amount_cents": "Add-on amount, in the currency's smallest unit.",
+ "amount_currency": "Currency of the add-on amount (ISO 4217).",
+ "created_at": "Timestamp at which the add-on was created in Lago.",
+ },
+ },
+ "credit_notes": {
+ "description": "A credit note issued against an invoice, refunding or crediting a customer.",
+ "docs_url": "https://docs.getlago.com/api-reference/credit-notes/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the credit note.",
+ "number": "Human-readable credit note number.",
+ "lago_invoice_id": "Identifier of the invoice the credit note was issued against.",
+ "credit_status": "Status of the credited portion of the credit note.",
+ "refund_status": "Status of the refunded portion of the credit note.",
+ "total_amount_cents": "Total value of the credit note, in the currency's smallest unit.",
+ "created_at": "Timestamp at which the credit note was created in Lago.",
+ },
+ },
+ "fees": {
+ "description": "An individual charge line generated from usage, a plan, or an add-on.",
+ "docs_url": "https://docs.getlago.com/api-reference/fees/object",
+ "columns": {
+ "lago_id": "Lago's globally-unique identifier for the fee.",
+ "lago_invoice_id": "Identifier of the invoice the fee belongs to, if any.",
+ "fee_type": "Type of fee (e.g. charge, subscription, add_on, credit).",
+ "amount_cents": "Fee amount, in the currency's smallest unit.",
+ "amount_currency": "Currency of the fee amount (ISO 4217).",
+ "created_at": "Timestamp at which the fee was created in Lago.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/lago/lago.py b/posthog/temporal/data_imports/sources/lago/lago.py
new file mode 100644
index 000000000000..55fce34d4b7a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lago/lago.py
@@ -0,0 +1,266 @@
+"""Lago transport layer.
+
+Lago is an open-source usage-based billing platform offered both as Lago Cloud
+(``https://api.getlago.com``) and self-hosted (a customer-supplied host), so the API base URL
+must be configurable. Auth is a single Bearer API key. List endpoints are page-number paginated
+(``page`` / ``per_page``) and wrap their records under a resource key alongside a ``meta`` object
+that carries ``next_page``.
+
+Every stream is full-refresh. Lago's REST API exposes no universal server-side ``created_at`` /
+``updated_at`` cursor across resources — only a handful of endpoints offer ad-hoc date filters
+(e.g. ``issuing_date_from`` on invoices) that filter on a business date rather than a monotonic
+record-creation timestamp, so they are unsafe to treat as an incremental cursor. Incremental sync
+can be layered on later for a specific endpoint once its server-side filter is verified against the
+live API.
+"""
+
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.lago.settings import LAGO_ENDPOINTS, LagoEndpointConfig
+
+DEFAULT_API_HOST = "https://api.getlago.com"
+API_VERSION_PATH = "/api/v1"
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+
+HOST_NOT_ALLOWED_ERROR = "Lago API URL is not allowed"
+
+
+class LagoRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class LagoHostNotAllowedError(Exception):
+ pass
+
+
+class LagoResumeConfig:
+ # The next page to fetch on resume. Persisted after each page is yielded, so a crash before
+ # this write leaves the previous value in place and the last page is re-yielded (Lago merges
+ # dedupe on `lago_id`).
+ next_page: int
+
+
+def normalize_base_url(api_url: Optional[str]) -> str:
+ """Turn whatever the user typed into a ``<scheme>://<host>/api/v1`` base URL.
+
+ Blank → Lago Cloud. Accepts bare hosts (``billing.example.com``), full URLs with or without a
+ scheme, and values that already include the ``/api/v1`` suffix.
+ """
+ raw = (api_url or "").strip()
+ if not raw:
+ raw = DEFAULT_API_HOST
+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):
+ raw = f"https://{raw}"
+ raw = raw.rstrip("/")
+ # Drop a trailing version segment the user may have pasted in, then re-add the version we target.
+ raw = re.sub(r"/api/v\d+$", "", raw)
+ return f"{raw}{API_VERSION_PATH}"
+
+
+def _host_of(base_url: str) -> str:
+ return (urlparse(base_url).hostname or "").lower()
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def validate_credentials(
+ api_url: Optional[str], api_key: str, schema_name: Optional[str] = None, team_id: Optional[int] = None
+) -> tuple[bool, str | None]:
+ """Probe a cheap list endpoint to confirm the Bearer token is genuine.
+
+ At source-create (``schema_name is None``) a 403 is accepted: the token is valid but may lack
+ permission for this particular probe. A scoped probe (``schema_name`` set) treats 403 as a hard
+ failure.
+ """
+ base_url = normalize_base_url(api_url)
+ host = _host_of(base_url)
+
+ if not host:
+ return False, "Invalid Lago API URL"
+
+ # The host is fully customer-controlled for self-hosted deployments, so block hosts that resolve
+ # to private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(host, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ url = f"{base_url}/customers?{urlencode({'per_page': 1, 'page': 1})}"
+ try:
+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating
+ # the host check above (SSRF).
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10, allow_redirects=False)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.is_redirect or response.is_permanent_redirect:
+ return False, HOST_NOT_ALLOWED_ERROR
+
+ if response.status_code == 200:
+ return True, None
+
+ if response.status_code == 401:
+ return False, "Invalid Lago API key"
+
+ if response.status_code == 403:
+ if schema_name is None:
+ # Valid token, missing permission for this probe — let source creation through.
+ return True, None
+ return False, "Lago API key lacks the required permissions for this endpoint"
+
+ try:
+ body = response.json()
+ return False, body.get("error", response.text)
+ except Exception:
+ return False, response.text
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """Honor a whole-second ``Retry-After`` on 429. HTTP-date forms are ignored."""
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ """Use a server-provided Retry-After when present, else exponential backoff."""
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, LagoRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def get_rows(
+ api_url: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LagoResumeConfig],
+ team_id: int,
+) -> Iterator[list[dict[str, Any]]]:
+ config: LagoEndpointConfig = LAGO_ENDPOINTS[endpoint]
+ base_url = normalize_base_url(api_url)
+ host = _host_of(base_url)
+
+ # Re-check at run time (not just at source-create) in case the URL was edited or now resolves
+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(host, team_id)
+ if not host_ok:
+ raise LagoHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ headers = _get_headers(api_key)
+ request_url = f"{base_url}{config.path}"
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume_config.next_page if resume_config is not None else 1
+ if resume_config is not None:
+ logger.debug(f"Lago: resuming {endpoint} from page {page}")
+
+ @retry(
+ retry=retry_if_exception_type((LagoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_number: int) -> requests.Response:
+ query = urlencode({"page": page_number, "per_page": config.page_size})
+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address,
+ # bypassing the host validation done before the request (SSRF).
+ response = make_tracked_session().get(
+ f"{request_url}?{query}", headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise LagoRetryableError(
+ f"Lago API error (retryable): status={response.status_code}, url={request_url}",
+ retry_after=retry_after,
+ )
+
+ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than
+ # silently parsing the redirect body as data.
+ if response.is_redirect or response.is_permanent_redirect:
+ raise LagoHostNotAllowedError(
+ f"Lago API returned an unexpected redirect (status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(f"Lago API error: status={response.status_code}, body={response.text}, url={request_url}")
+ response.raise_for_status()
+
+ return response
+
+ while True:
+ response = fetch_page(page)
+ body = response.json()
+ rows = body.get(config.data_key) or []
+ if not isinstance(rows, list) or not rows:
+ break
+
+ yield rows
+
+ next_page = (body.get("meta") or {}).get("next_page")
+ if not next_page:
+ break
+ page = int(next_page)
+
+ # Checkpoint AFTER yielding the page: a crash before this write re-yields the page on resume
+ # (dedupes on the primary key), while a crash after it resumes at the next page.
+ resumable_source_manager.save_state(LagoResumeConfig(next_page=page))
+
+
+def lago_source(
+ api_url: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LagoResumeConfig],
+ team_id: int,
+) -> SourceResponse:
+ config = LAGO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_url=api_url,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ ),
+ primary_keys=[config.primary_key],
+ # Full-refresh replace: Lago exposes no `sort` param and no incremental cursor, so there is
+ # no watermark to checkpoint. The default ascending mode is harmless here.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/lago/settings.py b/posthog/temporal/data_imports/sources/lago/settings.py
new file mode 100644
index 000000000000..650830d0e632
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lago/settings.py
@@ -0,0 +1,53 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+# Number of records to request per page. Lago caps `per_page` at 100.
+DEFAULT_PAGE_SIZE = 100
+
+
+@dataclass
+class LagoEndpointConfig:
+ name: str
+ # Path appended to the API base (which already ends in `/api/v1`).
+ path: str
+ # Key under which the list of records lives in the JSON response body
+ # (e.g. `{"customers": [...], "meta": {...}}`).
+ data_key: str
+ # Lago objects carry both an external (customer-supplied) id and `lago_id`, Lago's own
+ # globally-unique UUID. `lago_id` is the stable primary key across every resource.
+ primary_key: str = "lago_id"
+ # Stable, immutable field to partition by. `created_at` is present on every list resource
+ # and never changes. Never partition on a mutable field.
+ partition_key: Optional[str] = "created_at"
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Lago's REST API exposes no universal server-side `created_at`/`updated_at` cursor, so every
+ # stream is full-refresh only. Left empty deliberately — see the module docstring in lago.py.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# Top-level list endpoints that return a full collection without requiring a parent resource
+# (e.g. a customer or subscription id) as a filter. Per-customer resources such as `wallets` and
+# `wallet_transactions`, and the write-oriented `events` endpoint, are intentionally excluded:
+# they require a fan-out we cannot verify against the live API without credentials.
+LAGO_ENDPOINTS: dict[str, LagoEndpointConfig] = {
+ "add_ons": LagoEndpointConfig(name="add_ons", path="/add_ons", data_key="add_ons"),
+ "applied_coupons": LagoEndpointConfig(name="applied_coupons", path="/applied_coupons", data_key="applied_coupons"),
+ "billable_metrics": LagoEndpointConfig(
+ name="billable_metrics", path="/billable_metrics", data_key="billable_metrics"
+ ),
+ "coupons": LagoEndpointConfig(name="coupons", path="/coupons", data_key="coupons"),
+ "credit_notes": LagoEndpointConfig(name="credit_notes", path="/credit_notes", data_key="credit_notes"),
+ "customers": LagoEndpointConfig(name="customers", path="/customers", data_key="customers"),
+ "fees": LagoEndpointConfig(name="fees", path="/fees", data_key="fees"),
+ "invoices": LagoEndpointConfig(name="invoices", path="/invoices", data_key="invoices"),
+ "plans": LagoEndpointConfig(name="plans", path="/plans", data_key="plans"),
+ "subscriptions": LagoEndpointConfig(name="subscriptions", path="/subscriptions", data_key="subscriptions"),
+}
+
+ENDPOINTS = tuple(LAGO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in LAGO_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/lago/source.py b/posthog/temporal/data_imports/sources/lago/source.py
index b140fc16f6ba..fa82c5902e46 100644
--- a/posthog/temporal/data_imports/sources/lago/source.py
+++ b/posthog/temporal/data_imports/sources/lago/source.py
@@ -1,31 +1,136 @@
-from typing import cast
+from typing import Optional, cast
from 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 CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import LagoSourceConfig
+from posthog.temporal.data_imports.sources.lago.lago import (
+ HOST_NOT_ALLOWED_ERROR,
+ LagoResumeConfig,
+ lago_source,
+ validate_credentials as validate_lago_credentials,
+)
+from posthog.temporal.data_imports.sources.lago.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LagoSource(SimpleSource[LagoSourceConfig]):
+class LagoSource(ResumableSource[LagoSourceConfig, LagoResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LAGO
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `api_url` is where the stored API key is sent; retargeting it must re-require the key.
+ return ["api_url"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Lago API key. Please generate a new key and reconnect.",
+ "403 Client Error": "Your Lago API key lacks the required permissions. Please check the key and try again.",
+ HOST_NOT_ALLOWED_ERROR: "The Lago API URL is not allowed. Please use a publicly reachable host.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.lago.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: LagoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ 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: LagoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_lago_credentials(config.api_url, config.api_key, schema_name, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LagoResumeConfig]:
+ return ResumableSourceManager[LagoResumeConfig](inputs, LagoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LagoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LagoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return lago_source(
+ api_url=config.api_url,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.LAGO,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Lago",
- iconPath="/static/services/lago.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Lago API key to pull your billing data into the PostHog Data warehouse.
+
+You can create an API key in the Lago dashboard under **Developers > API keys**.
+
+Self-hosted Lago users should set the API URL to their own Lago host (for example `https://billing.example.com`). Leave it blank to use Lago Cloud.""",
+ iconPath="/static/services/lago.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/lago",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="api_url",
+ label="API URL (self-hosted only)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://api.getlago.com",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/posthog/temporal/data_imports/sources/lago/tests/test_lago.py b/posthog/temporal/data_imports/sources/lago/tests/test_lago.py
new file mode 100644
index 000000000000..81b3633cc131
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lago/tests/test_lago.py
@@ -0,0 +1,251 @@
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.lago import lago as lago_module
+from posthog.temporal.data_imports.sources.lago.lago import (
+ LagoHostNotAllowedError,
+ LagoResumeConfig,
+ get_rows,
+ lago_source,
+ normalize_base_url,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.lago.settings import LAGO_ENDPOINTS
+
+
+def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (301, 302, 303, 307, 308)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ response.headers = {}
+ return response
+
+
+def _page(rows: list[dict[str, Any]], next_page: Optional[int]) -> mock.MagicMock:
+ return _response(json_data={"customers": rows, "meta": {"next_page": next_page}})
+
+
+class TestNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ (None, "https://api.getlago.com/api/v1"),
+ ("", "https://api.getlago.com/api/v1"),
+ (" ", "https://api.getlago.com/api/v1"),
+ ("https://api.getlago.com", "https://api.getlago.com/api/v1"),
+ ("https://api.getlago.com/", "https://api.getlago.com/api/v1"),
+ ("https://api.getlago.com/api/v1", "https://api.getlago.com/api/v1"),
+ ("billing.example.com", "https://billing.example.com/api/v1"),
+ ("http://billing.example.com/", "http://billing.example.com/api/v1"),
+ ("https://billing.example.com/api/v2", "https://billing.example.com/api/v1"),
+ ],
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize_base_url(raw) == expected
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(lago_module, "make_tracked_session", return_value=session)
+
+ def test_success(self):
+ with self._patch_session(_response(status_code=200)):
+ assert validate_credentials(None, "key") == (True, None)
+
+ def test_invalid_key(self):
+ with self._patch_session(_response(status_code=401)):
+ valid, msg = validate_credentials(None, "key")
+ assert valid is False
+ assert msg == "Invalid Lago API key"
+
+ def test_403_at_source_create_is_accepted(self):
+ with self._patch_session(_response(status_code=403)):
+ assert validate_credentials(None, "key", schema_name=None) == (True, None)
+
+ def test_403_for_scoped_probe_fails(self):
+ with self._patch_session(_response(status_code=403)):
+ valid, msg = validate_credentials(None, "key", schema_name="invoices")
+ assert valid is False
+ assert msg is not None
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials(None, "key")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ with self._patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials(None, "key")
+ assert valid is False
+ assert msg == lago_module.HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(lago_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("http://10.0.0.1", "key", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ def test_probe_hits_configured_host(self):
+ with self._patch_session(_response(status_code=200)) as patched:
+ validate_credentials("https://billing.example.com", "key")
+ url = patched.return_value.get.call_args.args[0]
+ assert url.startswith("https://billing.example.com/api/v1/customers")
+
+
+class TestLagoSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(LAGO_ENDPOINTS.keys()))
+ def test_response_shape(self, endpoint):
+ response = lago_source(
+ api_url=None,
+ api_key="key",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["lago_id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+
+
+class TestGetRows:
+ def _run(self, manager, responses, team_id=1, api_url=None):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with mock.patch.object(lago_module, "make_tracked_session", return_value=session):
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ api_url=api_url,
+ api_key="key",
+ endpoint="customers",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=team_id,
+ ):
+ rows.extend(batch)
+ return rows, session
+
+ def test_paginates_via_meta_next_page(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _page([{"lago_id": "1"}, {"lago_id": "2"}], next_page=2)
+ page2 = _page([{"lago_id": "3"}], next_page=None)
+ rows, session = self._run(manager, [page1, page2])
+
+ assert [r["lago_id"] for r in rows] == ["1", "2", "3"]
+ # First request page=1, second request page=2 (from meta.next_page).
+ first_qs = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)
+ second_qs = parse_qs(urlparse(session.get.call_args_list[1].args[0]).query)
+ assert first_qs["page"] == ["1"]
+ assert second_qs["page"] == ["2"]
+
+ def test_saves_next_page_after_yielding(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _page([{"lago_id": "1"}], next_page=2)
+ page2 = _page([{"lago_id": "2"}], next_page=None)
+ self._run(manager, [page1, page2])
+
+ # State is saved once (after page 1, pointing at page 2); the last page has no next_page.
+ assert manager.save_state.call_count == 1
+ saved = manager.save_state.call_args.args[0]
+ assert isinstance(saved, LagoResumeConfig)
+ assert saved.next_page == 2
+
+ def test_resumes_from_saved_state(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = LagoResumeConfig(next_page=3)
+ rows, session = self._run(manager, [_page([{"lago_id": "9"}], next_page=None)])
+
+ first_qs = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)
+ assert first_qs["page"] == ["3"]
+ assert [r["lago_id"] for r in rows] == ["9"]
+
+ def test_empty_page_terminates(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ rows, session = self._run(manager, [_page([], next_page=2)])
+ assert rows == []
+ assert session.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ def test_does_not_follow_redirects(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ with pytest.raises(LagoHostNotAllowedError):
+ self._run(manager, [_response(status_code=302)])
+
+ def test_passes_allow_redirects_false(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ _rows, session = self._run(manager, [_page([{"lago_id": "1"}], next_page=None)])
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_raises_when_host_not_allowed(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ with mock.patch.object(lago_module, "_is_host_safe", return_value=(False, "internal address")):
+ with pytest.raises(LagoHostNotAllowedError):
+ self._run(manager, [_page([{"lago_id": "1"}], next_page=None)])
+
+ @pytest.mark.parametrize("status_code", [429, 503])
+ def test_retries_retryable_status_then_succeeds(self, status_code):
+ # End-to-end: a retryable status raises LagoRetryableError, tenacity retries, and the
+ # subsequent 200 yields rows. Guards against accidentally dropping the retry predicate.
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ responses = [_response(status_code=status_code), _page([{"lago_id": "r1"}], next_page=None)]
+ with mock.patch.object(lago_module, "_retry_wait", return_value=0):
+ rows, session = self._run(manager, responses)
+ assert [r["lago_id"] for r in rows] == ["r1"]
+ assert session.get.call_count == 2
+
+
+class TestRetryAfter:
+ @pytest.mark.parametrize(
+ "header, expected",
+ [
+ ({"Retry-After": "5"}, 5.0),
+ ({"Retry-After": " 9 "}, 9.0),
+ ({"Retry-After": "100000"}, 60.0),
+ ({"Retry-After": "Wed, 21 Oct 2025 07:28:00 GMT"}, None),
+ ({}, None),
+ ],
+ )
+ def test_parse_retry_after(self, header, expected):
+ from posthog.temporal.data_imports.sources.lago.lago import _parse_retry_after
+
+ response = mock.MagicMock()
+ response.headers = header
+ assert _parse_retry_after(response) == expected
+
+ def test_retry_wait_prefers_retry_after(self):
+ from posthog.temporal.data_imports.sources.lago.lago import LagoRetryableError, _retry_wait
+
+ state = mock.MagicMock()
+ state.outcome.exception.return_value = LagoRetryableError("rate limited", retry_after=7.0)
+ assert _retry_wait(state) == 7.0
diff --git a/posthog/temporal/data_imports/sources/lago/tests/test_lago_source.py b/posthog/temporal/data_imports/sources/lago/tests/test_lago_source.py
new file mode 100644
index 000000000000..18a61e23f9dd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/lago/tests/test_lago_source.py
@@ -0,0 +1,118 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import LagoSourceConfig
+from posthog.temporal.data_imports.sources.lago.lago import LagoResumeConfig
+from posthog.temporal.data_imports.sources.lago.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.lago.source import LagoSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestLagoSource:
+ def setup_method(self):
+ self.source = LagoSource()
+ self.team_id = 123
+ self.config = LagoSourceConfig(api_key="lago_key", api_url=None)
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.LAGO
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Lago"
+ assert config.label == "Lago"
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/lago.png"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["api_key", "api_url"]
+
+ api_key_field, api_url_field = config.fields
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ assert isinstance(api_url_field, SourceFieldInputConfig)
+ assert api_url_field.type == SourceFieldInputConfigType.TEXT
+ assert api_url_field.secret is False
+ assert api_url_field.required is False
+
+ def test_connection_host_fields_force_secret_reentry(self):
+ # The API key is sent to api_url, so retargeting it must re-require the key.
+ assert self.source.connection_host_fields == ["api_url"]
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_schemas_are_full_refresh(self):
+ # Lago exposes no universal server-side cursor, so every stream ships full-refresh only.
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ 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):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "invoices"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected",
+ [
+ ((True, None), (True, None)),
+ ((False, "Invalid Lago API key"), (False, "Invalid Lago API key")),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.lago.source.validate_lago_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="invoices")
+
+ assert result == expected
+ mock_validate.assert_called_once_with(self.config.api_url, self.config.api_key, "invoices", self.team_id)
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is LagoResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.lago.source.lago_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_lago_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.team_id = 42
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_lago_source.assert_called_once()
+ kwargs = mock_lago_source.call_args.kwargs
+ assert kwargs["api_url"] == self.config.api_url
+ assert kwargs["api_key"] == "lago_key"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+
+ def test_canonical_descriptions_cover_core_tables(self):
+ descriptions = self.source.get_canonical_descriptions()
+ # Curated docs only describe endpoints we actually expose.
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "customers" in descriptions
+ assert "invoices" in descriptions