: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(data-warehouse): keep metronome usage progress across a worker hand-off (#112659)
Tom Owers21395cf18bc8
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 f42a2a960ebd..25e6edf983cd 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,14 +1,15 @@import threadingimport dataclassesfrom collections import deque-from collections.abc import Callable, Iterable, Iterator-from concurrent.futures import Future, ThreadPoolExecutor+from collections.abc import Callable, Generator, Iterable, Iterator+from concurrent.futures import Future, ThreadPoolExecutor, waitfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional, castfrom requests import PreparedRequest, Request, Response, Sessionfrom posthog.dataclasses import frozen+from posthog.temporal.common.shutdown import WorkerShuttingDownErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (coerce_datetime_to_utc,@@ -86,6 +87,9 @@ USAGE_REQUESTS_PER_SECOND = 7.5USAGE_RATE_LIMIT_HOLD_SECONDS = 5.0# Caps a batch when an account's customers are small enough that the row cap never trips.USAGE_CUSTOMERS_PER_BATCH = 100+# How long the walk waits on one customer before it looks for a worker shutdown again. One customer+# can take minutes on an account with many billable metrics, and a batch can take hours to fill.+USAGE_SHUTDOWN_POLL_SECONDS = 5.0@frozen@@ -511,18 +515,25 @@ def _parallel_usage_pages(config: MetronomeEndpointConfig,json_body: dict[str, Any],walk: "MetronomeWalkStart",- commit_checkpoint: Callable[[Optional[str], tuple[str, ...]], None],-) -> Iterator[list[Any]]:+ stage_checkpoint: Callable[[Optional[str], tuple[str, ...]], None],+ safe_point: Callable[[], None] = lambda: None,+) -> Generator[list[Any]]:"""Walk each customer's usage separately, several at a time, and yield whole customers.`customer_ids` makes each customer's walk independent, which is the only parallelism thisendpoint allows: its cursor is one opaque chain per customer and billable metric, so the nextcursor is unknowable until the previous page returns.- A batch carries only customers whose walk finished, and its checkpoint is committed after the- `yield` returns, once the consumer has written the batch. So the recorded set never runs ahead- of rows that reached Delta, and a resumed attempt re-walks only customers that wrote nothing.- That is what lets a full refresh resume here without duplicating rows.+ A batch carries only customers whose walk finished, and its checkpoint is staged before the+ `yield`. The pipeline commits a staged checkpoint when it has written the rows yielded so far,+ and it can end the attempt before control returns here. A checkpoint staged after the `yield`+ is lost on that path, and the next attempt starts again at the first customer. So the recorded+ set never runs ahead of rows that reached Delta, and a resumed attempt re-walks only customers+ that wrote nothing. That is what lets a full refresh resume here without duplicating rows.++ A customer with no usage yields nothing, so its checkpoint is staged at a safe point instead.+ `safe_point` also tells the walk about a worker shutdown. The walk then hands over the customers+ it has finished, so the attempt ends in seconds and keeps its progress."""parent = METRONOME_ENDPOINTS["customers"]paginator = _paginator_for(parent)@@ -540,6 +551,8 @@ def _parallel_usage_pages(page_cursor = walk.parent_cursordone_in_page = set(walk.completed_customers)+ batch: list[Any] = []+ batch_customers: list[str] = []pool = ThreadPoolExecutor(max_workers=USAGE_CUSTOMER_CONCURRENCY, thread_name_prefix="metronome-usage")cancelled = threading.Event()@@ -549,6 +562,14 @@ def _parallel_usage_pages(pool, lambda: _usage_rows_for_customer(clients.get(), config, json_body, customer_id, cancelled))+ def take_batch() -> list[Any]:+ """Stage the checkpoint that covers the finished customers, and give back their rows."""+ nonlocal batch, batch_customers+ done_in_page.update(batch_customers)+ stage_checkpoint(page_cursor, tuple(done_in_page))+ rows, batch, batch_customers = batch, [], []+ return rows+try:for page_index, customer_page in enumerate(clients.get().paginate(@@ -568,23 +589,35 @@ def _parallel_usage_pages(todo = deque(cid for row in customer_page if (cid := _customer_id(row)) not in done_in_page)in_flight: deque[tuple[str, Future[list[Any]]]] = deque()_fill_in_flight(submit_walk, todo, in_flight)- batch: list[Any] = []- batch_customers: list[str] = []while in_flight:- customer_id, future = in_flight.popleft()- batch.extend(future.result())- batch_customers.append(customer_id)- _fill_in_flight(submit_walk, todo, in_flight)- if len(batch) >= USAGE_COALESCE_ROWS or len(batch_customers) >= USAGE_CUSTOMERS_PER_BATCH:- yield batch- done_in_page.update(batch_customers)- commit_checkpoint(page_cursor, tuple(done_in_page))- batch, batch_customers = [], []+ customer_id, future = in_flight[0]+ # Not `future.result(timeout=...)`: a walk that fails with a `TimeoutError` of its+ # own would look the same as one that has not finished.+ wait([future], timeout=USAGE_SHUTDOWN_POLL_SECONDS)+ if future.done():+ in_flight.popleft()+ batch.extend(future.result())+ batch_customers.append(customer_id)+ _fill_in_flight(submit_walk, todo, in_flight)+ if not batch:+ # Only customers with no usage so far. Nothing has to be written before+ # their checkpoint is safe, so the walk does not wait for a batch to fill.+ take_batch()+ elif len(batch) >= USAGE_COALESCE_ROWS or len(batch_customers) >= USAGE_CUSTOMERS_PER_BATCH:+ yield take_batch()+ try:+ # Any staged checkpoint covers only rows already yielded, so this is a safe+ # point also while `batch` holds rows.+ safe_point()+ except WorkerShuttingDownError:+ # The rows held here belong to finished customers. Hand them over with their+ # checkpoint, or the next attempt walks those customers again.+ if batch_customers and (rows := take_batch()):+ yield rows+ raiseif batch:- yield batch- done_in_page.update(batch_customers)- commit_checkpoint(page_cursor, tuple(done_in_page))+ yield take_batch()finally:# The consumer may close the generator early. Signal first so a walk already running stops# at its next page, then never block on the ones still in flight.@@ -791,7 +824,7 @@ def metronome_source(api_key, RequestPacer(USAGE_REQUESTS_PER_SECOND, hold_seconds=USAGE_RATE_LIMIT_HOLD_SECONDS))- def commit_usage_checkpoint(parent_cursor: Optional[str], completed: tuple[str, ...]) -> None:+ def stage_usage_checkpoint(parent_cursor: Optional[str], completed: tuple[str, ...]) -> None:# Nothing to resume to once the customer list is exhausted and its last page is written.if resumable_source_manager is None or (parent_cursor is None and not completed):return@@ -804,9 +837,15 @@ def metronome_source())+ def reach_usage_safe_point() -> None:+ if resumable_source_manager is not None:+ resumable_source_manager.safe_point()+return _make_source_response(endpoint_config,- lambda: _parallel_usage_pages(clients, endpoint_config, json_body, walk, commit_usage_checkpoint),+ lambda: _parallel_usage_pages(+ clients, endpoint_config, json_body, walk, stage_usage_checkpoint, reach_usage_safe_point+ ),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 a70eff5a2250..8a76dabda0f8 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@@ -10,6 +10,8 @@ from unittest.mock import MagicMock, Mock, patchimport requestsfrom parameterized import parameterized+from posthog.temporal.common.shutdown import WorkerShuttingDownError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (SinglePagePaginator,)@@ -246,10 +248,12 @@ class TestMetronomeResources:class _FakeUsageClient:"""Stands in for a `RESTClient`: one customer list, then one usage walk per customer."""- def __init__(self, customer_pages, rows_by_customer, page_cursors=()) -> None:+ def __init__(self, customer_pages, rows_by_customer, page_cursors=(), gates=None) -> None:self.customer_pages = customer_pagesself.rows_by_customer = rows_by_customerself.page_cursors = list(page_cursors)+ # A customer listed here answers only once its event is set.+ self.gates: dict[str, threading.Event] = gates or {}self.usage_bodies: list[dict[str, Any]] = []def paginate(self, path, **kwargs):@@ -264,7 +268,10 @@ class _FakeUsageClient:returnbody = kwargs["json"]self.usage_bodies.append(body)- yield self.rows_by_customer[body["customer_ids"][0]]+ customer_id = body["customer_ids"][0]+ if customer_id in self.gates:+ self.gates[customer_id].wait(timeout=10)+ yield self.rows_by_customer[customer_id]class _FakeClients:@@ -308,22 +315,109 @@ class TestMetronomeParallelUsage:assert isinstance(batches[0][0]["value"], float)assert batches[0][1]["value"] is None- def test_a_batch_is_checkpointed_only_once_it_has_been_yielded(self) -> None:- # The recorded set may only move over customers whose rows reached Delta. Committing while- # a batch is still being built would let a worker rotation resume past rows never written.- events: list[str] = []- client = _FakeUsageClient([[{"id": "c1"}]], {"c1": [{"value": 1}]})+ def _walk_events(self, client, events: list[str], safe_point=None):+ def stage(cursor, completed) -> None:+ events.append(f"stage:{','.join(sorted(completed))}")- for batch in _parallel_usage_pages(+ def reach_safe_point() -> None:+ events.append("safe_point")+ if safe_point is not None:+ safe_point()++ return _parallel_usage_pages(cast(Any, _FakeClients(client)),- METRONOME_ENDPOINTS["usage_daily"],- {"window_size": "DAY"},+ METRONOME_ENDPOINTS["usage"],+ {"window_size": "NONE"},MetronomeWalkStart(),- lambda cursor, completed: events.append(f"commit-{sorted(completed)}") if completed else None,- ):- events.append(f"flush-{len(batch)}")+ stage,+ reach_safe_point,+ )++ def test_a_hand_off_after_the_first_batch_keeps_its_checkpoint(self) -> None:+ # The pipeline commits what is staged when it has written a batch, and it can then end the+ # attempt at once. A checkpoint staged after the yield is never committed on that path, so+ # every attempt of a slow walk starts again at the first customer.+ staged: list[tuple[Any, tuple[str, ...]]] = []+ committed: list[tuple[Any, tuple[str, ...]]] = []+ client = _FakeUsageClient([[{"id": "c1"}, {"id": "c2"}]], {"c1": [{"value": 1}], "c2": [{"value": 2}]})++ with patch(f"{TRANSPORT}.USAGE_COALESCE_ROWS", 1):+ walk = _parallel_usage_pages(+ cast(Any, _FakeClients(client)),+ METRONOME_ENDPOINTS["usage"],+ {"window_size": "NONE"},+ MetronomeWalkStart(),+ lambda cursor, completed: staged.append((cursor, completed)),+ )+ first_batch = next(walk)+ committed.extend(staged[-1:])+ walk.close()++ assert first_batch == [{"value": 1.0}]+ assert committed == [(None, ("c1",))]++ @parameterized.expand(+ [+ # A checkpoint is staged only when every row it covers is yielded or about to be.+ (+ "rows_then_none",+ {"c1": [{"value": 1}], "c2": []},+ ["safe_point", "safe_point", "stage:c1,c2", "yield:1"],+ ),+ # A customer with no usage never reaches a yield, so it advances at a safe point.+ ("none_then_none", {"c1": [], "c2": []}, ["stage:c1", "safe_point", "stage:c1,c2", "safe_point"]),+ (+ "none_then_rows",+ {"c1": [], "c2": [{"value": 2}]},+ ["stage:c1", "safe_point", "safe_point", "stage:c1,c2", "yield:1"],+ ),+ ]+ )+ def test_customers_with_no_usage_advance_the_checkpoint(self, _name, rows_by_customer, expected) -> None:+ events: list[str] = []+ client = _FakeUsageClient([[{"id": "c1"}, {"id": "c2"}]], rows_by_customer)++ for batch in self._walk_events(client, events):+ events.append(f"yield:{len(batch)}")++ assert events == expected++ @parameterized.expand(+ [+ # The shutdown is seen when a customer finishes.+ ("after_a_customer", 1, {}),+ # The shutdown is seen while the next customer is still being walked.+ ("during_a_slow_customer", 2, {"c2": threading.Event()}),+ ]+ )+ def test_a_shutdown_hands_over_the_finished_customers(self, _name, shutdown_on_call, gates) -> None:+ events: list[str] = []+ calls = 0++ def safe_point() -> None:+ nonlocal calls+ calls += 1+ if calls >= shutdown_on_call:+ raise WorkerShuttingDownError("id", "type", "queue", 1, None, None)++ client = _FakeUsageClient(+ [[{"id": "c1"}, {"id": "c2"}]], {"c1": [{"value": 1}], "c2": [{"value": 2}]}, gates=gates+ )- assert events == ["flush-1", "commit-['c1']"]+ try:+ with (+ patch(f"{TRANSPORT}.USAGE_SHUTDOWN_POLL_SECONDS", 0.01),+ patch(f"{TRANSPORT}.USAGE_CUSTOMER_CONCURRENCY", 1),+ pytest.raises(WorkerShuttingDownError),+ ):+ for batch in self._walk_events(client, events, safe_point):+ events.append(f"yield:{len(batch)}")+ finally:+ for gate in gates.values():+ gate.set()++ assert events[-2:] == ["stage:c1", "yield:1"]+ assert "stage:c1,c2" not in eventsdef test_a_resumed_walk_skips_the_customers_already_written(self) -> None:# Re-walking a finished customer duplicates its rows on a table that appends when it@@ -570,8 +664,8 @@ class TestMetronomeSourceResponse:).items()synced_body = mock_parallel.call_args.args[2]- commit_checkpoint = mock_parallel.call_args.args[4]- commit_checkpoint("cursor-3", ("c1",))+ stage_checkpoint = mock_parallel.call_args.args[4]+ stage_checkpoint("cursor-3", ("c1",))manager.save_state.assert_called_once_with(MetronomeResumeConfig(