: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): type the Metronome usage amount, and merge fewer times (#100324)
Daniel RCec3a3cd7cb0a
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 67e3ffc3d80e..2b214946baea 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@@ -56,6 +56,12 @@ 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)+# How much of a bucketed usage walk goes into one yielded batch, which is one Delta merge. Two caps,+# because only one of them is ours to predict: the page cap bounds the requests a resumed attempt+# repeats, and the row cap bounds the merge if Metronome ever returns larger pages than it does now.+USAGE_COALESCE_PAGES = 100+USAGE_COALESCE_ROWS = 20_000+@frozenclass MetronomeResumeConfig:@@ -300,6 +306,50 @@ def _list_params(config: MetronomeEndpointConfig) -> dict[str, Any]:return params+def _coalesced_pages(pages: Iterable[Any], commit_checkpoint: Callable[[], None]) -> Iterator[list[Any]]:+ """Gather several API pages into one yielded batch, and checkpoint once that batch has landed.++ `commit_checkpoint` runs after the `yield` returns, which is after the consumer flushed the+ batch, so the cursor only ever moves over rows that reached Delta. A batch closes on the page+ that would overflow it rather than on the page that already did, which holds it inside the caps+ and also makes the cursor exact: `rest_client` offers a page's cursor when the page after it is+ pulled, so by then it names the first page this batch does not carry.++ A single page wider than the row cap is still yielded whole, because a batch may only end where+ a cursor does. The batcher splits an oversized table on its own byte cap downstream.+ """+ batch: list[Any] = []+ page_count = 0++ for page in pages:+ if batch and (page_count >= USAGE_COALESCE_PAGES or len(batch) + len(page) > USAGE_COALESCE_ROWS):+ yield batch+ commit_checkpoint()+ batch = []+ page_count = 0+ batch.extend(page)+ page_count += 1++ if batch:+ yield batch+ commit_checkpoint()+++def _float_usage_value(row: dict[str, Any]) -> dict[str, Any]:+ """Give the usage amount a floating point type before the column is inferred from it.++ Metronome returns `value` as a bare JSON number, so an account whose first batch holds whole+ numbers infers an integer column, and the first fractional amount after that no longer fits+ the stored type. That failure is not retryable and turns the schema off.++ A null means no usage matched the period, which is not the same as zero, so it stays null.+ """+ value = row.get("value")+ if isinstance(value, int) and not isinstance(value, bool):+ row["value"] = float(value)+ return row++def get_resource(endpoint: str,should_use_incremental_field: bool,@@ -352,13 +402,16 @@ def get_resource(# follows the endpoint declaring a cursor field rather than the injected param.syncs_incrementally = should_use_incremental_field and bool(config.incremental_fields)- return {+ resource: EndpointResource = {"name": config.name,"table_name": config.name,"write_disposition": {"disposition": "merge", "strategy": "upsert"} if syncs_incrementally else "replace","endpoint": endpoint_config,"table_format": "delta",}+ if config.window_size is not None:+ resource["data_map"] = _float_usage_value+ return resourcedef _body_fanout_pages(client: RESTClient, config: MetronomeEndpointConfig) -> Iterator[list[dict[str, Any]]]:@@ -481,25 +534,41 @@ def metronome_source(],}- resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None- if resumable_source_manager is not None:+ # Only a bucketed usage walk coalesces. `audit_logs` is incremental as well, but it sets its own+ # page size, so it never reaches the page counts these caps are sized for.+ coalesces_pages = (+ should_use_incremental_field+ and endpoint_config.window_size is not None+ and bool(endpoint_config.incremental_fields)+ )++ pending_state: Optional[dict[str, Any]] = None- 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. The pinned window rides along so a resumed attempt replays it.- if resumable_source_manager is None or not state:- return- cursor = state.get("cursor")- if cursor:- resumable_source_manager.save_state(- MetronomeResumeConfig(- next_page=str(cursor),- ending_before=walk.ending_before,- starting_on=walk.starting_on,- )+ def persist(state: Optional[dict[str, Any]]) -> None:+ # Persist only while there is another page to resume to; the Redis TTL cleans up on+ # completion. The pinned window rides along so a resumed attempt replays it.+ if resumable_source_manager is None or not state:+ return+ cursor = state.get("cursor")+ if cursor:+ resumable_source_manager.save_state(+ MetronomeResumeConfig(+ next_page=str(cursor),+ ending_before=walk.ending_before,+ starting_on=walk.starting_on,)+ )++ def hold(state: Optional[dict[str, Any]]) -> None:+ nonlocal pending_state+ pending_state = state++ def commit_checkpoint() -> None:+ persist(pending_state)- resume_hook = save_checkpoint+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None+ if resumable_source_manager is not None:+ resume_hook = hold if coalesces_pages else persistresource = rest_api_resource(config,@@ -509,12 +578,16 @@ def metronome_source(resume_hook=resume_hook,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.- # 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.+ # `rest_client` fires the resume hook after the `yield` it belongs to, so the consumer has+ # already taken a yielded item by the time the cursor past it is offered. chunk_size=1 turns+ # that into a durability rule: one yielded item is one flush, so a page reaches Delta before+ # its cursor is checkpointed, and a mid-sync worker shutdown resumes at the page it stopped on+ # rather than past it. Buffering pages in the batcher instead would move the cursor over rows+ # that never landed. The fan-out tables above don't resume, so they keep the default.+ if coalesces_pages:+ return _make_source_response(+ endpoint_config, lambda: _coalesced_pages(resource, commit_checkpoint), chunk_size=1+ )return _make_source_response(endpoint_config, lambda: resource, chunk_size=1)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 3d03737dc1b0..be8581c07fa2 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@@ -16,6 +16,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.MetronomeCursorPaginator,MetronomeResumeConfig,_clamp_window_start,+ _coalesced_pages,_format_rfc3339,_paginator_for,get_resource,@@ -164,6 +165,20 @@ class TestMetronomeResources:assert resource["endpoint"]["params"] == {}assert isinstance(resource["endpoint"]["paginator"], MetronomeCursorPaginator)+ @parameterized.expand([("usage",), ("usage_daily",), ("usage_hourly",)])+ def test_usage_value_is_typed_as_a_float(self, endpoint) -> None:+ # A batch of whole numbers infers an integer column, and the first fractional usage amount+ # after that no longer fits it, which fails the sync and turns the schema off.+ resource = cast(+ dict[str, Any],+ get_resource(endpoint, should_use_incremental_field=False, window_starting_on=EPOCH_RFC_3339),+ )+ data_map = resource["data_map"]++ assert isinstance(data_map({"value": 7})["value"], float)+ # No usage matched the period, which is not the same as none of it costing anything.+ assert data_map({"value": None})["value"] is None+@parameterized.expand([("invoices",), ("contracts",)])def test_get_resource_rejects_fanout_endpoints(self, endpoint) -> None:with pytest.raises(ValueError, match="Fan-out endpoint"):@@ -220,6 +235,54 @@ class TestMetronomeResources:assert body["ending_before"].endswith("T00:00:00Z")+class TestMetronomeCoalescing:+ @patch(f"{TRANSPORT}.USAGE_COALESCE_PAGES", 2)+ def test_a_batch_is_checkpointed_only_once_it_has_been_yielded(self) -> None:+ # The cursor may only move over rows that reached Delta. Checkpointing while the batch is+ # still filling would let a worker rotation resume past pages the consumer never flushed.+ events: list[str] = []++ def pages():+ for index in range(5):+ events.append(f"page-{index}")+ yield [{"n": index}]++ for batch in _coalesced_pages(pages(), lambda: events.append("commit")):+ events.append(f"flush-{len(batch)}")++ # A batch closes on the page that would overflow it, so the pull of that page precedes the+ # flush, and the cursor committed after it names the first page the batch does not carry.+ assert events == [+ "page-0",+ "page-1",+ "page-2",+ "flush-2",+ "commit",+ "page-3",+ "page-4",+ "flush-2",+ "commit",+ "flush-1",+ "commit",+ ]++ @patch(f"{TRANSPORT}.USAGE_COALESCE_ROWS", 3)+ def test_the_row_cap_closes_a_batch_before_the_page_cap(self) -> None:+ # Metronome sets the page size, so a batch is held to a row count as well as a page count.+ pages = ([{"n": index}, {"n": index}] for index in range(3))++ sizes = [len(batch) for batch in _coalesced_pages(pages, lambda: None)]++ assert sizes == [2, 2, 2]+ assert max(sizes) <= 3++ @patch(f"{TRANSPORT}.USAGE_COALESCE_ROWS", 3)+ def test_a_page_wider_than_the_row_cap_is_yielded_whole(self) -> None:+ # A batch may only end where a cursor does, so an oversized page is passed through rather+ # than split; the batcher applies its own byte cap downstream.+ assert [len(batch) for batch in _coalesced_pages(iter([[1, 2, 3, 4, 5]]), lambda: None)] == [5]++class TestMetronomeSourceResponse:@parameterized.expand([@@ -404,6 +467,40 @@ class TestMetronomeSourceResponse:))+ @parameterized.expand(+ [+ ("bucketed_usage_holds_it", "usage_daily", True, False),+ # A full refresh is not a coalescing walk, so its cursor still moves page by page.+ ("full_refresh_checkpoints_each_page", "usage_daily", False, True),+ # Incremental too, but not a usage window: it sets its own page size, so it never+ # reaches the page counts the usage caps are sized for.+ ("audit_logs_checkpoints_each_page", "audit_logs", True, True),+ ]+ )+ @patch(f"{TRANSPORT}.rest_api_resource")+ def test_only_a_bucketed_usage_walk_defers_its_checkpoint(+ self, _name, endpoint, should_use_incremental_field, saves_on_the_page, mock_rest_api_resource+ ) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False+ mock_rest_api_resource.return_value = iter([[{"n": 1}]])++ response = metronome_source(+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=datetime(2026, 3, 14, tzinfo=UTC),+ history_start=datetime(2026, 1, 1, tzinfo=UTC),+ )+ mock_rest_api_resource.call_args.kwargs["resume_hook"]({"cursor": "cursor-3"})++ assert manager.save_state.called is saves_on_the_page+ list(cast(Any, response.items()))+ assert manager.save_state.called is True+@patch(f"{TRANSPORT}.build_dependent_resource")def test_invoices_fan_out_over_customers(self, mock_build) -> None:mock_build.return_value = iter([])