:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 9 missing tables to the Lago source (#117107)
Tom Owersc07ee4d36a20
diff --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 4eeb6e098a75..1eb7451f531b 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@@ -7035,10 +7035,10 @@ Diffed against: <https://raw.githubusercontent.com/getlago/lago-openapi/main/ope- [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)-- [ ] `GET /analytics/mrr, /analytics/gross_revenue, /analytics/invoice_collection, /analytics/overdue_balance, /analytics/invoiced_usage` — Lago's headline pre-computed revenue metrics (medium)+- [x] `GET /taxes` — lookup resolving tax codes applied on invoices, fees and customers (medium)+- [x] `GET /payment_requests and GET /payment_receipts` — dunning requests and receipts for collections reporting (medium)+- [x] `GET /billing_entities` — lookup for the billing entity that owns each invoice in multi-entity setups (medium)+- [x] `GET /analytics/mrr, /analytics/gross_revenue, /analytics/invoice_collection, /analytics/overdue_balance, /analytics/invoiced_usage` — Lago's headline pre-computed revenue metrics (medium)- [ ] `GET /subscriptions/{external_id}/lifetime_usage` — lifetime usage per subscription for commitment and threshold tracking (medium)- [ ] `GET /activity_logs` — state-change history across customers, subscriptions and invoices (medium)- [ ] `GET /customers/{external_customer_id}/current_usage and /past_usage` — in-period usage before invoicing, needed for revenue forecasting (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 edd89af98aa8..8e1050bb4aa9 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@@ -202,4 +202,112 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Timestamp at which the transaction was created in Lago.",},},+ "taxes": {+ "description": "A tax rate that Lago applies to billing entities or to specific customers.",+ "docs_url": "https://docs.getlago.com/api-reference/taxes/tax-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the tax.",+ "name": "Name of the tax.",+ "code": "Unique code of the tax, as referenced on invoices, fees and customers.",+ "description": "Internal description of the tax.",+ "rate": "Percentage rate of the tax.",+ "applied_to_billing_entities_codes": "Codes of the billing entities the tax is applied to.",+ "created_at": "Timestamp at which the tax was created in Lago.",+ },+ },+ "payment_requests": {+ "description": "A dunning request that asks a customer to pay one or more overdue invoices.",+ "docs_url": "https://docs.getlago.com/api-reference/payment-requests/payment-request-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the payment request.",+ "email": "Email address the dunning notifications are sent to.",+ "amount_cents": "Sum of the totals of the invoices in the request, in the currency's smallest unit.",+ "amount_currency": "Currency of the payment request (ISO 4217).",+ "payment_status": "Status of the payment for the request (e.g. pending, succeeded, failed).",+ "customer": "The customer the payment request applies to.",+ "invoices": "The invoices included in the payment request.",+ "created_at": "Timestamp at which the payment request was created in Lago.",+ },+ },+ "payment_receipts": {+ "description": "A receipt issued for a payment made on an invoice or a payment request.",+ "docs_url": "https://docs.getlago.com/api-reference/payment-receipts/payment-receipt-object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the payment receipt.",+ "number": "Unique number of the payment receipt.",+ "file_url": "URL of the PDF file of the payment receipt.",+ "xml_url": "URL of the e-invoicing XML file of the payment receipt.",+ "payment": "The payment the receipt was issued for.",+ "created_at": "Timestamp at which the payment receipt was created in Lago.",+ },+ },+ "billing_entities": {+ "description": "A legal entity of the organization that issues invoices, used in multi-entity setups.",+ "docs_url": "https://docs.getlago.com/api-reference/billing-entities/object",+ "columns": {+ "lago_id": "Lago's globally-unique identifier for the billing entity.",+ "code": "Unique code of the billing entity.",+ "name": "Name of the billing entity.",+ "default_currency": "Default currency of the billing entity (ISO 4217).",+ "is_default": "Whether this is the organization's default billing entity.",+ "legal_name": "Legal name of the billing entity.",+ "country": "Country code of the billing address.",+ "timezone": "Timezone of the billing entity.",+ "net_payment_term": "Net payment term of the billing entity, in days.",+ "created_at": "Timestamp at which the billing entity was created in Lago.",+ "updated_at": "Timestamp at which the billing entity was last updated in Lago.",+ },+ },+ "analytics_mrr": {+ "description": "Monthly recurring revenue from subscription fees, one row per month and currency.",+ "docs_url": "https://docs.getlago.com/guide/analytics/mrr",+ "columns": {+ "month": "First instant (UTC) of the month the MRR is reported for.",+ "amount_cents": "MRR for the month, in the currency's smallest unit. Null for a month with no subscription fee.",+ "currency": "Currency of the MRR (ISO 4217). Null for a month with no subscription fee.",+ },+ },+ "analytics_gross_revenue": {+ "description": "Monthly gross revenue from finalized invoices and pay-in-advance fees, net of refunds.",+ "docs_url": "https://docs.getlago.com/guide/analytics/gross-revenue",+ "columns": {+ "month": "First instant (UTC) of the month the revenue is reported for.",+ "amount_cents": "Gross revenue for the month, in the currency's smallest unit.",+ "currency": "Currency of the revenue (ISO 4217).",+ "invoices_count": "Number of finalized invoices issued during the month.",+ "billing_entity_id": "Lago identifier of the billing entity the revenue is attributed to.",+ },+ },+ "analytics_invoice_collection": {+ "description": "Monthly count and total of finalized invoices, grouped by payment status and currency.",+ "docs_url": "https://docs.getlago.com/guide/analytics/invoice-collection",+ "columns": {+ "month": "Month of the invoice issuing date.",+ "payment_status": "Payment status of the invoices in the row. Null for a month with no finalized invoices.",+ "invoices_count": "Number of finalized invoices issued during the month with this payment status.",+ "amount_cents": "Total of the invoices in the row, in the currency's smallest unit.",+ "currency": "Currency of the invoices (ISO 4217). Null for a month with no finalized invoices.",+ },+ },+ "analytics_invoiced_usage": {+ "description": "Monthly invoiced revenue from usage-based fees, per billable metric and currency.",+ "docs_url": "https://docs.getlago.com/guide/analytics/overview",+ "columns": {+ "month": "First instant (UTC) of the month the invoiced usage is reported for.",+ "code": "Code of the billable metric the usage fees were charged for.",+ "amount_cents": "Invoiced usage for the month, excluding taxes and net of coupons, in the smallest unit.",+ "currency": "Currency of the invoiced usage (ISO 4217).",+ },+ },+ "analytics_overdue_balance": {+ "description": "Amount still due on overdue invoices, per month of payment due date and currency.",+ "docs_url": "https://docs.getlago.com/guide/analytics/overview",+ "columns": {+ "month": "Month of the payment due date of the overdue invoices.",+ "amount_cents": "Amount still due, net of payments and credit notes, in the currency's smallest unit.",+ "currency": "Currency of the overdue invoices (ISO 4217).",+ "lago_invoice_ids": "Lago identifiers of the overdue invoices included in the amount.",+ "billing_entity_id": "Lago identifier of the billing entity the overdue balance is attributed to.",+ },+ },}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 957e84e76017..86aac40034c8 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@@ -4,7 +4,8 @@ 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 URLmust 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 ``total_pages`` / ``next_page``.+that carries ``total_pages`` / ``next_page``. Billing entities and the analytics reports are the+exception: they return the whole collection in one body with no ``meta``.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@@ -42,7 +43,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom 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 ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)from 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 (@@ -229,18 +233,15 @@ def lago_source(initial_paginator_state=resume.fanout_state if resume else None,)else:+ endpoint_config: Endpoint = {"path": config.path, "data_selector": config.data_key}+ if config.paginated:+ endpoint_config["params"] = {"per_page": config.page_size}+ else:+ endpoint_config["paginator"] = "single_page"+rest_config: RESTAPIConfig = {"client": client_config,- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": {"per_page": config.page_size},- "data_selector": config.data_key,- },- }- ],+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],}def save_checkpoint(state: Optional[dict[str, Any]]) -> None: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 48253a172066..76ac44737167 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@@ -25,6 +25,8 @@ class LagoEndpointConfig:# and never changes. Never partition on a mutable field.partition_key: Optional[str] = "created_at"page_size: int = DEFAULT_PAGE_SIZE+ # Billing entities and the analytics reports return their whole collection in one unpaginated body.+ paginated: bool = True# 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)@@ -33,13 +35,51 @@ class LagoEndpointConfig:fanout: Optional[DependentEndpointConfig] = None+def _analytics_endpoint(name: str, path: str, data_key: str, primary_keys: list[str]) -> LagoEndpointConfig:+ # Without a `months` filter each report covers every month since the organization was created,+ # one row per month and grouping key, so a full refresh rebuilds the whole history.+ return LagoEndpointConfig(+ name=name,+ path=path,+ data_key=data_key,+ primary_keys=primary_keys,+ partition_key=None,+ paginated=False,+ )++# 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"),+ "analytics_gross_revenue": _analytics_endpoint(+ "analytics_gross_revenue",+ "/analytics/gross_revenue",+ "gross_revenues",+ ["month", "currency", "billing_entity_id"],+ ),+ "analytics_invoice_collection": _analytics_endpoint(+ "analytics_invoice_collection",+ "/analytics/invoice_collection",+ "invoice_collections",+ ["month", "payment_status", "currency"],+ ),+ "analytics_invoiced_usage": _analytics_endpoint(+ "analytics_invoiced_usage", "/analytics/invoiced_usage", "invoiced_usages", ["month", "code", "currency"]+ ),+ "analytics_mrr": _analytics_endpoint("analytics_mrr", "/analytics/mrr", "mrrs", ["month", "currency"]),+ "analytics_overdue_balance": _analytics_endpoint(+ "analytics_overdue_balance",+ "/analytics/overdue_balance",+ "overdue_balances",+ ["month", "currency", "billing_entity_id"],+ ),"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"),+ "billing_entities": LagoEndpointConfig(+ name="billing_entities", path="/billing_entities", data_key="billing_entities", paginated=False+ ),"coupons": LagoEndpointConfig(name="coupons", path="/coupons", data_key="coupons"),"credit_notes": LagoEndpointConfig(name="credit_notes", path="/credit_notes", data_key="credit_notes"),"charges": LagoEndpointConfig(@@ -68,9 +108,16 @@ LAGO_ENDPOINTS: dict[str, LagoEndpointConfig] = {),"fees": LagoEndpointConfig(name="fees", path="/fees", data_key="fees"),"invoices": LagoEndpointConfig(name="invoices", path="/invoices", data_key="invoices"),+ "payment_receipts": LagoEndpointConfig(+ name="payment_receipts", path="/payment_receipts", data_key="payment_receipts"+ ),+ "payment_requests": LagoEndpointConfig(+ name="payment_requests", path="/payment_requests", data_key="payment_requests"+ ),"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"),+ "taxes": LagoEndpointConfig(name="taxes", path="/taxes", data_key="taxes"),# `/wallet_transactions` only accepts POST (top-ups); the listing is per wallet."wallet_transactions": LagoEndpointConfig(name="wallet_transactions",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 8a21824ab104..c0d10c1c4562 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@@ -133,21 +133,77 @@ class TestValidateCredentials:class TestPagination:- def test_paginates_and_progresses_page(self):+ @pytest.mark.parametrize(+ "endpoint, path",+ [+ ("customers", "/api/v1/customers"),+ ("taxes", "/api/v1/taxes"),+ ("payment_requests", "/api/v1/payment_requests"),+ ("payment_receipts", "/api/v1/payment_receipts"),+ ],+ )+ def test_paginates_and_progresses_page(self, endpoint, path):result = _driver().run(- "customers",+ endpoint,[- _page([{"lago_id": "1"}, {"lago_id": "2"}], total_pages=2, next_page=2),- _page([{"lago_id": "3"}], total_pages=2),+ _page([{"lago_id": "1"}, {"lago_id": "2"}], total_pages=2, next_page=2, data_key=endpoint),+ _page([{"lago_id": "3"}], total_pages=2, data_key=endpoint),],)assert result.raised is Noneassert [row["lago_id"] for row in result.rows] == ["1", "2", "3"]+ assert result.paths == [path, path]# First request page=1, second request page=2, both carry per_page.assert result.params("page") == ["1", "2"]assert result.params("per_page") == ["100", "100"]+ @pytest.mark.parametrize(+ "endpoint, path, data_key, row",+ [+ ("billing_entities", "/api/v1/billing_entities", "billing_entities", {"lago_id": "be1", "code": "acme"}),+ (+ "analytics_mrr",+ "/api/v1/analytics/mrr",+ "mrrs",+ {"month": "2024-01-01T00:00:00.000Z", "amount_cents": None, "currency": None},+ ),+ (+ "analytics_gross_revenue",+ "/api/v1/analytics/gross_revenue",+ "gross_revenues",+ {"month": "2024-01-01T00:00:00.000Z", "amount_cents": 1200, "currency": "EUR"},+ ),+ (+ "analytics_invoice_collection",+ "/api/v1/analytics/invoice_collection",+ "invoice_collections",+ {"month": "2024-01-01T00:00:00.000Z", "payment_status": "succeeded", "invoices_count": 3},+ ),+ (+ "analytics_invoiced_usage",+ "/api/v1/analytics/invoiced_usage",+ "invoiced_usages",+ {"month": "2024-01-01T00:00:00.000Z", "code": "api_calls", "currency": "USD"},+ ),+ (+ "analytics_overdue_balance",+ "/api/v1/analytics/overdue_balance",+ "overdue_balances",+ {"month": "2024-01-01T00:00:00.000Z", "lago_invoice_ids": ["inv-1"], "currency": "USD"},+ ),+ ],+ )+ def test_unpaginated_endpoint_makes_one_request_without_page_params(self, endpoint, path, data_key, row):+ # These bodies carry no `meta`, so page-number pagination must not apply.+ result = _driver().run(endpoint, [ScriptedResponse(json={data_key: [row, row]})])++ assert result.raised is None+ assert result.rows == [row, row]+ assert result.paths == [path]+ assert result.params("page") == [None]+ assert result.params("per_page") == [None]+def test_resumes_from_saved_state(self):result = _driver().run("customers", [_page([{"lago_id": "9"}], total_pages=3)], resume_state=LagoResumeConfig(next_page=3)