: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 usage per day and hour (#94510)
Daniel RC683f3d691a32
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.pyindex 0e56eeeb10d7..b504104d0590 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/base.py@@ -187,6 +187,14 @@ class _BaseSource(ABC, Generic[ConfigType]):# See `sources/common/history_window.py`.history_lookback: datetime.timedelta | None = None+ def history_lookback_for_schema(self, schema_name: str) -> datetime.timedelta | None:+ """How far back a first sync of one schema reaches, or None for no bound.++ Override when tables of one source need different bounds, for example a daily and an hourly+ rollup of the same data, where the hourly table holds 24 rows for every daily row.+ """+ return self.history_lookback+@property@abstractmethoddef source_type(self) -> ExternalDataSourceType:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.pyindex 6946c0557c96..9916a8116256 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/history_window.py@@ -45,7 +45,7 @@ def history_start_for_schema(logger.warning("history_window.unknown_source_type", source_type=schema.source.source_type)return None- lookback = source.history_lookback+ lookback = source.history_lookback_for_schema(schema.name)if lookback is None:return Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.pyindex 37ed533c42d2..ae323fa71daf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_history_window.py@@ -137,3 +137,27 @@ def test_a_declared_window_is_reachable_through_the_registry(source_type: str) -lookback = SourceRegistry.get_source(ExternalDataSourceType(source_type)).history_lookbackassert lookback == dt.timedelta(days=2 * 365)+++def test_a_source_that_declares_one_window_bounds_every_schema_the_same() -> None:+ # Resolving the window per schema must keep answering with the declared one for the sources+ # that bound their whole catalog together.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+ from products.warehouse_sources.backend.types import ExternalDataSourceType++ source = SourceRegistry.get_source(ExternalDataSourceType("GoogleAds"))++ assert source.history_lookback_for_schema("campaign_stats") == source.history_lookback+++def test_a_source_can_bound_some_of_its_schemas_and_not_others() -> None:+ # Metronome bounds only the usage tables holding one row per period. Its other tables read+ # lists the account already bounds, so recording a range for them would declare away the rest.+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+ from products.warehouse_sources.backend.types import ExternalDataSourceType++ source = SourceRegistry.get_source(ExternalDataSourceType("Metronome"))++ assert source.history_lookback_for_schema("usage_daily") == dt.timedelta(days=365)+ assert source.history_lookback_for_schema("usage_hourly") == dt.timedelta(days=30)+ assert source.history_lookback_for_schema("usage") is Nonediff --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 ffce42a88e65..3757f8c4a955 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@@ -162,7 +162,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {},},"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.",+ "description": "Aggregated usage per customer and billable metric, across every customer in the account. Each row is one lifetime total for a customer and metric pair. To see how much a customer used inside a period, sync the usage_daily or usage_hourly table instead.","docs_url": "https://docs.metronome.com/api-reference/usage/get-batched-usage-data","columns": {"customer_id": "The customer the usage belongs to.",@@ -174,8 +174,34 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"groups": "Usage broken down by group key. Empty, because the sync requests no group breakdown.",},},+ "usage_daily": {+ "description": "Usage per customer, billable metric and day, across every customer in the account. Use it to track what a customer consumed inside a billing period, or to chart usage over time. The first sync covers the last 365 days, and later syncs add each new day. The day in progress is included, and every sync updates it. Metronome accepts usage events backdated up to 34 days, so to keep earlier days up to date as well, set a lookback window in the table's sync settings.",+ "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 day this row covers, in UTC.",+ "end_timestamp": "End of the day this row covers.",+ "value": "The usage total for this customer, metric and day. Null when no usage matched.",+ "groups": "Usage broken down by group key. Empty, because the sync requests no group breakdown.",+ },+ },+ "usage_hourly": {+ "description": "Usage per customer, billable metric and hour, across every customer in the account. It answers the same questions as the daily table at a finer grain, which helps when you need to see spikes inside a day. It holds 24 times as many rows, so the first sync covers the last 30 days rather than a year. The hour in progress is included, and every sync updates it. Metronome accepts usage events backdated up to 34 days, so to keep earlier hours up to date as well, set a lookback window in the table's sync settings.",+ "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 hour this row covers, in UTC.",+ "end_timestamp": "End of the hour this row covers.",+ "value": "The usage total for this customer, metric and hour. 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.",+ "description": "One row per change made through the Metronome app or API: who did it, to what, and whether it succeeded. It is the only Metronome list endpoint with a server-side time filter, so each sync reads only the entries recorded since the last one.","docs_url": "https://docs.metronome.com/api-reference/security/get-audit-logs","columns": {"id": "The audit log entry's id.",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 252226112063..042da11c0993 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,7 +1,7 @@import dataclassesfrom collections.abc import Callable, Iterable, Iteratorfrom datetime import UTC, datetime-from typing import Any, Optional, cast+from typing import Any, Literal, Optional, castfrom requests import Request, Response@@ -9,6 +9,7 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (coerce_datetime_to_utc,+ parse_datetime_value,)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 (@@ -40,6 +41,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.DATA_SELECTOR,METRONOME_BASE_URL,METRONOME_ENDPOINTS,+ USAGE_HISTORY,MetronomeEndpointConfig,)@@ -58,10 +60,13 @@ class MetronomeResumeConfig: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.+ # For a windowed endpoint, 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 = None+ # The `starting_on` bound of the same request. A bucketed table resolves it against the clock+ # when the schema recorded no range, so it is pinned for the walk for the same reason.+ starting_on: str | None = Noneclass MetronomeCursorPaginator(JSONResponseCursorPaginator):@@ -128,6 +133,95 @@ def _incremental_window(config: MetronomeEndpointConfig, cursor_path: str) -> In}+def _align_to_window(value: datetime, window_size: Literal["hour", "day"]) -> datetime:+ """Floor a window bound to the boundary Metronome aggregates on.++ A period's `start_timestamp` is part of the table's primary key, and the bound this run asks+ from is the watermark shifted back by a lookback the user sets in seconds, so it usually lands+ mid-period. Asking from mid-period risks a partial aggregate for a period the table already+ holds in full, which then upserts as a second row instead of replacing the first.+ """+ if window_size == "day":+ return value.replace(hour=0, minute=0, second=0, microsecond=0)+ return value.replace(minute=0, second=0, microsecond=0)+++def _resolve_window_start(+ config: MetronomeEndpointConfig,+ db_incremental_field_last_value: Any,+ history_start: datetime | None,+) -> str:+ """Where the requested usage window begins.++ The lifetime table asks for everything the account has. A bucketed table starts at the period+ its watermark reached, so each run asks only for what it does not already hold. With no+ watermark it starts where the schema recorded its range on the first sync, and resolves the+ table's own bound against the clock only when no range was recorded.+ """+ window_size = config.window_size+ if window_size != "hour" and window_size != "day":+ return EPOCH_RFC_3339++ start = (+ parse_datetime_value(db_incremental_field_last_value)+ or coerce_datetime_to_utc(history_start)+ or datetime.now(UTC) - USAGE_HISTORY[config.name]+ )+ return _format_rfc3339(_align_to_window(start, window_size))+++@frozen+class MetronomeWalkStart:+ """Where one walk of an endpoint begins: the request window, and the cursor to resume from."""++ starting_on: str | None = None+ ending_before: str | None = None+ paginator_state: dict[str, Any] | None = None+++def _walk_start(+ config: MetronomeEndpointConfig,+ resumable_source_manager: "Optional[ResumableSourceManager[MetronomeResumeConfig]]",+ db_incremental_field_last_value: Any,+ history_start: datetime | None,+) -> MetronomeWalkStart:+ """Read the resume checkpoint, then fill in whatever it did not carry.++ A windowed endpoint pins its request window for the whole walk, and a resumed attempt has to+ replay the window its checkpoint stored. Recomputing the window 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()++ starting_on: str | None = None+ ending_before: str | None = None+ paginator_state: dict[str, Any] | None = 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.+ if config.window_size is not None and resume_config.ending_before is None:+ # 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:+ paginator_state = {"cursor": resume_config.next_page}+ ending_before = resume_config.ending_before+ starting_on = resume_config.starting_on++ if config.window_size is not None:+ if ending_before is None:+ ending_before = _format_rfc3339(datetime.now(UTC))+ if starting_on is None:+ starting_on = _resolve_window_start(config, db_incremental_field_last_value, history_start)++ return MetronomeWalkStart(starting_on=starting_on, ending_before=ending_before, paginator_state=paginator_state)++def _rest_api_client_config(api_key: str) -> ClientConfig:return {"base_url": METRONOME_BASE_URL,@@ -171,10 +265,15 @@ def get_resource(should_use_incremental_field: bool,incremental_field_name: str | None = None,window_ending_before: str | None = None,+ window_starting_on: str | None = None,) -> EndpointResource:config = METRONOME_ENDPOINTS[endpoint]if config.fanout or config.body_fanout:raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")+ # Falling back to the epoch here would ask for every period the account has ever had, which is+ # the one thing the bound on these tables exists to prevent.+ if config.window_size in ("hour", "day") and window_starting_on is None:+ raise ValueError(f"Bucketed usage endpoint '{endpoint}' needs a resolved 'starting_on'")endpoint_config: Endpoint = {"path": config.path,@@ -190,25 +289,30 @@ def get_resource(# and still expect a JSON document rather than an empty request.if config.method == "post":json_body = dict(config.json_body)- if config.window_body:+ if config.window_size is not None:# `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+ # sync time; the caller pins both for the whole walk so a resumed attempt replays the+ # same window, and these fall back only for a one-shot build with no pinned window.+ json_body["window_size"] = config.window_size+ json_body["starting_on"] = window_starting_on if window_starting_on is not None else EPOCH_RFC_3339json_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- if use_incremental:+ if should_use_incremental_field and incremental is not None:endpoint_config["incremental"] = cast(IncrementalConfig, incremental)+ # A bucketed usage table syncs incrementally with no framework-injected param: its window lives+ # in the request body, which `_incremental_window` cannot reach. So the write disposition+ # follows the endpoint declaring a cursor field rather than the injected param.+ syncs_incrementally = should_use_incremental_field and bool(config.incremental_fields)+return {"name": config.name,"table_name": config.name,- "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if syncs_incrementally else "replace","endpoint": endpoint_config,"table_format": "delta",}@@ -250,9 +354,10 @@ def _make_source_response(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- # no order for the rest, and none of them checkpoint a watermark.+ # `audit_logs` pins `sort=date_asc`, so the default ascending `sort_mode` matches the order its+ # rows arrive in. The bucketed usage tables declare "desc" instead, because their rows arrive+ # grouped by customer rather than by period. Metronome documents no order for the rest, and+ # none of them checkpoint a watermark.return SourceResponse(name=config.name,items=items_fn,@@ -262,6 +367,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,+ sort_mode=config.sort_mode,chunk_size=chunk_size,)@@ -275,6 +381,7 @@ def metronome_source(should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,+ history_start: Optional[datetime] = None,) -> SourceResponse:endpoint_config = METRONOME_ENDPOINTS[endpoint]@@ -315,36 +422,20 @@ 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))+ walk = _walk_start(endpoint_config, resumable_source_manager, db_incremental_field_last_value, history_start)config: RESTAPIConfig = {"client": _rest_api_client_config(api_key),"resource_defaults": {},- "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field, window_ending_before)],+ "resources": [+ get_resource(+ endpoint,+ should_use_incremental_field,+ incremental_field,+ walk.ending_before,+ walk.starting_on,+ )+ ],}resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None@@ -358,7 +449,11 @@ def metronome_source(cursor = state.get("cursor")if cursor:resumable_source_manager.save_state(- MetronomeResumeConfig(next_page=str(cursor), ending_before=window_ending_before)+ MetronomeResumeConfig(+ next_page=str(cursor),+ ending_before=walk.ending_before,+ starting_on=walk.starting_on,+ ))resume_hook = save_checkpoint@@ -369,7 +464,7 @@ def metronome_source(job_id,db_incremental_field_last_value,resume_hook=resume_hook,- initial_paginator_state=initial_paginator_state,+ initial_paginator_state=walk.paginator_state,)# 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.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 df0bbbcde45b..50af1a602237 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@@ -1,10 +1,12 @@from dataclasses import dataclass, field+from datetime import timedeltafrom typing import Any, Literalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalFieldMETRONOME_BASE_URL = "https://api.metronome.com"@@ -21,6 +23,22 @@ CURSOR_PARAM = "next_page"# `GET /v1/auditLogs` is the only endpoint with a server-side lower bound on record time.AUDIT_LOG_START_PARAM = "starting_on"+# How `POST /v1/usage` aggregates the period it is asked for: one row per hour, one row per day, or+# one row for the whole period.+WindowSize = Literal["none", "hour", "day"]++# How far back a first sync of each bucketed usage table reaches. A bucketed table holds one row per+# customer, billable metric and period, so its size is the account's customer/metric pairs+# multiplied by the number of periods. The hourly table holds 24 rows for every daily row, so it+# reaches back less far.+USAGE_DAILY_HISTORY = timedelta(days=365)+USAGE_HOURLY_HISTORY = timedelta(days=30)++# Metronome accepts usage events backdated up to 34 days, so a period that already synced can still+# change. Each incremental run re-reads this much of the period it already covered and upserts it.+USAGE_DAILY_LOOKBACK_SECONDS = 7 * 24 * 60 * 60+USAGE_HOURLY_LOOKBACK_SECONDS = 24 * 60 * 60+@dataclass(frozen=True)class BodyFanoutConfig:@@ -60,10 +78,19 @@ 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+ # `POST /v1/usage` needs a `window_size`/`starting_on`/`ending_before` window in its body. The+ # window is computed per run, because `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. None means the+ # endpoint sends no window.+ window_size: WindowSize | None = None+ # The order rows are emitted in. `POST /v1/usage` groups its rows by customer and billable+ # metric rather than by time, so a bucketed table declares "desc" to hold the incremental+ # watermark back until the walk finishes. Committing it per batch would advance it to the newest+ # period of the first customer walked, and the next run would then skip every older period the+ # remaining customers still owe.+ sort_mode: SortMode = "asc"+ should_sync_default: bool = True+ default_incremental_lookback_seconds: int | None = None# Customer-scoped children bind the parent's `id` into their path as `customer_id`. Every child@@ -155,11 +182,40 @@ METRONOME_ENDPOINTS: dict[str, MetronomeEndpointConfig] = {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,+ # `none` returns a single lifetime aggregate per customer/metric over the requested window,+ # which starts at the epoch, so the row count stays bounded by the account. The two tables+ # below carry the same usage split into periods, over a window bounded per table.+ window_size="none",+ ),+ # Both bucketed tables start off: a first sync of either is far larger than the whole rest of+ # the catalog, and the lifetime `usage` table above already answers the common question.+ "usage_daily": MetronomeEndpointConfig(+ name="usage_daily",+ path="/v1/usage",+ method="post",+ # One row per customer, billable metric and day, so the period joins the key that the+ # lifetime table identifies a row by.+ primary_key=["customer_id", "billable_metric_id", "start_timestamp"],+ partition_key="start_timestamp",+ window_size="day",+ incremental_fields=[incremental_field("start_timestamp")],+ default_incremental_field="start_timestamp",+ default_incremental_lookback_seconds=USAGE_DAILY_LOOKBACK_SECONDS,+ sort_mode="desc",+ should_sync_default=False,+ ),+ "usage_hourly": MetronomeEndpointConfig(+ name="usage_hourly",+ path="/v1/usage",+ method="post",+ primary_key=["customer_id", "billable_metric_id", "start_timestamp"],+ partition_key="start_timestamp",+ window_size="hour",+ incremental_fields=[incremental_field("start_timestamp")],+ default_incremental_field="start_timestamp",+ default_incremental_lookback_seconds=USAGE_HOURLY_LOOKBACK_SECONDS,+ sort_mode="desc",+ should_sync_default=False,),"audit_logs": MetronomeEndpointConfig(name="audit_logs",@@ -177,6 +233,12 @@ METRONOME_ENDPOINTS: dict[str, MetronomeEndpointConfig] = {ENDPOINTS = tuple(METRONOME_ENDPOINTS)+# The tables whose rows are one usage period, with how far back a first sync of each one reaches.+USAGE_HISTORY: dict[str, timedelta] = {+ "usage_daily": USAGE_DAILY_HISTORY,+ "usage_hourly": USAGE_HOURLY_HISTORY,+}+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in METRONOME_ENDPOINTS.items()}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.pyindex fc0683eba5cf..69c0daa38efa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom typing import Optional, castfrom posthog.schema import (@@ -31,6 +32,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import (ENDPOINTS,INCREMENTAL_FIELDS,+ METRONOME_ENDPOINTS,+ USAGE_HISTORY,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -69,7 +72,26 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConfforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ schemas = build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ # Appending would duplicate every period the lookback re-reads, so a bucketed usage+ # table has to merge on its primary key.+ merge_only=tuple(USAGE_HISTORY),+ should_sync_default={name: METRONOME_ENDPOINTS[name].should_sync_default for name in ENDPOINTS},+ )+ for schema in schemas:+ schema.default_incremental_lookback_seconds = METRONOME_ENDPOINTS[+ schema.name+ ].default_incremental_lookback_seconds+ return schemas++ def history_lookback_for_schema(self, schema_name: str) -> timedelta | None:+ # Only the bucketed usage tables bound their first sync. Everything else reads a list the+ # account already bounds, and the lifetime `usage` aggregate is one row per customer and+ # metric however far back it reaches.+ return USAGE_HISTORY.get(schema_name)def validate_credentials(self,@@ -100,6 +122,7 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConfif inputs.should_use_incremental_fieldelse None,incremental_field=inputs.incremental_field,+ history_start=inputs.history_start,)@propertydiff --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 b6085f16c657..5791ee9be145 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@@ -2,6 +2,7 @@ from datetime import UTC, datetimefrom typing import Any, castimport pytest+from freezegun import freeze_timefrom unittest.mock import MagicMock, Mock, patchimport requests@@ -20,10 +21,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import METRONOME_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import (+ METRONOME_ENDPOINTS,+ USAGE_DAILY_LOOKBACK_SECONDS,+ USAGE_HOURLY_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.source import MetronomeSourceTRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome"+# The instant every resolved window in these tests is measured against.+NOW = datetime(2026, 9, 3, 12, 34, 56, tzinfo=UTC)+def _response(body: dict[str, Any]) -> Mock:response = Mock()@@ -146,6 +155,26 @@ class TestMetronomeResources:with pytest.raises(ValueError, match="Fan-out endpoint"):get_resource(endpoint, should_use_incremental_field=False)+ @parameterized.expand([("usage_daily", "day"), ("usage_hourly", "hour")])+ def test_bucketed_usage_merges_on_a_body_window_with_no_injected_param(self, endpoint, window_size) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(endpoint, should_use_incremental_field=True, window_starting_on="2026-01-01T00:00:00Z"),+ )++ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ # The window rides the body, which the framework's incremental config cannot reach.+ assert "incremental" not in resource["endpoint"]+ body = resource["endpoint"]["json"]+ assert body["window_size"] == window_size+ assert body["starting_on"] == "2026-01-01T00:00:00Z"+ assert body["ending_before"] > "2026-01-01T00:00:00Z"++ @parameterized.expand([("usage_daily",), ("usage_hourly",)])+ def test_get_resource_rejects_a_bucketed_endpoint_with_no_lower_bound(self, endpoint) -> None:+ with pytest.raises(ValueError, match="needs a resolved"):+ get_resource(endpoint, should_use_incremental_field=True)+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.@@ -161,23 +190,106 @@ class TestMetronomeResources:class TestMetronomeSourceResponse:@parameterized.expand([- ("customers", ["id"], "created_at"),- ("audit_logs", ["id"], "timestamp"),- ("pricing_units", ["id"], None),- ("plans", ["id"], None),- ("usage", ["customer_id", "billable_metric_id"], None),+ ("customers", ["id"], "created_at", "asc"),+ ("audit_logs", ["id"], "timestamp", "asc"),+ ("pricing_units", ["id"], None, "asc"),+ ("plans", ["id"], None, "asc"),+ ("usage", ["customer_id", "billable_metric_id"], None, "asc"),+ # Bucketed usage arrives grouped by customer rather than by period, so its watermark+ # may only commit once the whole walk has finished.+ ("usage_daily", ["customer_id", "billable_metric_id", "start_timestamp"], "start_timestamp", "desc"),+ ("usage_hourly", ["customer_id", "billable_metric_id", "start_timestamp"], "start_timestamp", "desc"),])@patch(f"{TRANSPORT}.rest_api_resource")- def test_top_level_response_shape(self, endpoint, primary_keys, partition_key, _mock) -> None:+ def test_top_level_response_shape(self, endpoint, primary_keys, partition_key, sort_mode, _mock) -> None:response = metronome_source(api_key="tok", endpoint=endpoint, team_id=1, job_id="job-1")assert response.primary_keys == primary_keysassert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.sort_mode == sort_mode# 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+ @parameterized.expand(+ [+ (+ "a_watermark_is_floored_to_the_day",+ "usage_daily",+ datetime(2026, 3, 14, 15, 9, 26, tzinfo=UTC),+ None,+ "2026-03-14T00:00:00Z",+ ),+ (+ "a_watermark_is_floored_to_the_hour",+ "usage_hourly",+ datetime(2026, 3, 14, 15, 9, 26, tzinfo=UTC),+ None,+ "2026-03-14T15:00:00Z",+ ),+ (+ "a_first_sync_starts_where_the_schema_recorded_its_range",+ "usage_daily",+ None,+ datetime(2025, 12, 1, 6, 30, tzinfo=UTC),+ "2025-12-01T00:00:00Z",+ ),+ (+ "an_unrecorded_first_sync_falls_back_to_the_daily_bound",+ "usage_daily",+ None,+ None,+ "2025-09-03T00:00:00Z",+ ),+ (+ "an_unrecorded_first_sync_falls_back_to_the_hourly_bound",+ "usage_hourly",+ None,+ None,+ "2026-08-04T12:00:00Z",+ ),+ ]+ )+ @patch(f"{TRANSPORT}.rest_api_resource")+ def test_bucketed_usage_window_starts_where_the_table_left_off(+ self, _name, endpoint, watermark, history_start, expected_start, mock_rest_api_resource+ ) -> None:+ # An unaligned lower bound asks Metronome for part of a period the table already holds, and+ # the partial aggregate that comes back upserts as a second row, because the period start+ # is part of the primary key.+ with freeze_time(NOW):+ metronome_source(+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ should_use_incremental_field=watermark is not None,+ db_incremental_field_last_value=watermark,+ history_start=history_start,+ )++ body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]+ assert body["starting_on"] == expected_start++ @patch(f"{TRANSPORT}.rest_api_resource")+ def test_resumed_bucketed_run_replays_the_stored_lower_bound(self, mock_rest_api_resource) -> None:+ # Resolving the bound again on a resumed attempt would move it forward, against a cursor+ # that belongs to the window the walk started with.+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = MetronomeResumeConfig(+ next_page="cursor-9", ending_before="2026-06-01T00:00:00Z", starting_on="2026-05-01T00:00:00Z"+ )++ metronome_source(+ api_key="tok", endpoint="usage_daily", team_id=1, job_id="job-1", resumable_source_manager=manager+ )++ body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]+ assert body["starting_on"] == "2026-05-01T00:00:00Z"+ assert body["ending_before"] == "2026-06-01T00:00:00Z"+@patch(f"{TRANSPORT}.rest_api_resource")def test_resume_state_seeds_the_paginator_cursor(self, mock_rest_api_resource) -> None:manager = MagicMock()@@ -239,12 +351,16 @@ class TestMetronomeSourceResponse: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"]+ synced_body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]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)+ MetronomeResumeConfig(+ next_page="cursor-3",+ ending_before=synced_body["ending_before"],+ starting_on=synced_body["starting_on"],+ ))@patch(f"{TRANSPORT}.build_dependent_resource")@@ -337,3 +453,33 @@ class TestMetronomeCredentials:assert valid is Falseassert message == "Couldn't reach Metronome to validate the API token. Check your connection and try again."+++class TestMetronomeSchemas:+ def _schema(self, name: str):+ source = MetronomeSource()+ config = source.parse_config({"api_key": "tok"})+ return {schema.name: schema for schema in source.get_schemas(config, team_id=1)}[name]++ @parameterized.expand(+ [+ ("usage_daily", USAGE_DAILY_LOOKBACK_SECONDS),+ ("usage_hourly", USAGE_HOURLY_LOOKBACK_SECONDS),+ ]+ )+ def test_bucketed_usage_merges_incrementally_and_starts_off(self, name, lookback_seconds) -> None:+ schema = self._schema(name)++ assert schema.supports_incremental is True+ # Appending would duplicate every period the lookback re-reads.+ assert schema.supports_append is False+ assert [field["field"] for field in schema.incremental_fields] == ["start_timestamp"]+ assert schema.should_sync_default is False+ assert schema.default_incremental_lookback_seconds == lookback_seconds++ def test_the_lifetime_usage_table_keeps_its_defaults(self) -> None:+ schema = self._schema("usage")++ assert schema.supports_incremental is False+ assert schema.should_sync_default is True+ assert schema.default_incremental_lookback_seconds is None