Skip to content

: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.

fix(warehouse-sources): resolve the Metronome usage window per run (#104052)

Daniel RC79e451e707dd
diff --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.py
index 78a08e5e7263..0fa8a141a47f 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
@@ -158,16 +158,3 @@ def test_a_source_that_declares_one_window_bounds_every_schema_the_same() -> Non
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 None
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.py
index 692cf3e20d49..f42a2a960ebd 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
@@ -102,8 +102,8 @@ class MetronomeResumeConfig:
# 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.
+ # The `starting_on` bound of the same request. A bucketed table with no watermark resolves it
+ # against the clock, so it is pinned for the walk for the same reason.
starting_on: str | None = None
# Partitioned usage walks. The cursor that fetches the customer page being worked on, and the
# customers within that page whose rows are already written. Both reset together when a page
@@ -223,23 +223,22 @@ def _clamp_window_start(starting_on: str, ending_before: str) -> str:
def _resolve_window_start(
config: MetronomeEndpointConfig,
db_incremental_field_last_value: Any,
- history_start: datetime | None,
+ usage_history: timedelta | 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.
+ watermark it reaches back by the depth the source is set to, measured from today, so a depth the
+ user edits takes effect on the next run and the window stays the size they asked for however
+ long the source has existed.
"""
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]
+ start = parse_datetime_value(db_incremental_field_last_value) or datetime.now(UTC) - (
+ usage_history or USAGE_HISTORY[config.name]
)
return _format_rfc3339(_align_to_utc_midnight(start))
@@ -259,7 +258,7 @@ def _walk_start(
config: MetronomeEndpointConfig,
resumable_source_manager: "Optional[ResumableSourceManager[MetronomeResumeConfig]]",
db_incremental_field_last_value: Any,
- history_start: datetime | None,
+ usage_history: timedelta | None,
) -> MetronomeWalkStart:
"""Read the resume checkpoint, then fill in whatever it did not carry.
@@ -301,7 +300,7 @@ def _walk_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
+ _resolve_window_start(config, db_incremental_field_last_value, usage_history), ending_before
)
return MetronomeWalkStart(
@@ -735,7 +734,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,
+ usage_history: timedelta | None = None,
) -> SourceResponse:
endpoint_config = METRONOME_ENDPOINTS[endpoint]
@@ -776,7 +775,7 @@ def metronome_source(
)
return _make_source_response(endpoint_config, lambda: dependent_resource)
- walk = _walk_start(endpoint_config, resumable_source_manager, db_incremental_field_last_value, history_start)
+ walk = _walk_start(endpoint_config, resumable_source_manager, db_incremental_field_last_value, usage_history)
# A usage walk pages per customer and billable metric, so one sequential pass is one request
# per page for the whole account. Partition it by customer and run several walks at once.
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.py
index 438ea1b783af..4d2b7dcc32c5 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,4 +1,3 @@
-from datetime import timedelta
from typing import Optional, cast
from products.warehouse_sources.backend.facade.source_config import (
@@ -88,18 +87,6 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConf
].default_incremental_lookback_seconds
return schemas
- def history_lookback_for_schema(
- self, schema_name: str, config: MetronomeSourceConfig | None = None
- ) -> 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_window(
- schema_name,
- config.usage_hourly_history_days if config else None,
- config.usage_daily_history_months if config else None,
- )
-
def validate_credentials(
self,
config: MetronomeSourceConfig,
@@ -129,7 +116,14 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConf
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
- history_start=inputs.history_start,
+ # Resolved per run rather than recorded once, so a depth the user edits after the first
+ # sync takes effect, and the window stays the size they asked for rather than widening
+ # as the source ages.
+ usage_history=usage_history_window(
+ inputs.schema_name,
+ config.usage_hourly_history_days,
+ config.usage_daily_history_months,
+ ),
)
@property
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.py
index 96ca6f467c1e..a70eff5a2250 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
@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.
METRONOME_ENDPOINTS,
USAGE_DAILY_LOOKBACK_SECONDS,
USAGE_HOURLY_LOOKBACK_SECONDS,
+ usage_history_window,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.source import MetronomeSource
@@ -433,11 +434,11 @@ class TestMetronomeSourceResponse:
"2026-03-14T00:00:00Z",
),
(
- "a_first_sync_starts_where_the_schema_recorded_its_range",
+ "a_first_sync_reaches_back_by_the_configured_depth",
"usage_daily",
None,
- datetime(2025, 12, 1, 6, 30, tzinfo=UTC),
- "2025-12-01T00:00:00Z",
+ timedelta(days=90),
+ "2026-06-05T00:00:00Z",
),
(
"an_unrecorded_first_sync_falls_back_to_the_daily_bound",
@@ -465,7 +466,7 @@ class TestMetronomeSourceResponse:
)
@patch(f"{TRANSPORT}._parallel_usage_pages")
def test_bucketed_usage_window_starts_where_the_table_left_off(
- self, _name, endpoint, watermark, history_start, expected_start, mock_parallel
+ self, _name, endpoint, watermark, usage_history, expected_start, mock_parallel
) -> 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
@@ -478,7 +479,7 @@ class TestMetronomeSourceResponse:
job_id="job-1",
should_use_incremental_field=watermark is not None,
db_incremental_field_last_value=watermark,
- history_start=history_start,
+ usage_history=usage_history,
).items()
body = mock_parallel.call_args.args[2]
@@ -731,16 +732,26 @@ class TestMetronomeSchemas:
def test_the_usage_history_window_follows_the_source_setting(
self, _name, schema_name, hourly, daily, expected_days
) -> None:
+ window = usage_history_window(schema_name, hourly, daily)
+
+ assert window == (timedelta(days=expected_days) if expected_days is not None else None)
+
+ @patch(f"{TRANSPORT}._parallel_usage_pages")
+ def test_a_depth_the_user_edits_reaches_the_request(self, mock_parallel) -> None:
+ # The depth is a source setting the user can change after the first sync. Reading it per run
+ # is what makes an edit take effect; recording it once left the edit saved and inert.
source = MetronomeSource()
- config = source.parse_config(
- {"api_key": "tok", "usage_hourly_history_days": hourly, "usage_daily_history_months": daily}
+ config = source.parse_config({"api_key": "tok", "usage_daily_history_months": 3})
+ inputs = MagicMock(
+ schema_name="usage_daily",
+ team_id=1,
+ job_id="job-1",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
)
- window = source.history_lookback_for_schema(schema_name, config)
-
- assert window == (timedelta(days=expected_days) if expected_days is not None else None)
+ with time_machine.travel(NOW, tick=False):
+ source.source_for_pipeline(config, MagicMock(can_resume=lambda: False), inputs).items()
- def test_an_unreadable_config_leaves_the_defaults(self) -> None:
- # `history_start_for_schema` passes None when the source's inputs no longer parse, and a
- # table whose depth it cannot read must still be bounded.
- assert MetronomeSource().history_lookback_for_schema("usage_hourly", None) == timedelta(days=30)
+ assert mock_parallel.call_args.args[2]["starting_on"] == "2026-06-04T00:00:00Z"