: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(lago): add events, payments, charges and wallet tables (#113905)
Tom Owerse8fba762b851
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 4fc6157f2b3a..a10deb327116 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -740,8 +740,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/kustomer/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lacework/lacework.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lacework/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/lago/lago.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/lago/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/lambda_labs.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lambda_labs/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/langfuse/langfuse.pydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 2e2f77b2a84f..44f8c774f47e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -4944,10 +4944,10 @@ Today (10): `add_ons`, `applied_coupons`, `billable_metrics`, `coupons`, `creditDiffed against: <https://raw.githubusercontent.com/getlago/lago-openapi/main/openapi.yaml>-- [ ] `GET /wallets and GET /wallet_transactions` — prepaid credit balances and top-ups; an entire revenue mechanism is missing (high)-- [ ] `GET /payments` — actual cash collection against the invoices already synced (high)-- [ ] `GET /plans/{code}/charges (and /charges/{charge_code}/filters)` — lookup joining plans to billable metrics; without it, fees cannot be traced to pricing rules (high)-- [ ] `GET /events` — the raw usage events that every fee is derived from (high)+- [x] `GET /wallets and GET /wallet_transactions` — prepaid credit balances and top-ups; an entire revenue mechanism is missing (high)+- [x] `GET /payments` — actual cash collection against the invoices already synced (high)+- [x] `GET /plans/{code}/charges (and /charges/{charge_code}/filters)` — lookup joining plans to billable metrics; without it, fees cannot be traced to pricing rules (high)+- [x] `GET /events` — the raw usage events that every fee is derived from (high)- [ ] `GET /taxes` — lookup resolving tax codes applied on invoices, fees and customers (medium)- [ ] `GET /payment_requests and GET /payment_receipts` — dunning requests and receipts for collections reporting (medium)- [ ] `GET /billing_entities` — lookup for the billing entity that owns each invoice in multi-entity setups (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/canonical_descriptions.pyindex 45e0edf121cc..edd89af98aa8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/canonical_descriptions.py@@ -130,4 +130,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Timestamp at which the fee was created in Lago.",},},+ "payments": {+ "description": "A payment collected against one or more invoices or payment requests.",+ "docs_url": "https://docs.getlago.com/api-reference/payments/payment-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the payment.",+ "external_customer_id": "Identifier of the paying customer in your system.",+ "invoice_ids": "Identifiers of the invoices the payment covers.",+ "amount_cents": "Payment amount, in the currency's smallest unit.",+ "amount_currency": "Currency of the payment amount (ISO 4217).",+ "payment_status": "Status of the payment (e.g. pending, succeeded, failed).",+ "type": "Whether the payment was recorded manually or collected by a payment provider.",+ "created_at": "Timestamp at which the payment was created in Lago.",+ },+ },+ "events": {+ "description": "A raw usage event sent to Lago, from which usage-based fees are computed.",+ "docs_url": "https://docs.getlago.com/api-reference/events/event-object",+ "columns": {+ "transaction_id": "Idempotency identifier of the event, supplied by the sender.",+ "external_subscription_id": "Identifier, in your system, of the subscription the event is billed to.",+ "code": "Code of the billable metric the event feeds.",+ "timestamp": "Time at which the usage occurred, as supplied by the sender.",+ "properties": "Custom properties sent with the event, used by billable metric aggregations.",+ "created_at": "Timestamp at which Lago received the event.",+ },+ },+ "charges": {+ "description": "A usage-based charge on a plan, linking the plan to a billable metric and its pricing model.",+ "docs_url": "https://docs.getlago.com/api-reference/plans/charges/object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the charge.",+ "lago_plan_id": "Identifier of the plan the charge belongs to.",+ "plan_code": "Code of the plan the charge belongs to.",+ "lago_billable_metric_id": "Identifier of the billable metric the charge prices.",+ "billable_metric_code": "Code of the billable metric the charge prices.",+ "charge_model": "Pricing model of the charge (e.g. standard, graduated, package, percentage).",+ "properties": "Pricing configuration of the charge model.",+ "filters": "Filter-specific pricing applied on top of the default charge properties.",+ "created_at": "Timestamp at which the charge was created in Lago.",+ },+ },+ "wallets": {+ "description": "A customer's prepaid credit wallet and its current balance.",+ "docs_url": "https://docs.getlago.com/api-reference/wallets/wallet-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the wallet.",+ "external_customer_id": "Identifier of the wallet's customer in your system.",+ "status": "Status of the wallet (active or terminated).",+ "currency": "Currency of the wallet (ISO 4217).",+ "rate_amount": "Value of one credit in the wallet currency.",+ "credits_balance": "Number of credits left in the wallet.",+ "balance_cents": "Value of the remaining credits, in the currency's smallest unit.",+ "consumed_credits": "Number of credits consumed so far.",+ "created_at": "Timestamp at which the wallet was created in Lago.",+ },+ },+ "wallet_transactions": {+ "description": "A credit top-up, grant, or consumption recorded on a prepaid wallet.",+ "docs_url": "https://docs.getlago.com/api-reference/wallets/wallet-transaction-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the wallet transaction.",+ "lago_wallet_id": "Identifier of the wallet the transaction belongs to.",+ "external_customer_id": "Identifier of the wallet's customer in your system.",+ "transaction_type": "Direction of the transaction: inbound (adds credits) or outbound (consumes credits).",+ "transaction_status": "Kind of transaction (e.g. purchased, granted, voided, invoiced).",+ "status": "Settlement status of the transaction (pending or settled).",+ "amount": "Transaction amount in the wallet currency.",+ "credit_amount": "Number of credits added or removed.",+ "settled_at": "Timestamp at which the transaction was settled.",+ "created_at": "Timestamp at which the transaction was created in Lago.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/lago.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/lago.pyindex 87f7f302a49b..957e84e76017 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/lago.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/lago.py@@ -13,6 +13,9 @@ record-creation timestamp, so they are unsafe to treat as an incremental cursor.can be layered on later for a specific endpoint once its server-side filter is verified against thelive API.+Charges and wallet transactions are only listed per parent (a plan, a wallet), so those tables fan+out over a fresh listing of the parent on every sync.+Pagination, retries, auth-header redaction, and the redirect / off-host SSRF guards are provided bythe shared ``rest_source`` framework (page-number paginator, ``allowed_hosts`` host-pinning,``allow_redirects=False``). The DNS-based internal-IP check for customer-supplied self-hosted hosts@@ -21,9 +24,9 @@ has no framework equivalent, so it stays here as a run-time pre-check.import reimport dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iterable, Iteratorfrom typing import Any, Optional-from urllib.parse import urlencode, urlparse+from urllib.parse import quote, urlencode, urlparseimport requests@@ -33,9 +36,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (PageNumberPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.lago.settings import (@@ -53,12 +60,15 @@ class LagoHostNotAllowedError(Exception):pass[email protected](frozen=True)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+ next_page: Optional[int] = None+ # Fan-out tables checkpoint the shape `build_dependent_resource` emits: which parents finished+ # and where the current one stopped.+ fanout_state: Optional[dict[str, Any]] = Nonedef normalize_base_url(api_url: Optional[str]) -> str:@@ -82,6 +92,13 @@ def _host_of(base_url: str) -> str:return (urlparse(base_url).hostname or "").lower()+def _encode_plan_code(row: dict[str, Any]) -> dict[str, Any]:+ return {**row, "_path_code": quote(str(row.get("code", "")), safe="")}+++_PARENT_DATA_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {"plans": _encode_plan_code}++def _get_headers(api_key: str) -> dict[str, str]:return {"Authorization": f"Bearer {api_key}",@@ -168,55 +185,78 @@ def lago_source(base_url = normalize_base_url(api_url)host = _host_of(base_url)- rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url,- # Auth (Bearer) is supplied via the framework auth config so its value is redacted from- # logs and raised errors; only the non-secret accept/content headers are set here.- "headers": {"Accept": "application/json", "Content-Type": "application/json"},- "auth": {"type": "bearer", "token": api_key},- # Pin every request to the base host and refuse redirects: a self-hosted host is- # customer-controlled, so a tampered pagination link or a 3xx to an internal address must- # not carry the Authorization header off-host (SSRF). `allowed_hosts=[]` means- # "same host as base_url only".- "allowed_hosts": [],- "allow_redirects": False,- # Page-number pagination; `meta.total_pages` stops after the last page so no extra empty- # page is fetched. `stop_after_empty_page` (default) covers a 0-row / missing-key body.- "paginator": PageNumberPaginator(base_page=1, total_path="meta.total_pages"),- },- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": {"per_page": config.page_size},- "data_selector": config.data_key,- },- }- ],+ client_config: ClientConfig = {+ "base_url": base_url,+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from+ # logs and raised errors; only the non-secret accept/content headers are set here.+ "headers": {"Accept": "application/json", "Content-Type": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ # Pin every request to the base host and refuse redirects: a self-hosted host is+ # customer-controlled, so a tampered pagination link or a 3xx to an internal address must+ # not carry the Authorization header off-host (SSRF). `allowed_hosts=[]` means+ # "same host as base_url only".+ "allowed_hosts": [],+ "allow_redirects": False,+ # Page-number pagination; `meta.total_pages` stops after the last page so no extra empty+ # page is fetched. `stop_after_empty_page` (default) covers a 0-row / missing-key body.+ "paginator": PageNumberPaginator(base_page=1, total_path="meta.total_pages"),}- initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():- resume = resumable_source_manager.load_state()- if resume is not None:- initial_paginator_state = {"page": resume.next_page}-- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields- # the last page (merge dedupes on `lago_id`) rather than skipping it.- if state and state.get("page") is not None:- resumable_source_manager.save_state(LagoResumeConfig(next_page=int(state["page"])))-- resource = rest_api_resource(- rest_config,- team_id,- job_id,- db_incremental_field_last_value,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,- )+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ resource: Iterable[Any]+ if config.fanout is not None:+ parent_config = LAGO_ENDPOINTS[config.fanout.parent_name]++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state:+ resumable_source_manager.save_state(LagoResumeConfig(fanout_state=state))++ resource = build_dependent_resource(+ endpoint_configs=LAGO_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="per_page",+ parent_endpoint_extra={"data_selector": parent_config.data_key},+ child_endpoint_extra={"data_selector": config.data_key},+ parent_data_map=_PARENT_DATA_MAPS.get(config.fanout.parent_name),+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=resume.fanout_state if resume else None,+ )+ else:+ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resources": [+ {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": {"per_page": config.page_size},+ "data_selector": config.data_key,+ },+ }+ ],+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields+ # the last page (merge dedupes on `lago_id`) rather than skipping it.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(LagoResumeConfig(next_page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state={"page": resume.next_page} if resume and resume.next_page is not None else None,+ )def items() -> Iterator[list[dict[str, Any]]]:# Re-check at run time (not just at source-create) in case the URL was edited or now resolves@@ -229,7 +269,7 @@ def lago_source(return SourceResponse(name=endpoint,items=items,- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,# 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",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/settings.pyindex 644a8aa4cf9a..48253a172066 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/settings.py@@ -1,13 +1,16 @@from dataclasses import dataclass, fieldfrom typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField# Number of records to request per page. Lago caps `per_page` at 100.DEFAULT_PAGE_SIZE = 100-@dataclass+@dataclass(frozen=True)class LagoEndpointConfig:name: str# Path appended to the API base (which already ends in `/api/v1`).@@ -16,8 +19,8 @@ class LagoEndpointConfig:# (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"+ # globally-unique UUID. `lago_id` is the stable primary key on every resource except events.+ primary_keys: list[str] = field(default_factory=lambda: ["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"@@ -25,12 +28,12 @@ class LagoEndpointConfig:# 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)+ default_incremental_field: Optional[str] = None+ # Set for resources only listed per parent (e.g. a plan's charges); the parent is re-listed each sync.+ fanout: Optional[DependentEndpointConfig] = None-# 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.+# Charge filters are not a separate table: every charge row already carries its `filters` array.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"),@@ -39,11 +42,49 @@ LAGO_ENDPOINTS: dict[str, LagoEndpointConfig] = {),"coupons": LagoEndpointConfig(name="coupons", path="/coupons", data_key="coupons"),"credit_notes": LagoEndpointConfig(name="credit_notes", path="/credit_notes", data_key="credit_notes"),+ "charges": LagoEndpointConfig(+ name="charges",+ path="/plans/{plan_code}/charges",+ data_key="charges",+ fanout=DependentEndpointConfig(+ parent_name="plans",+ resolve_param="plan_code",+ # Plan codes are user-defined, so the path segment is the percent-encoded code that+ # `_encode_plan_code` adds to each plan row.+ resolve_field="_path_code",+ include_from_parent=["lago_id", "code"],+ parent_field_renames={"lago_id": "lago_plan_id", "code": "plan_code"},+ ),+ ),"customers": LagoEndpointConfig(name="customers", path="/customers", data_key="customers"),+ # Lago events have no guaranteed `lago_id`. Lago dedupes an event on its transaction id within a+ # subscription, and the ClickHouse event store also keys on the timestamp.+ "events": LagoEndpointConfig(+ name="events",+ path="/events",+ data_key="events",+ primary_keys=["transaction_id", "external_subscription_id", "timestamp"],+ partition_key="timestamp",+ ),"fees": LagoEndpointConfig(name="fees", path="/fees", data_key="fees"),"invoices": LagoEndpointConfig(name="invoices", path="/invoices", data_key="invoices"),+ "payments": LagoEndpointConfig(name="payments", path="/payments", data_key="payments"),"plans": LagoEndpointConfig(name="plans", path="/plans", data_key="plans"),"subscriptions": LagoEndpointConfig(name="subscriptions", path="/subscriptions", data_key="subscriptions"),+ # `/wallet_transactions` only accepts POST (top-ups); the listing is per wallet.+ "wallet_transactions": LagoEndpointConfig(+ name="wallet_transactions",+ path="/wallets/{wallet_id}/wallet_transactions",+ data_key="wallet_transactions",+ fanout=DependentEndpointConfig(+ parent_name="wallets",+ resolve_param="wallet_id",+ resolve_field="lago_id",+ include_from_parent=["external_customer_id"],+ parent_field_renames={"external_customer_id": "external_customer_id"},+ ),+ ),+ "wallets": LagoEndpointConfig(name="wallets", path="/wallets", data_key="wallets"),}ENDPOINTS = tuple(LAGO_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/tests/test_lago.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/tests/test_lago.pyindex 2d14dc999393..52fb49c2d915 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lago/tests/test_lago.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lago/tests/test_lago.py@@ -250,3 +250,42 @@ class TestRedirectAndHostGuards:_rows(_source(_make_manager()))# The SSRF pre-check fires before any request leaves the process.session.send.assert_not_called()+++class TestFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_charges_walk_every_plan_and_child_page(self, MockSession):+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page(+ [{"lago_id": "p1", "code": "pro/annual"}, {"lago_id": "p2", "code": "basic"}],+ data_key="plans",+ ),+ _page([{"lago_id": "c1"}], total_pages=2, next_page=2, data_key="charges"),+ _page([{"lago_id": "c2"}], total_pages=2, data_key="charges"),+ _page([{"lago_id": "c3"}], data_key="charges"),+ ],+ )+ manager = _make_manager()++ rows = _rows(_source(manager, endpoint="charges"))++ urls = [c.args[0].url for c in session.prepare_request.call_args_list]+ assert urls == [+ "https://api.getlago.com/api/v1/plans",+ # A user-defined plan code is percent-encoded so it stays one path segment.+ "https://api.getlago.com/api/v1/plans/pro%2Fannual/charges",+ "https://api.getlago.com/api/v1/plans/pro%2Fannual/charges",+ "https://api.getlago.com/api/v1/plans/basic/charges",+ ]+ assert [p.get("page") for p in params] == [1, 1, 2, 1]+ assert [(r["lago_id"], r["lago_plan_id"], r["plan_code"]) for r in rows] == [+ ("c1", "p1", "pro/annual"),+ ("c2", "p1", "pro/annual"),+ ("c3", "p2", "basic"),+ ]+ assert all("_path_code" not in r for r in rows)+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert saved and all(s.fanout_state is not None and s.next_page is None for s in saved)