: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 paddle explore metrics table (#119546)
Tom Owers310db2c480a0
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex ff6aad45b55a..626bc99c665c 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -858,7 +858,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/pabbly_subscriptions_billing/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/packagist/packagist.py1 products/warehouse_sources/backend/temporal/data_imports/sources/packagist/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py1 products/warehouse_sources/backend/temporal/data_imports/sources/pagerduty/pagerduty.py1 products/warehouse_sources/backend/temporal/data_imports/sources/pagerduty/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/pandadoc/pandadoc.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 947d27510941..e7e7a5d15a9f 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@@ -9063,6 +9063,16 @@ No material gaps found.Note: Packagist's public API is small and read-only. The source takes a user-supplied package/vendor list and already covers every per-package read endpoint: packages/{vendor}/{package}.json, the p2 metadata, stats.json, and /api/security-advisories. The only unexposed read endpoints are registry-wide rather than per-package: /explore/popular.json (top packages by weekly downloads), /statistics.json (global download total), /search.json, and /metadata/changes.json (a sync change feed, not warehouse data). None of these justify a table for a user tracking their own packages.+## Paddle — gaps++Today (8): `adjustments`, `customers`, `discounts`, `explore_metrics`, `prices`, `products`, `subscriptions`, `transactions`++Diffed against: <https://developer.paddle.com/api-reference/metrics/run-explore-metrics-query>++- [x] `Explore metrics (POST /metrics/explore, catalog from GET /metrics/explore/entities)` — daily revenue, transactions, refunds, chargebacks, and checkout conversion, plus monthly MRR and MRR growth, computed by Paddle (high)++Note: Added from the Explore metrics changelog (API version 1, 2026-08-27). The table holds account totals with no breakdown dimension. Querying it needs the `metrics.read` permission.+## PagerDuty — gapsToday (9): `escalation_policies`, `incidents`, `log_entries`, `priorities`, `schedules`, `services`, `teams`, `users`, `vendors`diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/canonical_descriptions.pyindex 79e6d1670ad8..fb885cf1bc3b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/canonical_descriptions.py@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.conADJUSTMENT_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,+ EXPLORE_METRICS_RESOURCE_NAME,PRICE_RESOURCE_NAME,PRODUCT_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,@@ -138,4 +139,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {payout_totals="Adjustment totals in your payout currency.",),},+ EXPLORE_METRICS_RESOURCE_NAME: {+ "description": (+ "Daily (monthly for subscriptions) account totals from Paddle Explore metrics: revenue, transactions, "+ "refunds, chargebacks, checkout conversion, MRR, and MRR growth. One row per entity, measure, and time bucket."+ ),+ "docs_url": "https://developer.paddle.com/api-reference/metrics/run-explore-metrics-query",+ "columns": {+ "entity": "Explore entity the measure comes from (e.g. transactions.completed, adjustments.refunds, checkouts, subscriptions).",+ "interval": "Time bucket size: day, or month for entities that only support monthly buckets.",+ "timestamp": "Start of the time bucket in UTC (RFC 3339); the incremental cursor.",+ "measure": "Measure name: {agg}_{field} (e.g. sum_gross_revenue, count_id), or the field name for derived measures (e.g. mrr, checkout_conversion).",+ "field": "Source field the measure is computed from. Empty for derived measures.",+ "agg": "Aggregation applied to the field: sum, count, or count_distinct. Empty for derived measures.",+ "value_type": "Value type of the measure: currency, integer, decimal, or string.",+ "value": "Measure value as a string. Currency values are in the smallest currency unit (e.g. cents).",+ "currency_code": "Three-letter ISO currency code for currency values, derived from your balance currency.",+ "updated_at": "Time at which Paddle last refreshed the data behind this metric (RFC 3339).",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/constants.pyindex 8dadf28e05d1..18dd5fad3d4f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/constants.py@@ -5,3 +5,4 @@ PRODUCT_RESOURCE_NAME = "products"SUBSCRIPTION_RESOURCE_NAME = "subscriptions"TRANSACTION_RESOURCE_NAME = "transactions"ADJUSTMENT_RESOURCE_NAME = "adjustments"+EXPLORE_METRICS_RESOURCE_NAME = "explore_metrics"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.pyindex 8b6d346cd670..9b32527d4b52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/paddle.py@@ -1,5 +1,6 @@import dataclasses-from datetime import UTC, date, datetime, time+from collections.abc import Iterator+from datetime import UTC, date, datetime, time, timedeltafrom typing import Any, Optionalimport requests@@ -12,27 +13,44 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,+ RESTClient,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuthfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponsePaginator,)from 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 SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.constants import (+ EXPLORE_METRICS_RESOURCE_NAME,+)from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.settings import (- ENDPOINTS,+ CREDENTIAL_CHECK_ENDPOINTS,INCREMENTAL_FIELDS,)PADDLE_BASE_URL = "https://api.paddle.com"PAGE_SIZE = 200+EXPLORE_ENTITIES_PATH = "metrics/explore/entities"+EXPLORE_QUERY_PATH = "metrics/explore"+EXPLORE_REQUEST_TIMEOUT = (10, 60)+EXPLORE_RETRY_BUDGET_SECONDS = 180+# Finest first. Each query covers one calendar month, so a weekly bucket would straddle two queries.+EXPLORE_INTERVALS = ("day", "month")++PROBE_PATHS = {EXPLORE_METRICS_RESOURCE_NAME: EXPLORE_ENTITIES_PATH}+[email protected](frozen=True)class PaddleResumeConfig:# Self-contained next-page URL from Paddle's `meta.pagination.next`. Empty once the sync is done.next_url: str = ""+ # Explore metrics: the month window and the entity to query next.+ explore_window_start: str = ""+ explore_entity: str = ""class PaddlePermissionError(Exception):@@ -97,6 +115,159 @@ def _get_paddle_session(api_key: str) -> requests.Session:)+def _explore_client(api_key: str) -> RESTClient:+ return RESTClient(+ base_url=PADDLE_BASE_URL,+ auth=BearerTokenAuth(token=api_key),+ request_timeout=EXPLORE_REQUEST_TIMEOUT,+ retry_budget_seconds=EXPLORE_RETRY_BUDGET_SECONDS,+ allowed_hosts=[],+ allow_redirects=False,+ )+++def _explore_measures(entity: dict[str, Any]) -> list[dict[str, str]]:+ measures: list[dict[str, str]] = []+ for measure in entity.get("measures") or []:+ aggs = measure.get("aggs")+ if aggs is None:+ measures.append({"field": measure["name"]})+ else:+ measures.extend({"field": measure["name"], "agg": agg} for agg in aggs)+ return measures+++def _next_month(day: date) -> date:+ return (day.replace(day=1) + timedelta(days=32)).replace(day=1)+++def _explore_rows(result: dict[str, Any]) -> list[dict[str, Any]]:+ measures = {measure["name"]: measure for measure in (result.get("fields") or {}).get("measures") or []}+ rows: list[dict[str, Any]] = []+ for series in result.get("series") or []:+ for point in series.get("timeseries") or []:+ timestamp = _format_paddle_datetime_query_value(point["timestamp"])+ for name, value in (point.get("measures") or {}).items():+ measure = measures.get(name, {})+ rows.append(+ {+ "entity": result.get("entity"),+ "interval": result.get("interval"),+ "timestamp": timestamp,+ "measure": name,+ "field": measure.get("field"),+ "agg": measure.get("agg"),+ "value_type": measure.get("type"),+ "value": None if value is None else str(value),+ "currency_code": result.get("currency_code"),+ "updated_at": result.get("updated_at"),+ }+ )+ return rows+++def _iter_explore_metrics(+ api_key: str,+ manager: ResumableSourceManager[PaddleResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool,+) -> Iterator[list[dict[str, Any]]]:+ client = _explore_client(api_key)+ try:+ catalog: list[dict[str, Any]] = []+ for page in client.paginate(path=EXPLORE_ENTITIES_PATH, data_selector="data", data_selector_required=True):+ catalog.extend(page)++ queries: list[tuple[str, str, list[dict[str, str]]]] = []+ lookback_days: list[int] = []+ for entity in sorted(catalog, key=lambda item: item["entity"]):+ time_dimension = entity.get("time_dimension") or {}+ interval = next((i for i in EXPLORE_INTERVALS if i in (time_dimension.get("intervals") or [])), None)+ measures = _explore_measures(entity)+ if interval is None or not measures:+ continue+ queries.append((entity["entity"], interval, measures))+ lookback_days.append(time_dimension["max_lookback_days"])+ if not queries:+ return++ today = datetime.now(UTC).date()+ # A day of margin keeps a query sent just after midnight UTC inside the lookback limit.+ earliest = today - timedelta(days=min(lookback_days) - 2)+ window = earliest if earliest.day == 1 else _next_month(earliest)+ if should_use_incremental_field and db_incremental_field_last_value:+ last_value = date.fromisoformat(_format_paddle_datetime_query_value(db_incremental_field_last_value)[:10])+ window = max(window, last_value.replace(day=1))++ resume_entity = ""+ resume = manager.load_state() if manager.can_resume() else None+ if resume is not None and resume.explore_window_start:+ window = date.fromisoformat(resume.explore_window_start)+ resume_entity = resume.explore_entity++ end = today + timedelta(days=1)+ while window < end:+ window_end = min(_next_month(window), end)+ for index, (entity_name, interval, measures) in enumerate(queries):+ if entity_name < resume_entity:+ continue+ manager.safe_point()+ body = {+ "entity": entity_name,+ "from": window.isoformat(),+ "to": window_end.isoformat(),+ "interval": interval,+ "measures": measures,+ }+ rows: list[dict[str, Any]] = []+ # With no breakdown dimension the result is a single series, so it fits on one page.+ for page in client.paginate(+ path=EXPLORE_QUERY_PATH, method="POST", json=body, data_selector="data", data_selector_required=True+ ):+ for result in page:+ rows.extend(_explore_rows(result))++ next_entity = queries[index + 1][0] if index + 1 < len(queries) else ""+ next_window = window if next_entity else window_end+ manager.save_state(+ PaddleResumeConfig(+ explore_window_start=next_window.isoformat() if next_window < end else "",+ explore_entity=next_entity,+ )+ )+ if rows:+ yield rows+ else:+ manager.safe_point()+ resume_entity = ""+ window = window_end+ finally:+ client.session.close()+++def paddle_explore_metrics_source(+ api_key: str,+ resumable_source_manager: ResumableSourceManager[PaddleResumeConfig],+ db_incremental_field_last_value: Optional[Any] = None,+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ return SourceResponse(+ items=lambda: _iter_explore_metrics(+ api_key, resumable_source_manager, db_incremental_field_last_value, should_use_incremental_field+ ),+ primary_keys=["entity", "interval", "measure", "timestamp"],+ name=EXPLORE_METRICS_RESOURCE_NAME,+ # Rows restart at the window start for each entity. Every window is one calendar month, and the+ # next run starts at the month that holds the watermark, so it re-reads the whole window.+ sort_mode="asc",+ partition_keys=["timestamp"],+ partition_mode="datetime",+ partition_count=1,+ partition_size=1,+ partition_format="month",+ )++def paddle_source(api_key: str,endpoint: str,@@ -106,6 +277,14 @@ def paddle_source(db_incremental_field_last_value: Optional[Any] = None,should_use_incremental_field: bool = False,) -> SourceResponse:+ if endpoint == EXPLORE_METRICS_RESOURCE_NAME:+ return paddle_explore_metrics_source(+ api_key,+ resumable_source_manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+column_mapping = get_dlt_mapping_for_external_table(f"paddle_{endpoint.lower()}")column_hints = {key: value.get("data_type") for key, value in column_mapping.items()}@@ -179,12 +358,12 @@ def paddle_source(def validate_credentials(api_key: str, table_name: Optional[str] = None) -> bool:- endpoints_to_check = [table_name] if table_name else ENDPOINTS+ endpoints_to_check = [table_name] if table_name else CREDENTIAL_CHECK_ENDPOINTSfor endpoint in endpoints_to_check:ok, status = validate_via_probe(lambda: _get_paddle_session(api_key),- f"{PADDLE_BASE_URL}/{endpoint}",+ f"{PADDLE_BASE_URL}/{PROBE_PATHS.get(endpoint, endpoint)}",)if status == 403:raise PaddlePermissionError(f"Missing permissions for {endpoint}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/settings.pyindex 4ab8303ec30a..328f91bf66db 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/settings.py@@ -2,6 +2,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.conADJUSTMENT_RESOURCE_NAME,CUSTOMER_RESOURCE_NAME,DISCOUNT_RESOURCE_NAME,+ EXPLORE_METRICS_RESOURCE_NAME,PRICE_RESOURCE_NAME,PRODUCT_RESOURCE_NAME,SUBSCRIPTION_RESOURCE_NAME,@@ -17,8 +18,16 @@ ENDPOINTS = [SUBSCRIPTION_RESOURCE_NAME,TRANSACTION_RESOURCE_NAME,ADJUSTMENT_RESOURCE_NAME,+ EXPLORE_METRICS_RESOURCE_NAME,]+# Explore metrics need the separate `metrics.read` permission, so the connection check skips them+# and a key without it can still sync the other tables.+CREDENTIAL_CHECK_ENDPOINTS = [endpoint for endpoint in ENDPOINTS if endpoint != EXPLORE_METRICS_RESOURCE_NAME]++# Paddle refreshes Explore data on a 24-hour cycle, so recent buckets can change after a sync.+EXPLORE_METRICS_LOOKBACK_SECONDS = 60 * 60 * 24 * 3+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {TRANSACTION_RESOURCE_NAME: [{@@ -28,4 +37,12 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {"field_type": IncrementalFieldType.DateTime,}],+ EXPLORE_METRICS_RESOURCE_NAME: [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.pyindex 8abd785ff798..1d2360b7a808 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/source.py@@ -21,6 +21,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.paddle import PaddleSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.constants import (+ EXPLORE_METRICS_RESOURCE_NAME,+)from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.paddle import (PaddlePermissionError,PaddleResumeConfig,@@ -30,6 +33,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.pad)from products.warehouse_sources.backend.temporal.data_imports.sources.paddle.settings import (ENDPOINTS as PADDLE_ENDPOINTS,+ EXPLORE_METRICS_LOOKBACK_SECONDS,INCREMENTAL_FIELDS as PADDLE_INCREMENTAL_FIELDS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -160,7 +164,12 @@ class PaddleSource(ResumableSource[PaddleSourceConfig, PaddleResumeConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(PADDLE_ENDPOINTS, PADDLE_INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(+ PADDLE_ENDPOINTS,+ PADDLE_INCREMENTAL_FIELDS,+ names,+ default_incremental_lookback_seconds={EXPLORE_METRICS_RESOURCE_NAME: EXPLORE_METRICS_LOOKBACK_SECONDS},+ )def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PaddleResumeConfig]:return ResumableSourceManager[PaddleResumeConfig](inputs, PaddleResumeConfig)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.pyindex c35e49073c9e..cbacc07b9128 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paddle/tests/test_paddle.py@@ -1,10 +1,13 @@+from collections.abc import Iteratorfrom datetime import datetimefrom typing import Anyimport pytest+import time_machinefrom unittest import mockfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,ScriptedResponse,SourceDriver,always,@@ -46,6 +49,58 @@ def _response(return ScriptedResponse(json=body)+EXPLORE_CATALOG = [+ {+ "entity": "transactions.completed",+ "time_dimension": {"intervals": ["day", "week", "month"], "max_lookback_days": 1096},+ "dimensions": [],+ "measures": [+ {"name": "gross_revenue", "type": "currency", "aggs": ["sum"]},+ {"name": "id", "type": "string", "aggs": ["count"]},+ ],+ },+ {+ "entity": "subscriptions",+ "time_dimension": {"intervals": ["month"], "max_lookback_days": 70},+ "dimensions": [],+ "measures": [{"name": "mrr", "type": "currency", "aggs": None}],+ },+]+++def _explore_network(request: RecordedRequest) -> ScriptedResponse:+ if request.path.endswith("/metrics/explore/entities"):+ return ScriptedResponse(json={"data": EXPLORE_CATALOG})+ body = request.json()+ measures = [+ {"name": f"{m['agg']}_{m['field']}" if "agg" in m else m["field"], "type": "currency", **m}+ for m in body["measures"]+ ]+ return ScriptedResponse(+ json={+ "data": {+ "entity": body["entity"],+ "interval": body["interval"],+ "currency_code": "USD",+ "updated_at": "2026-08-20T06:00:00Z",+ "fields": {"dimensions": [], "measures": measures},+ "series": [+ {+ "dimensions": {},+ "timeseries": [{"timestamp": body["from"], "measures": {m["name"]: "100" for m in measures}}],+ }+ ],+ },+ "meta": {"pagination": {"per_page": 5, "next": None, "has_more": False, "estimated_total": 1}},+ }+ )+++def _explore_queries(result: Any) -> list[tuple[str, str, str, str]]:+ bodies = [request.json() for request in result.requests if request.method == "POST"]+ return [(body["entity"], body["interval"], body["from"], body["to"]) for body in bodies]++def _driver() -> SourceDriver:return SourceDriver(PaddleSource(), PaddleSourceConfig(paddle_api_key="key"))@@ -86,6 +141,70 @@ class TestIncremental:assert result.requests[0].param("billed_at[GT]") == "2024-01-02T03:04:05Z"+class TestExploreMetrics:+ @pytest.fixture(autouse=True)+ def _frozen_clock(self) -> Iterator[None]:+ with time_machine.travel("2026-08-20T12:00:00Z", tick=False):+ yield++ @pytest.mark.parametrize(+ "inputs, expected_queries",+ [+ (+ # The shortest lookback (70 days) bounds every entity, rounded up to the next month start.+ {},+ [+ ("subscriptions", "month", "2026-07-01", "2026-08-01"),+ ("transactions.completed", "day", "2026-07-01", "2026-08-01"),+ ("subscriptions", "month", "2026-08-01", "2026-08-21"),+ ("transactions.completed", "day", "2026-08-01", "2026-08-21"),+ ],+ ),+ (+ {"should_use_incremental_field": True, "db_incremental_field_last_value": "2026-08-02T00:00:00Z"},+ [+ ("subscriptions", "month", "2026-08-01", "2026-08-21"),+ ("transactions.completed", "day", "2026-08-01", "2026-08-21"),+ ],+ ),+ ],+ )+ def test_queries_each_entity_per_calendar_month(+ self, inputs: dict[str, Any], expected_queries: list[tuple[str, str, str, str]]+ ) -> None:+ result = _driver().run("explore_metrics", _explore_network, **inputs)++ assert result.raised is None+ assert _explore_queries(result) == expected_queries+ posts = [request.json() for request in result.requests if request.method == "POST"]+ assert posts[0]["measures"] == [{"field": "mrr"}]+ assert posts[1]["measures"] == [{"field": "gross_revenue", "agg": "sum"}, {"field": "id", "agg": "count"}]+ assert {+ "entity": "transactions.completed",+ "interval": "day",+ "timestamp": f"{expected_queries[1][2]}T00:00:00Z",+ "measure": "sum_gross_revenue",+ "field": "gross_revenue",+ "agg": "sum",+ "value_type": "currency",+ "value": "100",+ "currency_code": "USD",+ "updated_at": "2026-08-20T06:00:00Z",+ } in result.rows+ assert len(result.rows) == 3 * len(expected_queries) // 2+ assert result.saved_states[-1] == PaddleResumeConfig()++ def test_resume_continues_at_saved_window_and_entity(self) -> None:+ result = _driver().run(+ "explore_metrics",+ _explore_network,+ resume_state=PaddleResumeConfig(explore_window_start="2026-08-01", explore_entity="transactions.completed"),+ )++ assert result.raised is None+ assert _explore_queries(result) == [("transactions.completed", "day", "2026-08-01", "2026-08-21")]++class TestResume:def test_checkpoint_saved_on_last_page_terminates_on_resume(self) -> None:# A checkpoint saved while looping on the final page points at that page.@@ -111,6 +230,22 @@ class TestValidateCredentials:validate_credentials("key")assert network.requests_log[0].headers["authorization"] == "Bearer key"+ @pytest.mark.parametrize(+ "table_name, expected_paths",+ [+ # A key without `metrics.read` must still connect, so the create-time check skips Explore.+ (+ None,+ ["/customers", "/discounts", "/prices", "/products", "/subscriptions", "/transactions", "/adjustments"],+ ),+ ("explore_metrics", ["/metrics/explore/entities"]),+ ],+ )+ def test_probed_paths(self, table_name: str | None, expected_paths: list[str]) -> None:+ with scripted_network(always(ScriptedResponse(status=200))) as network:+ assert validate_credentials("key", table_name) is True+ assert [request.path for request in network.requests_log] == expected_paths+def test_transport_failure_is_not_a_rejected_key(self) -> None:with scripted_network(always(ConnectionError("boom"))):with pytest.raises(PaddleUnreachableError):