: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(chartmogul): sync subscriptions, CRM deals, and key metrics (#102237)
Tom Owers4eed83077ca1
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 f105f8caf22d..dbf5f0fe5f84 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@@ -1381,21 +1381,21 @@ Note: Full OpenAPI 3 spec (2 MB, 541 paths) is served unauthenticated at api.cha## ChartMogul — gaps-Today (6): `activities`, `customers`, `data_sources`, `invoices`, `plan_groups`, `plans`+Today (11): `activities`, `customer_subscriptions`, `customers`, `data_sources`, `invoices`, `metrics`, `metrics_mrr`, `opportunities`, `plan_groups`, `plans`, `subscription_events`Diffed against: <https://dev.chartmogul.com/sitemap.xml>-- [ ] `/v1/customers/{customer_uuid}/subscriptions` — subscriptions are the core SaaS object and currently unreachable - plans and invoices cannot be joined into a subscription lifecycle (high)-- [ ] `/v1/subscription_events` — subscription state transition stream (started, updated, cancelled) - the movement history behind churn analysis (high)-- [ ] `/v1/metrics/all (plus /metrics/mrr, /arr, /arpa, /asp, /ltv, /customer-count, /churn-rate, /mrr-churn-rate)` — ChartMogul's headline metrics; today none of the product's actual output is syncable (high)-- [ ] `/v1/opportunities` — CRM pipeline deals with value and stage - the main revenue-forecasting object (high)+- [x] `/v1/customers/{customer_uuid}/subscriptions` — subscriptions are the core SaaS object and currently unreachable - plans and invoices cannot be joined into a subscription lifecycle (high)+- [x] `/v1/subscription_events` — subscription state transition stream (started, updated, cancelled) - the movement history behind churn analysis (high)+- [x] `/v1/metrics/all (plus /metrics/mrr)` — ChartMogul's headline metrics; today none of the product's actual output is syncable (high). `/arr`, `/arpa`, `/asp`, `/ltv`, `/customer-count`, `/churn-rate` and `/mrr-churn-rate` are intentionally not synced: each returns one metric `/v1/metrics/all` already carries as a column.+- [x] `/v1/opportunities` — CRM pipeline deals with value and stage - the main revenue-forecasting object (high)- [ ] `/v1/contacts` — person-level contacts under each customer, needed to join CRM activity to accounts (medium)- [ ] `/v1/plan_groups/{plan_group_uuid}/plans` — lookup mapping the already-synced plans to the already-synced plan_groups (medium)- [ ] `/v1/customers/{customer_uuid}/attributes (custom attributes and tags)` — the segmentation dimensions customers are actually sliced by (medium)- [ ] `/v1/tasks` — CRM tasks per customer for CS workload and follow-up analysis (medium)- [ ] `/v1/customer_notes (notes and call logs)` — logged calls and notes per customer, joinable to churn outcomes (low)-Note: No machine-readable spec is published; I enumerated the full /reference/\* resource tree from the sitemap (182 URLs) and then fetched the individual reference pages to confirm the concrete api.chartmogul.com paths (e.g. /v1/subscription_events, /v1/opportunities, /v1/customers/{uuid}/subscriptions, /v1/plan_groups/{uuid}/plans). Notably the entire ChartMogul CRM surface (opportunities, contacts, tasks, notes) and every metrics endpoint are absent.+Note: No machine-readable spec is published; I enumerated the full /reference/\* resource tree from the sitemap (182 URLs) and then fetched the individual reference pages to confirm the concrete api.chartmogul.com paths (e.g. /v1/subscription_events, /v1/opportunities, /v1/customers/{uuid}/subscriptions, /v1/plan_groups/{uuid}/plans). The entire ChartMogul CRM surface and every metrics endpoint were absent at audit time; opportunities, subscription events, customer subscriptions and the metrics timeseries are now synced, and contacts, tasks and notes remain.## Chatwoot — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/api_inventory.mdindex 04e495a13c44..dd713d957d88 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/api_inventory.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/api_inventory.md@@ -10,29 +10,64 @@## Verification status-The pagination, sort order, and `start-date` filter behavior below are taken from the public docs.+The pagination, sort order, and filter behavior below are taken from the public docs.They could **not** be smoke-tested with curl against the live API during implementation because noChartMogul API key was available in the build environment. The conservative choices (full refresh onevery endpoint except activities; `start-date` server-side filter only on activities) reflect that:-only the activities endpoint documents a genuine server-side date filter, so it is the single endpoint-marked incremental.+only the activities endpoint documents a genuine server-side date filter on a field that cannot move.## Endpoints-| Schema | Path | Data key | Primary key | Partition key | Incremental |-| ------------ | ------------------ | -------------- | ----------- | ------------- | ---------------------------- |-| customers | `/v1/customers` | `entries` | `uuid` | — | full refresh (no timestamp) |-| plans | `/v1/plans` | `plans` | `uuid` | — | full refresh |-| plan_groups | `/v1/plan_groups` | `plan_groups` | `uuid` | — | full refresh |-| invoices | `/v1/invoices` | `invoices` | `uuid` | `date` | full refresh |-| activities | `/v1/activities` | `entries` | `uuid` | `date` | `start-date` server filter |-| data_sources | `/v1/data_sources` | `data_sources` | `uuid` | `created_at` | full refresh (not paginated) |+| Schema | Path | Data key | Primary key | Partition key | Incremental |+| ---------------------- | --------------------------------------------- | --------------------- | ------------------------ | ------------- | ---------------------------- |+| customers | `/v1/customers` | `entries` | `uuid` | — | full refresh (no timestamp) |+| customer_subscriptions | `/v1/customers/{customer_uuid}/subscriptions` | `entries` | `customer_uuid` + `uuid` | — | full refresh (no filter) |+| plans | `/v1/plans` | `plans` | `uuid` | — | full refresh |+| plan_groups | `/v1/plan_groups` | `plan_groups` | `uuid` | — | full refresh |+| invoices | `/v1/invoices` | `invoices` | `uuid` | `date` | full refresh |+| activities | `/v1/activities` | `entries` | `uuid` | `date` | `start-date` server filter |+| subscription_events | `/v1/subscription_events` | `subscription_events` | `id` | `created_at` | full refresh (no range) |+| opportunities | `/v1/opportunities` | `entries` | `uuid` | `created_at` | full refresh (no range) |+| metrics | `/v1/metrics/all` | `entries` | `date` | `date` | full refresh (recalculated) |+| metrics_mrr | `/v1/metrics/mrr` | `entries` | `date` | `date` | full refresh (recalculated) |+| data_sources | `/v1/data_sources` | `data_sources` | `uuid` | `created_at` | full refresh (not paginated) |Notes:- **Customers** expose no update timestamp and no server-side creation/update date filter, so trueincremental sync is impossible — Airbyte's connector also only supports full refresh here.+- **customer_subscriptions** is only reachable per customer, so it fans out over the customers+ listing. The subscription object carries no reference back to its customer, so the parent's `uuid`+ is injected as `customer_uuid`: without it the rows cannot be joined to anything, and the docs do+ not commit to `uuid` being unique outside its own customer, so it is part of the primary key. The+ child accepts only `cursor` and `per_page`, with no filters, so it is full refresh. Every date on the+ object is hyphenated (`start-date`, `end-date`), unlike every partition key this source uses, so+ the table is left unpartitioned.- **Activities** is the only endpoint with a documented server-side `start-date` / `end-date` filter,and is documented to return rows in ascending chronological order, so it is synced incrementally onthe `date` field with `sort_mode="asc"`.+- **subscription_events** takes `event_date` and `effective_date` as **exact-timestamp** filters, not+ ranges, so there is nothing for an incremental cursor to bind to. Its id is ChartMogul's own+ integer, not a uuid. `created_at` is the only date on the object that cannot move, so it is the+ partition key.+- **Opportunities** filters only on `estimated_close_date_on_or_after` / `_on_or_before`, and a deal's+ estimated close date moves in either direction, so it cannot serve as an incremental cursor.+- **metrics / metrics_mrr** return one entry per interval and take no pagination params, so each is a+ single request. Both require `start-date` and `end-date`, built at request time from a floor set+ well before ChartMogul existed (so no imported billing history is cut off) to the sync date, at+ `interval=day`, because a warehouse query can roll days up to months but not the reverse. They are full+ refresh despite that range filter being a real server-side one: ChartMogul recalculates past+ intervals when invoices and events are backfilled or edited, so an incremental window anchored on+ the newest `date` would freeze every revised historical value. A full refresh is the same single+ request, so the incremental option would save nothing and lose the revisions.- **data_sources** returns the full list in a single response (no cursor), so it is fetched once.++## Endpoints deliberately not synced++- `/v1/metrics/arr`, `/arpa`, `/asp`, `/ltv`, `/customer-count`, `/churn-rate`, `/mrr-churn-rate`+ each return entries of `{date, <one metric>, percentage-change}`. `/v1/metrics/all` already carries+ every one of those metrics as a column, with its own `*-percentage-change`, so syncing them would+ add seven single-metric tables duplicating the `metrics` table and seven requests per sync.+ `/v1/metrics/mrr` is the one sibling kept, because it is the only one with columns `/all` does not+ have: the MRR movement breakdown (`mrr-new-business`, `mrr-expansion`, `mrr-contraction`,+ `mrr-churn`, `mrr-reactivation`).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/canonical_descriptions.pyindex e3cc00bfe3ba..9ae7c49cfb09 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/canonical_descriptions.py@@ -85,6 +85,117 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"customer-uuid": "UUID of the customer the activity relates to.",},},+ "customer_subscriptions": {+ "description": "A subscription held by a customer, listed per customer.",+ "docs_url": "https://dev.chartmogul.com/reference/list-customer-subscriptions",+ "columns": {+ "uuid": "Unique identifier for the customer subscription in ChartMogul.",+ "customer_uuid": "UUID of the customer the subscription belongs to, carried over from the customer listing.",+ "id": "ChartMogul's identifier for the subscription.",+ "external_id": "Identifier of the subscription in the source billing system.",+ "subscription_set_external_id": "External identifier of the subscription set this subscription belongs to, if any.",+ "subscription_set_uuid": "UUID of the subscription set this subscription belongs to, if any.",+ "plan": "Name of the plan the customer subscribed to.",+ "quantity": "Number of plans purchased by the customer.",+ "mrr": "Monthly recurring revenue attributable to this subscription, in cents.",+ "arr": "Annual run rate for this subscription, calculated as MRR multiplied by 12.",+ "status": "Whether the subscription is active or inactive.",+ "billing-cycle": "Unit of the billing cycle (day, month, or year).",+ "billing-cycle-count": "How many billing cycle units pass between billings.",+ "start-date": "Date and time the subscription started.",+ "end-date": "Date and time the subscription is due to run out, based on payments made so far.",+ "currency": "Three-letter ISO currency code the MRR and ARR are reported in.",+ "currency-sign": "Display symbol for the subscription's currency.",+ "custom_attributes": "Custom attributes set on the subscription.",+ },+ },+ "subscription_events": {+ "description": "A subscription state transition (started, updated, cancelled, or retracted) recorded by ChartMogul.",+ "docs_url": "https://dev.chartmogul.com/reference/list-subscription-events",+ "columns": {+ "id": "ChartMogul's identifier for the subscription event.",+ "external_id": "Identifier of the event supplied when it was created.",+ "data_source_uuid": "UUID of the data source the event was added to.",+ "customer_external_id": "Identifier of the customer in the source billing system.",+ "data_source_customer_external_id": "Identifier of the customer in the source billing system.",+ "subscription_external_id": "Identifier of the subscription the event belongs to.",+ "subscription_set_external_id": "External identifier of the subscription set grouping this subscription, if any.",+ "plan_external_id": "Identifier of the plan associated with the event.",+ "event_type": "Type of transition, such as subscription_start, subscription_updated, or subscription_cancelled.",+ "event_date": "Date and time the event was raised.",+ "effective_date": "Date and time the event takes effect.",+ "event_order": "Ordering applied to events that share an effective date.",+ "quantity": "Number of plans on the subscription after the event.",+ "currency": "Three-letter ISO currency code of the event amount.",+ "amount_in_cents": "Final charge after discounts, taxes, and fees, in cents.",+ "tax_amount_in_cents": "Tax applied to the subscription, in cents.",+ "retracted_event_id": "Identifier of the event this event retracts; null for anything other than a retraction.",+ "disabled": "Whether the event has been disabled.",+ "disabled_by": "Email of the team member who disabled the event.",+ "disabled_at": "Date and time the event was disabled.",+ "user_created": "Whether a team member created the event manually on an automatic data source.",+ "errors": "Validation errors raised when the event was created.",+ "created_at": "Date and time the event was created in ChartMogul.",+ "updated_at": "Date and time the event was last updated.",+ },+ },+ "opportunities": {+ "description": "A sales pipeline deal tracked in ChartMogul's CRM, with its value, stage, and forecast.",+ "docs_url": "https://dev.chartmogul.com/reference/list-opportunities",+ "columns": {+ "uuid": "Unique identifier for the opportunity in ChartMogul.",+ "customer_uuid": "UUID of the customer the opportunity is associated with.",+ "owner": "Email of the team member who is the primary salesperson for the opportunity.",+ "pipeline": "Name of the sales pipeline the opportunity sits in.",+ "pipeline_stage": "Name of the current deal stage within the sales pipeline.",+ "estimated_close_date": "Date the deal is expected to close.",+ "currency": "Three-letter ISO currency code of the deal amount.",+ "amount_in_cents": "Value of the deal, in cents.",+ "type": "Opportunity type: recurring, arr, or one-time.",+ "forecast_category": "Forecast bucket for the deal: pipeline, best_case, committed, lost, or won.",+ "win_likelihood": "Estimated probability of winning the deal, as a percentage.",+ "custom": "Custom fields set on the opportunity.",+ "created_at": "Date and time the opportunity was created.",+ "updated_at": "Date and time the opportunity was last updated.",+ },+ },+ "metrics": {+ "description": "ChartMogul's headline subscription metrics for each interval in the reporting period.",+ "docs_url": "https://dev.chartmogul.com/reference/retrieve-all-key-metrics",+ "columns": {+ "date": "End date of the interval the metrics are reported for.",+ "mrr": "Monthly recurring revenue at the end of the interval, in cents.",+ "mrr-percentage-change": "Change in MRR against the previous interval.",+ "arr": "Annual run rate at the end of the interval, in cents.",+ "arr-percentage-change": "Change in ARR against the previous interval.",+ "customer-churn-rate": "Customer churn rate at the end of the interval, as a percentage.",+ "customer-churn-rate-percentage-change": "Change in customer churn rate against the previous interval.",+ "mrr-churn-rate": "Net MRR churn rate at the end of the interval, as a percentage.",+ "mrr-churn-rate-percentage-change": "Change in net MRR churn rate against the previous interval.",+ "ltv": "Customer lifetime value at the end of the interval, in cents.",+ "ltv-percentage-change": "Change in customer lifetime value against the previous interval.",+ "customers": "Number of active customers at the end of the interval.",+ "customers-percentage-change": "Change in active customer count against the previous interval.",+ "asp": "Average sale price at the end of the interval, in cents.",+ "asp-percentage-change": "Change in average sale price against the previous interval.",+ "arpa": "Average revenue per account at the end of the interval, in cents.",+ "arpa-percentage-change": "Change in average revenue per account against the previous interval.",+ },+ },+ "metrics_mrr": {+ "description": "Monthly recurring revenue for each interval, broken down into the movements that produced it.",+ "docs_url": "https://dev.chartmogul.com/reference/retrieve-mrr",+ "columns": {+ "date": "End date of the interval the MRR is reported for.",+ "mrr": "Monthly recurring revenue at the end of the interval, in cents.",+ "percentage-change": "Change in MRR against the previous interval.",+ "mrr-new-business": "New MRR during the interval from new customers, in cents.",+ "mrr-expansion": "New MRR during the interval from existing customers, such as upgrades, in cents.",+ "mrr-contraction": "MRR lost during the interval excluding cancellations, in cents.",+ "mrr-churn": "MRR lost during the interval to subscription cancellations, in cents.",+ "mrr-reactivation": "MRR regained during the interval from previously cancelled customers, in cents.",+ },+ },"data_sources": {"description": "A configured ChartMogul data source that billing data is imported through.","docs_url": "https://dev.chartmogul.com/reference/list-data-sources",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/chartmogul.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/chartmogul.pyindex bef69f281c46..7e15b47c9113 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/chartmogul.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/chartmogul.py@@ -1,35 +1,52 @@-import dataclasses+from collections.abc import Iterablefrom datetime import UTC, date, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom requests import Request, Responsefrom requests.auth import HTTPBasicAuth-from products.warehouse_sources.backend.temporal.data_imports.sources.chartmogul.settings import CHARTMOGUL_ENDPOINTS+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.chartmogul.settings import (+ CHARTMOGUL_ENDPOINTS,+ METRICS_START_DATE,+ ChartMogulEndpointConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,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 (BasePaginator,SinglePagePaginator,)+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.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponseCHARTMOGUL_BASE_URL = "https://api.chartmogul.com"-DEFAULT_PAGE_SIZE = 200+# (connect, read) seconds. Without it a stalled ChartMogul response holds an import worker+# until Temporal cancels the activity, rather than raising a retryable request timeout.+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)+@frozenclass ChartMogulResumeConfig:- # ChartMogul cursor pagination: each page returns an opaque `cursor` that- # encodes the next page. We persist only the cursor — the static query- # params (page size, incremental start-date) are deterministically rebuilt+ # Top-level endpoints resume from the opaque `cursor` of the last fully-yielded page. The+ # static query params (page size, incremental start-date) are deterministically rebuilt# from the config and the job inputs on resume.- cursor: str+ cursor: Optional[str] = None+ # Fan-out endpoints resume by parent: the customer paths already fully synced, the customer+ # in progress, and that customer's paginator state. See+ # `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed: Optional[list[str]] = None+ current: Optional[str] = None+ child_state: Optional[dict[str, Any]] = Noneclass ChartMogulPaginator(BasePaginator):@@ -105,36 +122,50 @@ def validate_credentials(api_key: str) -> bool:return ok-def chartmogul_source(- api_key: str,- endpoint: str,- team_id: int,- job_id: str,- resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],- should_use_incremental_field: bool = False,- db_incremental_field_last_value: Optional[Any] = None,-) -> SourceResponse:- config = CHARTMOGUL_ENDPOINTS[endpoint]+def _client_config(api_key: str, paginated: bool) -> ClientConfig:+ return {+ "base_url": CHARTMOGUL_BASE_URL,+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ # Some endpoints (data_sources, metrics) return the full list without pagination.+ "paginator": ChartMogulPaginator() if paginated else SinglePagePaginator(),+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+- params: dict[str, Any] = {}+def _request_params(+ config: ChartMogulEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> dict[str, Any]:+ params: dict[str, Any] = {**config.extra_params}if config.paginated:- params["per_page"] = DEFAULT_PAGE_SIZE+ params["per_page"] = config.page_size+ if config.requires_date_range:+ params["start-date"] = METRICS_START_DATE+ params["end-date"] = datetime.now(UTC).strftime("%Y-%m-%d")if config.incremental_param and should_use_incremental_field and db_incremental_field_last_value:params[config.incremental_param] = _format_start_date(db_incremental_field_last_value)+ return params++def _top_level_resource(+ config: ChartMogulEndpointConfig,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Iterable[Any]:rest_config: RESTAPIConfig = {- "client": {- "base_url": CHARTMOGUL_BASE_URL,- "auth": {"type": "http_basic", "username": api_key, "password": ""},- # Some endpoints (data_sources) return the full list without pagination.- "paginator": ChartMogulPaginator() if config.paginated else SinglePagePaginator(),- },+ "client": _client_config(api_key, config.paginated),"resources": [{"name": endpoint,"endpoint": {"path": config.path,- "params": params,+ "params": _request_params(config, should_use_incremental_field, db_incremental_field_last_value),# ChartMogul wraps results per resource (customers/activities# use "entries", plans use "plans", etc.); a missing key is# treated as an empty page, matching the historical behavior.@@ -147,7 +178,7 @@ def chartmogul_source(initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume_config = resumable_source_manager.load_state()- if resume_config is not None:+ if resume_config is not None and resume_config.cursor:initial_paginator_state = {"cursor": resume_config.cursor}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:@@ -157,7 +188,7 @@ def chartmogul_source(if state and state.get("cursor"):resumable_source_manager.save_state(ChartMogulResumeConfig(cursor=str(state["cursor"])))- resource = rest_api_resource(+ return rest_api_resource(rest_config,team_id,job_id,@@ -166,10 +197,103 @@ def chartmogul_source(initial_paginator_state=initial_paginator_state,)++def _fanout_resource(+ config: ChartMogulEndpointConfig,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Iterable[Any]:+ assert config.fanout is not None+ parent_config = CHARTMOGUL_ENDPOINTS[config.fanout.parent_name]++ initial_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and (resume.completed or resume.current):+ initial_state = {+ "completed": resume.completed or [],+ "current": resume.current,+ "child_state": resume.child_state,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ ChartMogulResumeConfig(+ completed=state.get("completed"),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ return cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=CHARTMOGUL_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key, config.paginated),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ # No fan-out endpoint has a server-side time filter today, so this never selects+ # merge. Passing it anyway makes a future incremental child fail loudly for its+ # missing incremental_config_factory instead of quietly full-refreshing.+ should_use_incremental_field=should_use_incremental_field,+ parent_endpoint_extra={"data_selector": parent_config.data_key},+ child_endpoint_extra={"data_selector": config.data_key},+ page_size_param="per_page",+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )+++def chartmogul_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[ChartMogulResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CHARTMOGUL_ENDPOINTS[endpoint]++ resource: Iterable[Any]+ if config.fanout is not None:+ resource = _fanout_resource(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else:+ resource = _top_level_resource(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,partition_count=1,partition_size=1,partition_mode="datetime" if config.partition_key else None,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/settings.pyindex bc95fc5f1e4f..e0ee30bf989c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/settings.py@@ -1,25 +1,55 @@-from dataclasses import dataclass, field-from typing import Optional+from dataclasses import field+from typing import Any, Optional+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+DEFAULT_PAGE_SIZE = 200++# The metrics endpoints require an explicit `start-date`/`end-date` range, and ChartMogul+# publishes no earliest supported date. This floor predates ChartMogul itself, so it covers+# the imported billing history of any recurring-revenue business the product serves. An+# account with history before it loses those intervals, which is the price of a bounded+# request: the range is walked daily, so a much earlier floor only adds empty rows and+# server-side work. Lower it if a real account needs it.+METRICS_START_DATE = "2010-01-01"+# Daily intervals: a warehouse query can roll days up to months, but not the reverse.+METRICS_INTERVAL = "day"+-@dataclass+@frozenclass ChartMogulEndpointConfig:name: strpath: str# Body key the list of rows lives under (ChartMogul wraps results per resource:# customers/activities use "entries", plans use "plans", etc.).data_key: str- primary_key: str = "uuid"+ primary_keys: list[str] = field(default_factory=lambda: ["uuid"])incremental_fields: list[IncrementalField] = field(default_factory=list)# Stable field to partition by — must never change for a given row.partition_key: Optional[str] = None# Query param used to push the incremental cursor server-side. Only set for# endpoints with a genuine server-side date filter (today: activities).incremental_param: Optional[str] = None- # Some endpoints (data_sources) return the full list without pagination.+ # Some endpoints (data_sources, metrics) return the full list without pagination.paginated: bool = True+ page_size: int = DEFAULT_PAGE_SIZE+ # Static query params the endpoint requires on every request.+ extra_params: dict[str, Any] = field(default_factory=dict)+ # Metrics endpoints reject a request without a date range, so the window is built at+ # request time from METRICS_START_DATE to the sync date.+ requires_date_range: bool = False+ # Set where the endpoint is only reachable per parent record, so rows are collected by+ # iterating the parent listing first.+ fanout: Optional[DependentEndpointConfig] = None++ @property+ def default_incremental_field(self) -> Optional[str]:+ return self.incremental_fields[0]["field"] if self.incremental_fields else NoneCHARTMOGUL_ENDPOINTS: dict[str, ChartMogulEndpointConfig] = {@@ -27,34 +57,47 @@ CHARTMOGUL_ENDPOINTS: dict[str, ChartMogulEndpointConfig] = {name="customers",path="/v1/customers",data_key="entries",- primary_key="uuid",# Customers expose no update timestamp and no server-side date filter, so# full refresh is the only honest sync mode here.),+ "customer_subscriptions": ChartMogulEndpointConfig(+ name="customer_subscriptions",+ path="/v1/customers/{customer_uuid}/subscriptions",+ data_key="entries",+ # The subscription object carries no reference back to its customer, so the parent's+ # uuid is injected to make rows joinable and to key them uniquely across customers,+ # because the docs do not commit to `uuid` being unique outside its customer.+ primary_keys=["customer_uuid", "uuid"],+ # Every date on this object is hyphenated (`start-date`, `end-date`), which no+ # partition key in this source uses, so the table is left unpartitioned.+ fanout=DependentEndpointConfig(+ parent_name="customers",+ resolve_param="customer_uuid",+ resolve_field="uuid",+ include_from_parent=["uuid"],+ parent_field_renames={"uuid": "customer_uuid"},+ ),+ ),"plans": ChartMogulEndpointConfig(name="plans",path="/v1/plans",data_key="plans",- primary_key="uuid",),"plan_groups": ChartMogulEndpointConfig(name="plan_groups",path="/v1/plan_groups",data_key="plan_groups",- primary_key="uuid",),"invoices": ChartMogulEndpointConfig(name="invoices",path="/v1/invoices",data_key="invoices",- primary_key="uuid",partition_key="date",),"activities": ChartMogulEndpointConfig(name="activities",path="/v1/activities",data_key="entries",- primary_key="uuid",partition_key="date",# ChartMogul's Activities endpoint documents a server-side `start-date`# filter, so this is the one endpoint we can sync incrementally.@@ -72,10 +115,50 @@ CHARTMOGUL_ENDPOINTS: dict[str, ChartMogulEndpointConfig] = {name="data_sources",path="/v1/data_sources",data_key="data_sources",- primary_key="uuid",partition_key="created_at",paginated=False,),+ "subscription_events": ChartMogulEndpointConfig(+ name="subscription_events",+ path="/v1/subscription_events",+ data_key="subscription_events",+ # ChartMogul's own integer event id, not a uuid.+ primary_keys=["id"],+ partition_key="created_at",+ # ChartMogul omits disabled events by default. They are part of the transition+ # history and carry the `disabled` flag to filter on, so ask for them.+ extra_params={"with_disabled": "true"},+ # The only date params here (`event_date`, `effective_date`) match an exact+ # timestamp rather than a range, so there is nothing to bind a cursor to.+ ),+ "opportunities": ChartMogulEndpointConfig(+ name="opportunities",+ path="/v1/opportunities",+ data_key="entries",+ partition_key="created_at",+ # The only date filters are on `estimated_close_date`, which a deal can move in+ # either direction, so it cannot serve as an incremental cursor.+ ),+ "metrics": ChartMogulEndpointConfig(+ name="metrics",+ path="/v1/metrics/all",+ data_key="entries",+ primary_keys=["date"],+ partition_key="date",+ paginated=False,+ extra_params={"interval": METRICS_INTERVAL},+ requires_date_range=True,+ ),+ "metrics_mrr": ChartMogulEndpointConfig(+ name="metrics_mrr",+ path="/v1/metrics/mrr",+ data_key="entries",+ primary_keys=["date"],+ partition_key="date",+ paginated=False,+ extra_params={"interval": METRICS_INTERVAL},+ requires_date_range=True,+ ),}ENDPOINTS = tuple(CHARTMOGUL_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.py b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.pyindex 4159ccbdda0e..4213f60abfe6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/chartmogul/tests/test_chartmogul.py@@ -3,6 +3,7 @@ from datetime import UTC, date, datetimefrom typing import Anyimport pytest+import time_machinefrom unittest import mockfrom requests import Response@@ -13,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.chartmogulchartmogul_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.chartmogul.settings import METRICS_START_DATE# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -103,19 +105,25 @@ class TestFormatStartDate:class TestPagination:+ # subscription_events wraps its rows under its own resource name rather than "entries",+ # so it paginates through a different data selector.+ @pytest.mark.parametrize(+ "endpoint,data_key",+ [("customers", "entries"), ("subscription_events", "subscription_events")],+ )@mock.patch(CLIENT_SESSION_PATCH)- def test_paginates_across_cursors(self, MockSession) -> None:+ def test_paginates_across_cursors(self, MockSession, endpoint: str, data_key: str) -> None:session = MockSession.return_valueparams = _wire(session,[- _page("entries", [{"uuid": "a"}], has_more=True, cursor="c1"),- _page("entries", [{"uuid": "b"}]),+ _page(data_key, [{"uuid": "a"}], has_more=True, cursor="c1"),+ _page(data_key, [{"uuid": "b"}]),],)manager = _make_manager()- rows = _rows(_source("customers", manager))+ rows = _rows(_source(endpoint, manager))assert [r["uuid"] for r in rows] == ["a", "b"]assert params[0]["per_page"] == 200@@ -259,6 +267,11 @@ class TestChartmogulSource:("invoices", ["uuid"], "date"),("activities", ["uuid"], "date"),("data_sources", ["uuid"], "created_at"),+ ("customer_subscriptions", ["customer_uuid", "uuid"], None),+ ("subscription_events", ["id"], "created_at"),+ ("opportunities", ["uuid"], "created_at"),+ ("metrics", ["date"], "date"),+ ("metrics_mrr", ["date"], "date"),],)@mock.patch(CLIENT_SESSION_PATCH)@@ -276,3 +289,121 @@ class TestChartmogulSource:else:assert response.partition_keys is Noneassert response.partition_mode is None+++def _urls(session: mock.MagicMock) -> list[str]:+ return [call.args[0].url for call in session.prepare_request.call_args_list]+++class TestMetricsDateRange:+ @pytest.mark.parametrize("endpoint", ["metrics", "metrics_mrr"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_metrics_send_a_closed_daily_window(self, MockSession, endpoint: str) -> None:+ # The metrics endpoints reject a request without both bounds, so the window has to be+ # built at request time rather than declared.+ session = MockSession.return_value+ params = _wire(session, [_page("entries", [{"date": "2026-01-01", "mrr": 100}])])++ with time_machine.travel(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), tick=False):+ rows = _rows(_source(endpoint, _make_manager()))++ assert [r["date"] for r in rows] == ["2026-01-01"]+ assert params[0]["start-date"] == METRICS_START_DATE+ assert params[0]["end-date"] == "2026-03-04"+ assert params[0]["interval"] == "day"+ # Unpaginated, so a page-size param would be undocumented and the run is one request.+ assert "per_page" not in params[0]+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_other_endpoints_send_no_date_range(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_page("entries", [{"uuid": "a"}])])++ _rows(_source("opportunities", _make_manager()))++ assert "start-date" not in params[0]+ assert "end-date" not in params[0]+ assert "interval" not in params[0]+++class TestCustomerSubscriptionsFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_child_requests_are_bound_to_each_customer(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page("entries", [{"uuid": "cus_1"}, {"uuid": "cus_2"}]),+ _page("entries", [{"uuid": "sub_a"}]),+ _page("entries", [{"uuid": "sub_b"}]),+ ],+ )++ rows = _rows(_source("customer_subscriptions", _make_manager()))++ urls = _urls(session)+ assert urls[0] == "https://api.chartmogul.com/v1/customers"+ assert urls[1:] == [+ "https://api.chartmogul.com/v1/customers/cus_1/subscriptions",+ "https://api.chartmogul.com/v1/customers/cus_2/subscriptions",+ ]+ # The subscription object carries no customer reference of its own, so the parent uuid is+ # injected under the name the primary key is declared on.+ assert rows == [+ {"uuid": "sub_a", "customer_uuid": "cus_1"},+ {"uuid": "sub_b", "customer_uuid": "cus_2"},+ ]+ assert all(page["per_page"] == 200 for page in params)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_child_pages_follow_the_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _page("entries", [{"uuid": "cus_1"}]),+ _page("entries", [{"uuid": "sub_a"}], has_more=True, cursor="c1"),+ _page("entries", [{"uuid": "sub_b"}]),+ ],+ )++ rows = _rows(_source("customer_subscriptions", _make_manager()))++ assert [r["uuid"] for r in rows] == ["sub_a", "sub_b"]+ assert params[2]["cursor"] == "c1"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_the_customer_in_progress(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _page("entries", [{"uuid": "cus_1"}, {"uuid": "cus_2"}]),+ _page("entries", [{"uuid": "sub_b"}]),+ ],+ )++ manager = _make_manager(ChartMogulResumeConfig(completed=["/v1/customers/cus_1/subscriptions"]))+ rows = _rows(_source("customer_subscriptions", manager))++ # cus_1 was already fully synced before the crash, so only cus_2 is fetched again.+ assert _urls(session)[1:] == ["https://api.chartmogul.com/v1/customers/cus_2/subscriptions"]+ assert [r["uuid"] for r in rows] == ["sub_b"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_the_completed_customer(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _page("entries", [{"uuid": "cus_1"}]),+ _page("entries", [{"uuid": "sub_a"}]),+ ],+ )++ manager = _make_manager()+ _rows(_source("customer_subscriptions", manager))++ saved = manager.save_state.call_args_list[-1].args[0]+ assert saved.completed == ["/v1/customers/cus_1/subscriptions"]