: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
fix(warehouse-sources): fix the Metronome usage request window (#99456)
Daniel RCbfbc9549ece6
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 34b643bdb0f5..67e3ffc3d80e 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, Iterator-from datetime import UTC, datetime-from typing import Any, Literal, Optional, cast+from datetime import UTC, datetime, timedelta+from typing import Any, Optional, castfrom requests import Request, Response@@ -53,6 +53,9 @@ RFC_3339_FORMAT = "%Y-%m-%dT%H:%M:%SZ"# Lower bound for a first incremental run — earlier than any Metronome account.EPOCH_RFC_3339 = "1970-01-01T00:00:00Z"+# `POST /v1/usage` documents `ending_before` as at least one day after `starting_on`.+MIN_USAGE_WINDOW = timedelta(days=1)+@frozenclass MetronomeResumeConfig:@@ -133,17 +136,48 @@ 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.+def _align_to_utc_midnight(value: datetime) -> datetime:+ """Floor a usage window bound to the boundary Metronome requires.++ `POST /v1/usage` documents both bounds as aligned to UTC midnight and answers a 400 when either+ is not, whatever the `window_size`, so an hourly table also asks for whole days.++ Flooring also keeps a bucketed table's rows stable. 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+ returns a partial aggregate for a period the table already holds in full, which then upserts as+ a second row instead of replacing the first.+ """+ return value.replace(hour=0, minute=0, second=0, microsecond=0)+++def _usage_window_end(value: datetime) -> datetime:+ """The end bound a usage request asks for.- 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.+ Metronome takes a UTC-midnight bound only, so the nearest aligned end that still covers the+ period in progress is the next midnight rather than the last one. Ending at the last one would+ hold every table a full period behind, which is the period a usage table is most asked about.++ Rows for a period still in progress come back partial. The merge key carries the period start,+ so each later run upserts a fresher value over them, and the row settles once the period+ closes. This is the same path a period already takes when Metronome accepts a backdated event+ for it.+ """+ return _align_to_utc_midnight(value) + timedelta(days=1)+++def _clamp_window_start(starting_on: str, ending_before: str) -> str:+ """Hold the requested window to the one-day minimum Metronome documents.++ Both bounds floor to UTC midnight, so a table whose watermark already reached the newest+ complete period resolves a start equal to the end. Metronome rejects that window, so ask for+ the last whole day instead. Those rows upsert over ones the table already holds."""- if window_size == "day":- return value.replace(hour=0, minute=0, second=0, microsecond=0)- return value.replace(minute=0, second=0, microsecond=0)+ start = parse_datetime_value(starting_on)+ end = parse_datetime_value(ending_before)+ if start is None or end is None or end - start >= MIN_USAGE_WINDOW:+ return starting_on+ return _format_rfc3339(end - MIN_USAGE_WINDOW)def _resolve_window_start(@@ -167,7 +201,7 @@ def _resolve_window_start(or coerce_datetime_to_utc(history_start)or datetime.now(UTC) - USAGE_HISTORY[config.name])- return _format_rfc3339(_align_to_window(start, window_size))+ return _format_rfc3339(_align_to_utc_midnight(start))@frozen@@ -215,9 +249,13 @@ def _walk_start(if config.window_size is not None:if ending_before is None:- ending_before = _format_rfc3339(datetime.now(UTC))+ ending_before = _format_rfc3339(_usage_window_end(datetime.now(UTC)))if starting_on is None:- starting_on = _resolve_window_start(config, db_incremental_field_last_value, history_start)+ # Only a freshly resolved start is clamped. A resumed walk replays the exact window its+ # checkpoint stored, and both bounds come back together or neither does.+ starting_on = _clamp_window_start(+ _resolve_window_start(config, db_incremental_field_last_value, history_start), ending_before+ )return MetronomeWalkStart(starting_on=starting_on, ending_before=ending_before, paginator_state=paginator_state)@@ -292,13 +330,16 @@ def get_resource(if config.method == "post":json_body = dict(config.json_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 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+ # `starting_on` at the epoch means "all usage the account has". The caller pins both+ # bounds 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.+ # The spec's enum accepts three casings, but both vendor SDKs emit upper case only.+ json_body["window_size"] = config.window_size.upper()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))+ window_ending_before+ if window_ending_before is not None+ else _format_rfc3339(_usage_window_end(datetime.now(UTC))))endpoint_config["json"] = json_bodydiff --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 2bd77b974b89..ed3a0169f82e 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@@ -84,7 +84,7 @@ class MetronomeEndpointConfig:fanout: DependentEndpointConfig | None = Nonebody_fanout: BodyFanoutConfig | None = None# `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+ # window is computed per run, because `ending_before` tracks the clock, 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 = Nonediff --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 ca388581c9ba..3d03737dc1b0 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@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.EPOCH_RFC_3339,MetronomeCursorPaginator,MetronomeResumeConfig,+ _clamp_window_start,_format_rfc3339,_paginator_for,get_resource,@@ -168,7 +169,7 @@ 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")])+ @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],@@ -182,6 +183,24 @@ class TestMetronomeResources:assert body["window_size"] == window_sizeassert body["starting_on"] == "2026-01-01T00:00:00Z"assert body["ending_before"] > "2026-01-01T00:00:00Z"+ # An hourly table asks for whole days too; Metronome 400s on a bound off UTC midnight.+ assert body["ending_before"].endswith("T00:00:00Z")++ @parameterized.expand(+ [+ ("a_full_day_is_left_alone", "2026-09-03T00:00:00Z", "2026-09-04T00:00:00Z", "2026-09-03T00:00:00Z"),+ (+ "a_shorter_window_backs_the_start_off",+ "2026-09-04T00:00:00Z",+ "2026-09-04T00:00:00Z",+ "2026-09-03T00:00:00Z",+ ),+ ]+ )+ def test_clamp_window_start_holds_the_one_day_minimum(self, _name, starting_on, ending_before, expected) -> None:+ # Metronome rejects a window shorter than a day, so the end bound reaching the start has to+ # widen the request rather than send one the vendor answers with a 400.+ assert _clamp_window_start(starting_on, ending_before) == expected@parameterized.expand([("usage_daily",), ("usage_hourly",)])def test_get_resource_rejects_a_bucketed_endpoint_with_no_lower_bound(self, endpoint) -> None:@@ -195,9 +214,10 @@ class TestMetronomeResources:assert resource["endpoint"]["method"] == "post"body = resource["endpoint"]["json"]- assert body["window_size"] == "none"+ assert body["window_size"] == "NONE"assert body["starting_on"] == EPOCH_RFC_3339assert body["ending_before"] > EPOCH_RFC_3339+ assert body["ending_before"].endswith("T00:00:00Z")class TestMetronomeSourceResponse:@@ -235,11 +255,11 @@ class TestMetronomeSourceResponse:"2026-03-14T00:00:00Z",),(- "a_watermark_is_floored_to_the_hour",+ "an_hourly_watermark_floors_to_utc_midnight_too","usage_hourly",datetime(2026, 3, 14, 15, 9, 26, tzinfo=UTC),None,- "2026-03-14T15:00:00Z",+ "2026-03-14T00:00:00Z",),("a_first_sync_starts_where_the_schema_recorded_its_range",@@ -260,7 +280,15 @@ class TestMetronomeSourceResponse:"usage_hourly",None,None,- "2026-08-04T12:00:00Z",+ "2026-08-04T00:00:00Z",+ ),+ # The window runs to the next midnight, so the day in progress is inside it.+ (+ "a_watermark_inside_today_still_asks_for_today",+ "usage_daily",+ NOW,+ None,+ "2026-09-03T00:00:00Z",),])