: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(warehouse-sources): sync Metronome plans and usage (#92733)
posthog[bot]fd1397765167
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.pyindex 7abac689b54c..ffce42a88e65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py@@ -151,6 +151,29 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"is_currency": "Whether the unit is a fiat currency rather than a custom credit type.",},},+ "plans": {+ "description": "Plans are Metronome's original way to price a customer. This table lists the plans defined in your account, with each plan's name, description, and custom fields. Metronome has deprecated plans in favor of contracts. It holds plan definitions only, not which customer is on which plan, so it does not by itself link a plan to a customer or an invoice.",+ "docs_url": "https://docs.metronome.com/api-reference/plans/list-plans",+ "columns": {+ "id": "The plan's id.",+ "name": "The plan's display name.",+ "description": "The plan's description.",+ "custom_fields": "Arbitrary key/value pairs set on the plan by your account.",+ },+ },+ "usage": {+ "description": "Aggregated usage per customer and billable metric, across every customer in the account. Each row is one lifetime total for a customer/metric pair, because the sync asks Metronome for a single aggregate over the whole period rather than a per-day or per-hour breakdown.",+ "docs_url": "https://docs.metronome.com/api-reference/usage/get-batched-usage-data",+ "columns": {+ "customer_id": "The customer the usage belongs to.",+ "billable_metric_id": "The billable metric the usage was measured against.",+ "billable_metric_name": "The billable metric's display name.",+ "start_timestamp": "Start of the aggregation window. The sync starts it at the epoch, so it covers all usage.",+ "end_timestamp": "End of the aggregation window, set to the time the sync ran.",+ "value": "The aggregated usage amount for the customer and metric. Null when no usage matched.",+ "groups": "Usage broken down by group key. Empty, because the sync requests no group breakdown.",+ },+ },"audit_logs": {"description": "One row per change made through the Metronome app or API: who did it, to what, and whether it succeeded. This is the only Metronome endpoint with a server-side time filter, so it is the only table that syncs incrementally.","docs_url": "https://docs.metronome.com/api-reference/security/get-audit-logs",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.pyindex 6f51430350bf..252226112063 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py@@ -1,5 +1,6 @@import dataclassesfrom collections.abc import Callable, Iterable, Iterator+from datetime import UTC, datetimefrom typing import Any, Optional, castfrom requests import Request, Response@@ -53,9 +54,14 @@ EPOCH_RFC_3339 = "1970-01-01T00:00:00Z"@frozenclass MetronomeResumeConfig:- """Paginator checkpoint — the `next_page` cursor of the page we have not yet fetched."""+ """Paginator checkpoint — the `next_page` cursor of the page we have not yet fetched, plus the+ request window that cursor belongs to."""next_page: str+ # For a window-body endpoint (`usage`), the `ending_before` cutoff pinned at the walk's start.+ # A resumed attempt replays it instead of recomputing from the clock, so one table never mixes+ # rows aggregated to two different cutoffs. None for endpoints that send no window.+ ending_before: str | None = Noneclass MetronomeCursorPaginator(JSONResponseCursorPaginator):@@ -164,6 +170,7 @@ def get_resource(endpoint: str,should_use_incremental_field: bool,incremental_field_name: str | None = None,+ window_ending_before: str | None = None,) -> EndpointResource:config = METRONOME_ENDPOINTS[endpoint]if config.fanout or config.body_fanout:@@ -182,7 +189,16 @@ def get_resource(# The POST list endpoints take their filters as a body. Two of them accept no filters at all,# and still expect a JSON document rather than an empty request.if config.method == "post":- endpoint_config["json"] = dict(config.json_body)+ json_body = dict(config.json_body)+ if config.window_body:+ # `starting_on` at the epoch means "all usage the account has". `ending_before` is the+ # sync time; the caller pins it for the whole walk so a resumed attempt replays the same+ # cutoff, and this falls back to now only for a one-shot build with no pinned window.+ json_body["starting_on"] = EPOCH_RFC_3339+ json_body["ending_before"] = (+ window_ending_before if window_ending_before is not None else _format_rfc3339(datetime.now(UTC))+ )+ endpoint_config["json"] = json_bodyincremental = _incremental_window(config, incremental_field_name or config.default_incremental_field or "")use_incremental = should_use_incremental_field and incremental is not None@@ -232,6 +248,7 @@ def _body_fanout_pages(client: RESTClient, config: MetronomeEndpointConfig) -> Idef _make_source_response(config: MetronomeEndpointConfig,items_fn: Callable[[], Iterable[Any]],+ chunk_size: int | None = None,) -> SourceResponse:# `audit_logs` is the only table that syncs incrementally, and it pins `sort=date_asc`, so the# default ascending `sort_mode` matches the order rows actually arrive in. Metronome documents@@ -245,6 +262,7 @@ def _make_source_response(partition_mode="datetime" if config.partition_key else None,partition_format="month" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,+ chunk_size=chunk_size,)@@ -297,28 +315,51 @@ def metronome_source()return _make_source_response(endpoint_config, lambda: dependent_resource)+ # Load resume state before building the resource. A window-body endpoint (`usage`) pins its+ # `ending_before` cutoff for the whole walk, and a resumed attempt has to replay the cutoff its+ # checkpoint stored. Recomputing the cutoff each attempt would pair an old cursor with a later+ # window and mix two snapshots in one table.+ resume_config: Optional[MetronomeResumeConfig] = None+ if resumable_source_manager is not None and resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()++ window_ending_before: str | None = None+ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume_config is not None and resumable_source_manager is not None:+ # A checkpoint written before the cutoff was stored carries none. Restart the walk rather+ # than replay its stale cursor against a freshly computed window.+ stale_pre_window_checkpoint = endpoint_config.window_body and resume_config.ending_before is None+ if stale_pre_window_checkpoint:+ # The pipeline reads the resume key itself after this returns, so skipping the stale+ # cursor here is not enough — a lingering key makes it treat the restarted walk as a+ # resume and append onto the partial `replace` table. Drop the key so the restart is a+ # clean full refresh.+ resumable_source_manager.clear_state()+ else:+ initial_paginator_state = {"cursor": resume_config.next_page}+ window_ending_before = resume_config.ending_before+ if endpoint_config.window_body and window_ending_before is None:+ window_ending_before = _format_rfc3339(datetime.now(UTC))+config: RESTAPIConfig = {"client": _rest_api_client_config(api_key),"resource_defaults": {},- "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field, window_ending_before)],}- initial_paginator_state: Optional[dict[str, Any]] = Noneresume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = Noneif resumable_source_manager is not None:- if resumable_source_manager.can_resume():- resume_config = resumable_source_manager.load_state()- if resume_config is not None:- initial_paginator_state = {"cursor": resume_config.next_page}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only while there is another page to resume to; the Redis TTL cleans up on- # completion.+ # completion. The pinned window rides along so a resumed attempt replays it.if resumable_source_manager is None or not state:returncursor = state.get("cursor")if cursor:- resumable_source_manager.save_state(MetronomeResumeConfig(next_page=str(cursor)))+ resumable_source_manager.save_state(+ MetronomeResumeConfig(next_page=str(cursor), ending_before=window_ending_before)+ )resume_hook = save_checkpoint@@ -330,7 +371,13 @@ def metronome_source(resume_hook=resume_hook,initial_paginator_state=initial_paginator_state,)- return _make_source_response(endpoint_config, lambda: resource)+ # The resume checkpoint advances after every yielded page — rest_client fires the resume hook+ # right after each yield — so each page has to reach Delta before the bookmark moves past it.+ # Each yielded item is already a whole API page, so chunk_size=1 flushes it on its own rather+ # than letting several pages sit in the batcher's buffer; a mid-sync worker shutdown would+ # otherwise resume past the buffered pages and finish the full-refresh table with silent gaps.+ # The fan-out tables above don't resume, so they keep the default and avoid a commit per page.+ return _make_source_response(endpoint_config, lambda: resource, chunk_size=1)def validate_credentials(api_key: str) -> tuple[bool, str | None]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.pyindex 83f9175f8fd6..df0bbbcde45b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py@@ -60,6 +60,10 @@ class MetronomeEndpointConfig:page_size: int = PAGE_SIZEfanout: DependentEndpointConfig | None = Nonebody_fanout: BodyFanoutConfig | None = None+ # `POST /v1/usage` needs a `starting_on`/`ending_before` window in its body. The window is+ # computed per run — `ending_before` is the sync time — so it can't live in the static+ # `json_body`. When set, the resource builder fills the window in.+ window_body: bool = False# Customer-scoped children bind the parent's `id` into their path as `customer_id`. Every child@@ -138,6 +142,25 @@ METRONOME_ENDPOINTS: dict[str, MetronomeEndpointConfig] = {path="/v1/credit-types/list",primary_key=["id"],),+ "plans": MetronomeEndpointConfig(+ name="plans",+ path="/v1/plans",+ primary_key=["id"],+ # Deprecated by Metronome in favor of contracts, but still the only place a customer's+ # plan is named. No created/updated filter, so every run reads the whole list.+ ),+ "usage": MetronomeEndpointConfig(+ name="usage",+ path="/v1/usage",+ method="post",+ # One aggregate per customer and billable metric — the endpoint carries no row id.+ primary_key=["customer_id", "billable_metric_id"],+ # `none` returns a single lifetime aggregate per customer/metric, so the row count stays+ # bounded by the account. `day`/`hour` would segment the whole window into one row per+ # period and, from the epoch start below, produce an unbounded table.+ json_body={"window_size": "none"},+ window_body=True,+ ),"audit_logs": MetronomeEndpointConfig(name="audit_logs",path="/v1/auditLogs",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.pyindex 083381569c81..b6085f16c657 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resSinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome import (+ EPOCH_RFC_3339,MetronomeCursorPaginator,MetronomeResumeConfig,_format_rfc3339,@@ -116,7 +117,7 @@ class TestMetronomeResources:assert "incremental" not in resource["endpoint"]assert "starting_on" not in resource["endpoint"]["params"]- @parameterized.expand([("customers",), ("products",), ("packages",), ("billable_metrics",)])+ @parameterized.expand([("customers",), ("products",), ("packages",), ("billable_metrics",), ("plans",), ("usage",)])def test_endpoints_without_a_time_filter_never_go_incremental(self, endpoint) -> None:# Metronome exposes no created/updated filter on these, so an "incremental" sync would# still fetch every page and cost the same as a full refresh.@@ -145,6 +146,17 @@ class TestMetronomeResources:with pytest.raises(ValueError, match="Fan-out endpoint"):get_resource(endpoint, should_use_incremental_field=False)+ def test_usage_resource_sends_the_full_window_in_the_body(self) -> None:+ # `POST /v1/usage` rejects the request unless the body carries `window_size`, `starting_on`+ # and `ending_before`. `ending_before` is the sync time, so it can't be a static default.+ resource = cast(dict[str, Any], get_resource("usage", should_use_incremental_field=False))++ assert resource["endpoint"]["method"] == "post"+ body = resource["endpoint"]["json"]+ assert body["window_size"] == "none"+ assert body["starting_on"] == EPOCH_RFC_3339+ assert body["ending_before"] > EPOCH_RFC_3339+class TestMetronomeSourceResponse:@parameterized.expand(@@ -152,6 +164,8 @@ class TestMetronomeSourceResponse:("customers", ["id"], "created_at"),("audit_logs", ["id"], "timestamp"),("pricing_units", ["id"], None),+ ("plans", ["id"], None),+ ("usage", ["customer_id", "billable_metric_id"], None),])@patch(f"{TRANSPORT}.rest_api_resource")@@ -160,6 +174,9 @@ class TestMetronomeSourceResponse:assert response.primary_keys == primary_keysassert response.partition_keys == ([partition_key] if partition_key else None)+ # Each of these tables walks the resume path, whose checkpoint advances per page, so the+ # batcher must flush one page at a time or a resumed sync appends past unflushed pages.+ assert response.chunk_size == 1@patch(f"{TRANSPORT}.rest_api_resource")def test_resume_state_seeds_the_paginator_cursor(self, mock_rest_api_resource) -> None:@@ -173,6 +190,63 @@ class TestMetronomeSourceResponse:assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"cursor": "cursor-9"}+ @parameterized.expand(+ [+ # Stored a cutoff: replay that exact window and resume from its cursor, keeping the key.+ (+ "with_stored_window",+ MetronomeResumeConfig(next_page="cursor-9", ending_before="2020-06-01T00:00:00Z"),+ "2020-06-01T00:00:00Z",+ {"cursor": "cursor-9"},+ False,+ ),+ # A checkpoint written before the cutoff was stored carries none, so the walk restarts+ # with a fresh window and no seeded cursor rather than mixing two windows. The stale key+ # is cleared so the pipeline's own resume probe doesn't append onto the partial table.+ ("pre_window_checkpoint", MetronomeResumeConfig(next_page="cursor-9"), None, None, True),+ ]+ )+ @patch(f"{TRANSPORT}.rest_api_resource")+ def test_resumed_usage_run_pins_the_window(+ self,+ _name,+ resume_state,+ expected_window,+ expected_paginator_state,+ expect_state_cleared,+ mock_rest_api_resource,+ ) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = resume_state++ metronome_source(api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager)++ body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]+ if expected_window is not None:+ assert body["ending_before"] == expected_window+ else:+ assert body["ending_before"] > EPOCH_RFC_3339+ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == expected_paginator_state+ assert manager.clear_state.called == expect_state_cleared++ @patch(f"{TRANSPORT}.rest_api_resource")+ def test_usage_checkpoint_saves_the_window_it_synced_with(self, mock_rest_api_resource) -> None:+ # The cutoff written into the request body and the cutoff saved for a resume must be the+ # same instant, or a retry can't replay the identical window.+ manager = MagicMock()+ manager.can_resume.return_value = False++ metronome_source(api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager)++ synced_window = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]["ending_before"]+ save_checkpoint = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ save_checkpoint({"cursor": "cursor-3"})++ manager.save_state.assert_called_once_with(+ MetronomeResumeConfig(next_page="cursor-3", ending_before=synced_window)+ )+@patch(f"{TRANSPORT}.build_dependent_resource")def test_invoices_fan_out_over_customers(self, mock_build) -> None:mock_build.return_value = iter([])@@ -208,6 +282,9 @@ class TestMetronomeBodyFanout:[{"id": "contract_1", "customer_id": "cust_1"}],[{"id": "contract_2", "customer_id": "cust_2"}],]+ # Fan-out tables don't resume, so they keep the default chunk size — a per-page flush here+ # would cost a Delta commit per page on the largest tables for no durability gain.+ assert response.chunk_size is Nonechild_calls = client.paginate.call_args_list[1:]assert [call.kwargs["json"] for call in child_calls] == [{"include_archived": True, "customer_id": "cust_1"},