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.

perf(warehouse-sources): make a Metronome usage sync finishable (#101691)

Daniel RC743c84fe1d69
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.py
index 76335fe8d615..b97cb2eb296d 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
@@ -188,11 +188,15 @@ 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:
+ def history_lookback_for_schema(
+ self, schema_name: str, config: ConfigType | None = None
+ ) -> 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.
+ rollup of the same data, where the hourly table holds 24 rows for every daily row. `config`
+ is the source's parsed config, for a source whose depth the user picks at setup; it is None
+ when the config could not be read, and an override must still answer in that case.
"""
return self.history_lookback
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.py
index 9916a8116256..94d02b076d0f 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,15 @@ def history_start_for_schema(
logger.warning("history_window.unknown_source_type", source_type=schema.source.source_type)
return None
- lookback = source.history_lookback_for_schema(schema.name)
+ # A source whose depth the user picks at setup reads it from here. Inputs that no longer parse
+ # leave the source on its declared default rather than failing every sync's history resolution.
+ config = None
+ try:
+ config = source.parse_config(schema.source.job_inputs or {})
+ except Exception:
+ logger.warning("history_window.config_unreadable", source_type=schema.source.source_type)
+
+ lookback = source.history_lookback_for_schema(schema.name, config)
if lookback is None:
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/request_pacer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/request_pacer.py
new file mode 100644
index 000000000000..6b19ffe10e6a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/request_pacer.py
@@ -0,0 +1,105 @@
+import time
+import threading
+import contextvars
+from collections.abc import Callable
+from concurrent.futures import Future, ThreadPoolExecutor
+from typing import Optional, ParamSpec, TypeVar
+
+_P = ParamSpec("_P")
+_T = TypeVar("_T")
+
+# Fallback hold when a 429 carries no Retry-After, and the quiet window the rate doubles back over.
+# No vendor documents it: it is a conservative guess, kept at the value the Stripe invoice walker
+# shipped with. A vendor whose limit is per second clears far sooner than this, so pass a shorter
+# hold rather than inheriting one sized for a header that vendor never sends.
+RATE_LIMIT_HOLD_SECONDS = 30.0
+
+
+def submit_with_context(
+ pool: ThreadPoolExecutor, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
+) -> Future[_T]:
+ """Run `fn` on the pool inside a copy of the caller's context.
+
+ Pool threads start with an empty context, which would strip the team and job labels that the
+ HTTP observer and structlog read from contextvars.
+ """
+ ctx = contextvars.copy_context()
+ return pool.submit(lambda: ctx.run(fn, *args, **kwargs))
+
+
+class RequestPacer:
+ """Spaces request starts across threads and slows the whole pool after a rate limit.
+
+ Every worker calls wait_turn() before a request, so the pool never starts more than
+ `per_second` requests in any second. A 429 halves the rate for the hold window and, when
+ the vendor sends Retry-After, holds every worker until it passes, including workers already
+ waiting for a slot. Each quiet window after that doubles the rate back until the base rate
+ is restored.
+
+ The budget being protected belongs to the customer's own account on the vendor, so this is a
+ caller-side courtesy rather than a shared PostHog budget. An API whose credential PostHog owns
+ belongs in `posthog/egress/` instead.
+ """
+
+ def __init__(
+ self,
+ per_second: float,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+ hold_seconds: float = RATE_LIMIT_HOLD_SECONDS,
+ ) -> None:
+ self._base_interval = 1.0 / per_second
+ self._interval = self._base_interval
+ self._clock = clock
+ self._sleep = sleep
+ self._hold_seconds = hold_seconds
+ self._lock = threading.Lock()
+ self._next_start = 0.0
+ self._hold_until = 0.0
+ self._recover_at: Optional[float] = None
+
+ def wait_turn(self) -> None:
+ start = self._reserve_slot()
+ while True:
+ delay = start - self._clock()
+ if delay > 0:
+ self._sleep(delay)
+ with self._lock:
+ if self._hold_until <= start:
+ return
+ # A throttle arrived during the sleep and its hold covers this slot: take a later one.
+ start = self._reserve_slot()
+
+ def _reserve_slot(self) -> float:
+ with self._lock:
+ now = self._clock()
+ if self._recover_at is not None and now >= self._recover_at:
+ self._interval = max(self._interval / 2, self._base_interval)
+ self._recover_at = None if self._interval == self._base_interval else now + self._hold_seconds
+ start = max(now, self._next_start)
+ self._next_start = start + self._interval
+ return start
+
+ def throttled(self, retry_after: Optional[float]) -> None:
+ with self._lock:
+ now = self._clock()
+ if now < self._hold_until:
+ # Requests already in flight when the first 429 landed report the same throttle, so
+ # a repeat changes nothing by itself. A vendor naming a deadline past the hold
+ # already running is not a repeat: honouring only the first would resume early and
+ # earn the next 429. A missing or shorter header still says nothing new.
+ if retry_after is not None and retry_after > 0:
+ deadline = now + retry_after
+ if deadline > self._hold_until:
+ self._hold_until = deadline
+ self._next_start = max(self._next_start, deadline)
+ self._recover_at = deadline if self._recover_at is None else max(self._recover_at, deadline)
+ return
+ hold = retry_after if retry_after is not None and retry_after > 0 else self._hold_seconds
+ self._interval = min(self._interval * 2, self._base_interval * 16)
+ # The hold applies whether or not the vendor named one. Reducing the rate alone lets a
+ # worker start again immediately, which is the opposite of standing down, and a vendor
+ # that documents no Retry-After would never be held at all.
+ self._hold_until = now + hold
+ self._next_start = max(self._next_start, self._hold_until)
+ self._recover_at = now + hold
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 ae323fa71daf..78a08e5e7263 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
@@ -8,6 +8,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import _BaseSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.history_window import (
history_start_for_schema,
)
@@ -35,6 +36,15 @@ class TestHistoryStartForSchema(BaseTest):
schema.refresh_from_db()
assert schema.history_start == NOW - dt.timedelta(days=2 * 365)
+ def test_a_source_whose_inputs_do_not_parse_keeps_its_declared_window(self):
+ # The config is read only for a source whose depth the user picks at setup. A source whose
+ # inputs no longer parse has to keep resolving its declared window, because this runs on
+ # every sync of every source.
+ schema = self._schema()
+
+ with mock.patch.object(_BaseSource, "parse_config", side_effect=ValueError("unreadable")):
+ assert self._resolve(schema) == NOW - dt.timedelta(days=2 * 365)
+
def test_the_recorded_start_is_not_moved_by_a_later_run(self):
# Recording it once is the whole mechanism. Re-deriving it per run is what this replaces.
recorded = dt.datetime(2020, 2, 8, tzinfo=dt.UTC)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_request_pacer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_request_pacer.py
new file mode 100644
index 000000000000..1482acff5e09
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_request_pacer.py
@@ -0,0 +1,110 @@
+import pytest
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.request_pacer import RequestPacer
+
+
+class TestRequestPacer:
+ def _pacer(self, per_second: float = 10.0) -> tuple[RequestPacer, dict[str, float], list[float]]:
+ clock = {"now": 0.0}
+ sleeps: list[float] = []
+ return RequestPacer(per_second, clock=lambda: clock["now"], sleep=sleeps.append), clock, sleeps
+
+ def test_spaces_request_starts_at_the_base_rate(self):
+ pacer, _clock, sleeps = self._pacer()
+
+ for _ in range(3):
+ pacer.wait_turn()
+
+ assert sleeps == pytest.approx([0.1, 0.2])
+
+ def test_a_rate_limit_holds_for_retry_after_and_halves_the_rate(self):
+ pacer, _clock, sleeps = self._pacer()
+ pacer.wait_turn()
+
+ pacer.throttled(retry_after=5)
+ pacer.wait_turn()
+ pacer.wait_turn()
+
+ assert sleeps == pytest.approx([5.0, 5.2])
+
+ def test_a_rate_limit_holds_a_worker_that_already_reserved_its_slot(self):
+ clock = {"now": 0.0}
+ sleeps: list[float] = []
+
+ def sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+ clock["now"] += seconds
+ if len(sleeps) == 1:
+ pacer.throttled(retry_after=5)
+
+ pacer = RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleep)
+ pacer.wait_turn()
+ pacer.wait_turn()
+
+ assert sleeps == pytest.approx([0.1, 5.0])
+
+ def test_rate_limits_reported_during_a_hold_do_not_compound(self):
+ pacer, clock, sleeps = self._pacer()
+ pacer.throttled(retry_after=5)
+ pacer.throttled(retry_after=5)
+
+ clock["now"] = 4.9
+ pacer.wait_turn()
+ pacer.wait_turn()
+
+ assert sleeps == pytest.approx([0.1, 0.3])
+
+ def test_the_rate_recovers_after_a_quiet_window(self):
+ pacer, clock, sleeps = self._pacer()
+ pacer.throttled(retry_after=None)
+
+ clock["now"] = 31.0
+ pacer.wait_turn()
+ pacer.wait_turn()
+
+ assert sleeps == pytest.approx([0.1])
+
+ def test_a_vendor_specific_hold_replaces_the_default(self) -> None:
+ # A vendor that documents no Retry-After takes the fallback on every throttle, so the hold
+ # has to be the one it chose. Inheriting a default sized for a vendor that sends the header
+ # would keep the pool slow for far longer than that vendor needs.
+ clock = {"now": 0.0}
+ sleeps: list[float] = []
+ pacer = RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleeps.append, hold_seconds=2.0)
+
+ pacer.throttled(None)
+ clock["now"] = 2.0
+ pacer.wait_turn()
+ pacer.wait_turn()
+
+ # Recovered to the base 0.1s spacing after its own 2s window, not after the 30s default.
+ assert sleeps[-1] == pytest.approx(0.1)
+
+ def test_a_longer_retry_after_extends_a_hold_already_running(self) -> None:
+ # Requests in flight when the first 429 lands all report it. A vendor naming a deadline past
+ # the hold already running is not that: keeping only the first would resume early.
+ clock = {"now": 0.0}
+ sleeps: list[float] = []
+ pacer = RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleeps.append)
+
+ pacer.throttled(5.0)
+ pacer.throttled(20.0)
+ clock["now"] = 6.0
+ pacer.wait_turn()
+
+ # Still held at 6s, because the second 429 moved the deadline out to 20s.
+ assert sleeps[-1] == pytest.approx(14.0)
+
+ def test_a_shorter_or_missing_retry_after_does_not_extend(self) -> None:
+ clock = {"now": 0.0}
+ sleeps: list[float] = []
+ pacer = RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleeps.append, hold_seconds=30.0)
+
+ pacer.throttled(20.0)
+ pacer.throttled(1.0)
+ pacer.throttled(None)
+ clock["now"] = 20.0
+ pacer.wait_turn()
+
+ # The 20s deadline stands: neither the shorter header nor the bare repeat moved it.
+ assert sleeps == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
index 307e09e93f9c..0710e369a3d7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
@@ -7,3 +7,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class MetronomeSourceConfig(config.Config):
api_key: str
+ usage_hourly_history_days: int | None = config.value(
+ converter=config.str_to_optional_int, default_factory=lambda: None
+ )
+ usage_daily_history_months: int | None = config.value(
+ converter=config.str_to_optional_int, default_factory=lambda: 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 2b214946baea..d13bc73e75b8 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,9 +1,12 @@
+import threading
import dataclasses
+from collections import deque
from collections.abc import Callable, Iterable, Iterator
+from concurrent.futures import Future, ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
from typing import Any, Optional, cast
-from requests import Request, Response
+from requests import PreparedRequest, Request, Response, Session
from posthog.dataclasses import frozen
@@ -12,6 +15,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.dat
parse_datetime_value,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.request_pacer import (
+ RequestPacer,
+ submit_with_context,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
RESTClient,
@@ -56,19 +63,39 @@ 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
+# How many rows of a usage walk go into one yielded batch, which is one Delta merge.
USAGE_COALESCE_ROWS = 20_000
+# `POST /v1/usage` pages per customer and billable metric and takes no page-size parameter, so a
+# first sync costs one request per page whatever the account holds, and a large account runs to
+# hundreds of thousands of requests. Customers are independent, so walk several at once. The
+# endpoint sits in Metronome's default rate tier, 8 requests a second shared with every other table
+# on the same account, so take well under it and leave the rest for the account's other syncs.
+# Two, not more: the pacer below is what governs throughput, and at the latency this endpoint
+# answers in, two workers already saturate it. Each worker holds one customer's rows while it walks
+# them, so a third would buy no request rate and cost another customer's worth of memory. More
+# workers only pay off if the endpoint slows enough for the workers, rather than the rate, to become
+# the limit.
+USAGE_CUSTOMER_CONCURRENCY = 2
+USAGE_REQUESTS_PER_SECOND = 5.0
+# Metronome documents its limit per second and documents no Retry-After, so a throttled pool only
+# has to stand down for a second or two, and it has to decide that for itself. The pacer's own
+# default is sized for a vendor that sends the header and falls back rarely.
+USAGE_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
+
@frozen
class MetronomeResumeConfig:
- """Paginator checkpoint — the `next_page` cursor of the page we have not yet fetched, plus the
- request window that cursor belongs to."""
+ """Checkpoint for a walk, plus the request window it belongs to.
+
+ A sequential walk stores `next_page`, the cursor of the page it has not fetched yet. A usage walk
+ is partitioned by customer, so it stores where the customer list had reached and which customers
+ of that page are already written; the rest of the page is re-walked from the start.
+ """
- next_page: str
+ next_page: str | None = None
# 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.
@@ -76,6 +103,11 @@ class MetronomeResumeConfig:
# 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 = 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
+ # finishes, so the checkpoint stays the size of one customer page however large the account is.
+ parent_cursor: str | None = None
+ completed_customers: tuple[str, ...] = ()
class MetronomeCursorPaginator(JSONResponseCursorPaginator):
@@ -217,6 +249,8 @@ class MetronomeWalkStart:
starting_on: str | None = None
ending_before: str | None = None
paginator_state: dict[str, Any] | None = None
+ parent_cursor: str | None = None
+ completed_customers: tuple[str, ...] = ()
def _walk_start(
@@ -238,6 +272,8 @@ def _walk_start(
starting_on: str | None = None
ending_before: str | None = None
paginator_state: dict[str, Any] | None = None
+ parent_cursor: str | None = None
+ completed_customers: tuple[str, ...] = ()
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
@@ -249,7 +285,10 @@ def _walk_start(
# clean full refresh.
resumable_source_manager.clear_state()
else:
- paginator_state = {"cursor": resume_config.next_page}
+ if resume_config.next_page:
+ paginator_state = {"cursor": resume_config.next_page}
+ parent_cursor = resume_config.parent_cursor
+ completed_customers = tuple(resume_config.completed_customers or ())
ending_before = resume_config.ending_before
starting_on = resume_config.starting_on
@@ -263,7 +302,13 @@ def _walk_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)
+ return MetronomeWalkStart(
+ starting_on=starting_on,
+ ending_before=ending_before,
+ paginator_state=paginator_state,
+ parent_cursor=parent_cursor,
+ completed_customers=completed_customers,
+ )
def _rest_api_client_config(api_key: str) -> ClientConfig:
@@ -306,33 +351,244 @@ 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.
+def _retry_after_seconds(response: Response) -> float | None:
+ raw = response.headers.get("Retry-After")
+ if not raw:
+ return None
+ try:
+ return float(raw)
+ except ValueError:
+ # The header may carry an HTTP date instead. The pacer's own hold covers that.
+ return None
+
+
+class _PacedSession:
+ """Fronts a tracked session, taking a pacer slot before every request it sends.
+
+ `RESTClient` drives pagination itself, so pacing at the call site would only space the first
+ request of a walk. Sitting in front of `send` puts a slot before every page, and reports a 429
+ so the whole pool backs off rather than the one thread that met it.
+
+ `RESTClient` reads `headers` and calls `prepare_request` and `send`, which is what this
+ forwards. The wrapped session keeps its tracked adapters, credential redaction and its refusal
+ to follow redirects, because every request still goes out through it.
+ """
+
+ def __init__(self, session: Session, pacer: RequestPacer) -> None:
+ self._session = session
+ self._pacer = pacer
+
+ @property
+ def headers(self) -> Any:
+ return self._session.headers
+
+ def prepare_request(self, request: Request) -> PreparedRequest:
+ return self._session.prepare_request(request)
+
+ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
+ self._pacer.wait_turn()
+ response = self._session.send(request, **kwargs)
+ if response.status_code == 429:
+ self._pacer.throttled(_retry_after_seconds(response))
+ return response
+
+
+def _paced_session(api_key: str, pacer: RequestPacer) -> Session:
+ session = make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False)
+ # Not a `Session` subclass: a tracked session is built by a factory, and subclassing it would
+ # mean rebuilding the adapters this needs to keep.
+ return cast(Session, _PacedSession(session, pacer))
+
+
+class _PacedClients:
+ """One client per worker thread, all sharing one pacer.
+
+ Every thread needs its own `requests.Session`, which is not documented as thread-safe, but the
+ budget being protected is the customer's single Metronome account, so the pacer is shared.
+ """
+
+ def __init__(self, api_key: str, pacer: RequestPacer) -> None:
+ self._api_key = api_key
+ self._pacer = pacer
+ self._local = threading.local()
+
+ def get(self) -> RESTClient:
+ client: Optional[RESTClient] = getattr(self._local, "client", None)
+ if client is None:
+ config = _rest_api_client_config(self._api_key)
+ client = RESTClient(
+ base_url=config["base_url"],
+ headers=config["headers"],
+ auth=create_auth(config["auth"]),
+ session=_paced_session(self._api_key, self._pacer),
+ allowed_hosts=config["allowed_hosts"],
+ allow_redirects=config["allow_redirects"],
+ request_timeout=config["request_timeout"],
+ )
+ self._local.client = client
+ return client
- `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.
+def _customer_id(row: dict[str, Any]) -> str:
+ """The id that partitions one customer's usage walk.
+
+ A customer that cannot be asked for has to fail the sync. Skipping it would drop that
+ customer's usage from the table with no signal, and a usage table that is quietly short is
+ worse than one that stops and says why. A missing key raises on its own; a null or empty id
+ needs saying, because `str(None)` would otherwise ask Metronome for a customer called "None".
"""
- batch: list[Any] = []
- page_count = 0
+ customer_id = row["id"]
+ if customer_id is None or customer_id == "":
+ raise ValueError("Metronome returned a customer with no id, so its usage cannot be read")
+ return str(customer_id)
+
- 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
+class _WalkCancelled(Exception):
+ """The consumer went away while this customer was still being walked.
- if batch:
- yield batch
- commit_checkpoint()
+ Raised rather than returning the rows gathered so far, because the checkpoint records whole
+ customers: a partial one must never be mistakable for a finished one.
+ """
+
+
+def _usage_rows_for_customer(
+ client: RESTClient,
+ config: MetronomeEndpointConfig,
+ json_body: dict[str, Any],
+ customer_id: str,
+ cancelled: threading.Event,
+) -> list[Any]:
+ """Every usage row one customer has in the requested window.
+
+ `_float_usage_value` is applied here because this path builds its own requests rather than going
+ through the resource's `data_map`.
+
+ `cancel_futures` only drops walks that never started, so a walk already running checks between
+ pages for itself. Otherwise it keeps spending the account's request budget after the consumer
+ has gone, and the pool's threads hold up the process on their way out.
+
+ The rows are gathered whole rather than streamed, because the checkpoint records whole
+ customers and a partial one must never be mistakable for a finished one. That is bounded rather
+ than open ended: one customer holds the periods in the requested window multiplied by the
+ account's billable metrics, the window is capped by the source's history setting, and only as
+ many of these exist at once as there are workers. Streaming within a customer would need a
+ per-customer resume cursor, which is a larger change than the size of this buffer justifies.
+ """
+ rows: list[Any] = []
+ for page in client.paginate(
+ config.path,
+ method=config.method,
+ params=_list_params(config),
+ json={**json_body, "customer_ids": [customer_id]},
+ data_selector=DATA_SELECTOR,
+ data_selector_required=True,
+ paginator=_paginator_for(config),
+ ):
+ rows.extend(_float_usage_value(row) for row in page)
+ if cancelled.is_set():
+ raise _WalkCancelled(customer_id)
+ return rows
+
+
+def _fill_in_flight(
+ submit: Callable[[str], "Future[list[Any]]"],
+ todo: deque[str],
+ in_flight: deque[tuple[str, "Future[list[Any]]"]],
+) -> None:
+ """Keep as many walks in flight as there are workers, and no more.
+
+ Submitting a whole customer page at once would leave every finished customer's rows in memory
+ behind a slow one, which is how a batch gets past the row cap.
+ """
+ while todo and len(in_flight) < USAGE_CUSTOMER_CONCURRENCY:
+ customer_id = todo.popleft()
+ in_flight.append((customer_id, submit(customer_id)))
+
+
+def _parallel_usage_pages(
+ clients: _PacedClients,
+ config: MetronomeEndpointConfig,
+ json_body: dict[str, Any],
+ walk: "MetronomeWalkStart",
+ commit_checkpoint: Callable[[Optional[str], tuple[str, ...]], None],
+) -> Iterator[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 this
+ endpoint allows: its cursor is one opaque chain per customer and billable metric, so the next
+ cursor 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.
+ """
+ parent = METRONOME_ENDPOINTS["customers"]
+ paginator = _paginator_for(parent)
+ if walk.parent_cursor:
+ paginator.set_resume_state({"cursor": walk.parent_cursor})
+
+ # `RESTClient.paginate` advances a deep copy of the paginator it is given, so the instance here
+ # never moves. The cursor has to come back through the resume hook, which fires when the loop
+ # asks for the page after the one it just handed over.
+ next_page_cursor: Optional[str] = None
+
+ def record_parent_cursor(state: Optional[dict[str, Any]]) -> None:
+ nonlocal next_page_cursor
+ next_page_cursor = (state or {}).get("cursor")
+
+ page_cursor = walk.parent_cursor
+ done_in_page = set(walk.completed_customers)
+ pool = ThreadPoolExecutor(max_workers=USAGE_CUSTOMER_CONCURRENCY, thread_name_prefix="metronome-usage")
+
+ cancelled = threading.Event()
+
+ def submit_walk(customer_id: str) -> "Future[list[Any]]":
+ return submit_with_context(
+ pool, lambda: _usage_rows_for_customer(clients.get(), config, json_body, customer_id, cancelled)
+ )
+
+ try:
+ for page_index, customer_page in enumerate(
+ clients.get().paginate(
+ parent.path,
+ params=_list_params(parent),
+ data_selector=DATA_SELECTOR,
+ data_selector_required=True,
+ paginator=paginator,
+ resume_hook=record_parent_cursor,
+ )
+ ):
+ if page_index:
+ # The hook fired while this page was being fetched, so its cursor is only known now.
+ page_cursor = next_page_cursor
+ done_in_page = set()
+
+ 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 = [], []
+
+ if batch:
+ yield batch
+ done_in_page.update(batch_customers)
+ commit_checkpoint(page_cursor, tuple(done_in_page))
+ 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.
+ cancelled.set()
+ pool.shutdown(wait=False, cancel_futures=True)
def _float_usage_value(row: dict[str, Any]) -> dict[str, Any]:
@@ -520,6 +776,39 @@ def metronome_source(
walk = _walk_start(endpoint_config, resumable_source_manager, db_incremental_field_last_value, history_start)
+ # 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.
+ if endpoint_config.window_size is not None:
+ usage_resource = cast(
+ dict[str, Any],
+ get_resource(
+ endpoint, should_use_incremental_field, incremental_field, walk.ending_before, walk.starting_on
+ ),
+ )
+ json_body = cast(dict[str, Any], usage_resource["endpoint"]).get("json", {})
+ clients = _PacedClients(
+ 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:
+ # 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
+ resumable_source_manager.save_state(
+ MetronomeResumeConfig(
+ ending_before=walk.ending_before,
+ starting_on=walk.starting_on,
+ parent_cursor=parent_cursor,
+ completed_customers=completed,
+ )
+ )
+
+ return _make_source_response(
+ endpoint_config,
+ lambda: _parallel_usage_pages(clients, endpoint_config, json_body, walk, commit_usage_checkpoint),
+ chunk_size=1,
+ )
+
config: RESTAPIConfig = {
"client": _rest_api_client_config(api_key),
"resource_defaults": {},
@@ -534,41 +823,25 @@ def metronome_source(
],
}
- # 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
+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None
+ if resumable_source_manager is not None:
- 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 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: Optional[Callable[[Optional[dict[str, Any]]], None]] = None
- if resumable_source_manager is not None:
- resume_hook = hold if coalesces_pages else persist
+ resume_hook = persist
resource = rest_api_resource(
config,
@@ -580,14 +853,9 @@ def metronome_source(
)
# `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
- )
+ # 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. The fan-out tables above don't resume, so they keep the default.
return _make_source_response(endpoint_config, lambda: resource, chunk_size=1)
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.py
index ed3a0169f82e..6318726573bc 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
@@ -34,6 +34,39 @@ WindowSize = Literal["none", "hour", "day"]
USAGE_DAILY_HISTORY = timedelta(days=365)
USAGE_HOURLY_HISTORY = timedelta(days=30)
+# The depths a user can pick per source. `POST /v1/usage` takes no page-size parameter and pages per
+# customer and billable metric, so a first sync costs one request per page whatever the account's
+# size, and depth is the only lever over how long that sync takes. The daily table is labelled in
+# months because that is the grain people reason about it in; twelve months is 365 days, which is
+# what this source shipped with.
+DEFAULT_USAGE_HOURLY_HISTORY_DAYS = 30
+DEFAULT_USAGE_DAILY_HISTORY_MONTHS = 12
+# Upper bounds, because a depth the endpoint cannot get through in one sync leaves the table empty
+# rather than shallow, which reads to the user as broken rather than as a setting they chose.
+MAX_USAGE_HOURLY_HISTORY_DAYS = 30
+MAX_USAGE_DAILY_HISTORY_MONTHS = 24
+# A month has no fixed length. This is the average that keeps twelve months at the 365 days this
+# source shipped with, so an unset daily depth reads exactly the window it read before.
+DAYS_PER_MONTH = 365 / 12
+
+
+def _bounded(value: int | None, default: int, highest: int) -> int:
+ """An unset depth reads the default; one outside the range is held to it rather than dropped."""
+ if value is None:
+ return default
+ return max(1, min(value, highest))
+
+
+def usage_history_window(schema_name: str, hourly_days: int | None, daily_months: int | None) -> timedelta | None:
+ """How far back a first sync of one bucketed usage table reaches."""
+ if schema_name == "usage_hourly":
+ return timedelta(days=_bounded(hourly_days, DEFAULT_USAGE_HOURLY_HISTORY_DAYS, MAX_USAGE_HOURLY_HISTORY_DAYS))
+ if schema_name == "usage_daily":
+ months = _bounded(daily_months, DEFAULT_USAGE_DAILY_HISTORY_MONTHS, MAX_USAGE_DAILY_HISTORY_MONTHS)
+ return timedelta(days=months * DAYS_PER_MONTH)
+ return None
+
+
# 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
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 cce2e79f566a..438ea1b783af 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
@@ -28,10 +28,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.
validate_credentials as validate_metronome_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import (
+ DEFAULT_USAGE_DAILY_HISTORY_MONTHS,
+ DEFAULT_USAGE_HOURLY_HISTORY_DAYS,
ENDPOINTS,
INCREMENTAL_FIELDS,
METRONOME_ENDPOINTS,
USAGE_HISTORY,
+ usage_history_window,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -85,11 +88,17 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConf
].default_incremental_lookback_seconds
return schemas
- def history_lookback_for_schema(self, schema_name: str) -> timedelta | None:
+ 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.get(schema_name)
+ 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,
@@ -145,6 +154,22 @@ class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConf
placeholder="",
secret=True,
),
+ SourceFieldInputConfig(
+ name="usage_hourly_history_days",
+ label="Hourly usage history (days)",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder=str(DEFAULT_USAGE_HOURLY_HISTORY_DAYS),
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="usage_daily_history_months",
+ label="Daily usage history (months)",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder=str(DEFAULT_USAGE_DAILY_HISTORY_MONTHS),
+ secret=False,
+ ),
],
),
)
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 be8581c07fa2..96ca6f467c1e 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
@@ -1,4 +1,6 @@
-from datetime import UTC, datetime
+import threading
+from collections import deque
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
import pytest
@@ -13,12 +15,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome import (
EPOCH_RFC_3339,
+ USAGE_CUSTOMER_CONCURRENCY,
MetronomeCursorPaginator,
MetronomeResumeConfig,
+ MetronomeWalkStart,
_clamp_window_start,
- _coalesced_pages,
+ _fill_in_flight,
_format_rfc3339,
_paginator_for,
+ _parallel_usage_pages,
+ _usage_rows_for_customer,
+ _WalkCancelled,
get_resource,
metronome_source,
validate_credentials,
@@ -235,52 +242,153 @@ class TestMetronomeResources:
assert body["ending_before"].endswith("T00:00:00Z")
-class TestMetronomeCoalescing:
- @patch(f"{TRANSPORT}.USAGE_COALESCE_PAGES", 2)
+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:
+ self.customer_pages = customer_pages
+ self.rows_by_customer = rows_by_customer
+ self.page_cursors = list(page_cursors)
+ self.usage_bodies: list[dict[str, Any]] = []
+
+ def paginate(self, path, **kwargs):
+ if path == "/v1/customers":
+ hook = kwargs.get("resume_hook")
+ for index, page in enumerate(self.customer_pages):
+ yield page
+ # `RESTClient` offers the next page's cursor once the consumer asks for it.
+ if hook is not None:
+ cursor = self.page_cursors[index] if index < len(self.page_cursors) else None
+ hook({"cursor": cursor} if cursor else None)
+ return
+ body = kwargs["json"]
+ self.usage_bodies.append(body)
+ yield self.rows_by_customer[body["customer_ids"][0]]
+
+
+class _FakeClients:
+ def __init__(self, client) -> None:
+ self._client = client
+
+ def get(self):
+ return self._client
+
+
+class TestMetronomeParallelUsage:
+ def _run(self, client, walk, commit=None, endpoint="usage_daily"):
+ return list(
+ _parallel_usage_pages(
+ cast(Any, _FakeClients(client)),
+ METRONOME_ENDPOINTS[endpoint],
+ {"window_size": "DAY"},
+ walk,
+ commit or (lambda cursor, completed: None),
+ )
+ )
+
+ def test_each_customer_is_asked_for_on_its_own(self) -> None:
+ # The partition is the whole point: without `customer_ids` every walk would re-read the
+ # entire account, and there would be nothing independent to run in parallel.
+ client = _FakeUsageClient([[{"id": "c1"}, {"id": "c2"}]], {"c1": [{"value": 1}], "c2": [{"value": 2}]})
+
+ self._run(client, MetronomeWalkStart())
+
+ assert [body["customer_ids"] for body in client.usage_bodies] == [["c1"], ["c2"]]
+ # The pinned window rides every partitioned request, not just the first.
+ assert {body["window_size"] for body in client.usage_bodies} == {"DAY"}
+
+ def test_the_usage_amount_is_still_floated(self) -> None:
+ # This path builds its own requests, so the resource's `data_map` never runs on it. Losing
+ # the cast here would put an integer column back and fail the sync on the first fraction.
+ client = _FakeUsageClient([[{"id": "c1"}]], {"c1": [{"value": 7}, {"value": None}]})
+
+ batches = self._run(client, MetronomeWalkStart())
+
+ 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 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.
+ # 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}]})
+
+ for batch in _parallel_usage_pages(
+ cast(Any, _FakeClients(client)),
+ METRONOME_ENDPOINTS["usage_daily"],
+ {"window_size": "DAY"},
+ MetronomeWalkStart(),
+ lambda cursor, completed: events.append(f"commit-{sorted(completed)}") if completed else None,
+ ):
+ events.append(f"flush-{len(batch)}")
- def pages():
- for index in range(5):
- events.append(f"page-{index}")
- yield [{"n": index}]
+ assert events == ["flush-1", "commit-['c1']"]
- for batch in _coalesced_pages(pages(), lambda: events.append("commit")):
- events.append(f"flush-{len(batch)}")
+ def 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
+ # resumes, which is what a full refresh does.
+ client = _FakeUsageClient([[{"id": "c1"}, {"id": "c2"}]], {"c1": [{"value": 1}], "c2": [{"value": 2}]})
- # 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",
- ]
+ self._run(client, MetronomeWalkStart(completed_customers=("c1",)))
+
+ assert [body["customer_ids"] for body in client.usage_bodies] == [["c2"]]
- @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))
+ def test_the_second_page_checkpoints_the_cursor_that_fetched_it(self) -> None:
+ # `RESTClient.paginate` advances a deep copy of the paginator, so reading the cursor off the
+ # instance here would leave it stuck and a resumed run would restart at the first page.
+ client = _FakeUsageClient(
+ [[{"id": "c1"}], [{"id": "c2"}]],
+ {"c1": [{"value": 1}], "c2": [{"value": 2}]},
+ page_cursors=["cursor-page-2"],
+ )
+ commits: list[tuple[Any, tuple[str, ...]]] = []
+
+ self._run(client, MetronomeWalkStart(), commit=lambda cursor, done: commits.append((cursor, done)))
+
+ assert commits == [(None, ("c1",)), ("cursor-page-2", ("c2",))]
+
+ def test_only_as_many_walks_are_submitted_as_there_are_workers(self) -> None:
+ # Submitting a whole page at once leaves every finished customer's rows in memory behind a
+ # slow one, which is how a batch gets past the row cap.
+ submitted: list[str] = []
+ todo = deque(["c1", "c2", "c3", "c4", "c5", "c6"])
+ in_flight: deque[Any] = deque()
+
+ _fill_in_flight(lambda customer_id: cast(Any, submitted.append(customer_id)), todo, in_flight)
+
+ assert len(submitted) == USAGE_CUSTOMER_CONCURRENCY
+ assert len(todo) == 6 - USAGE_CUSTOMER_CONCURRENCY
+
+ @parameterized.expand([("null", None), ("empty", "")])
+ def test_a_customer_with_no_id_fails_the_walk(self, _name, bad_id) -> None:
+ # `str(None)` would ask Metronome for a customer called "None", and skipping the row would
+ # drop that customer's usage from the table with no signal.
+ client = _FakeUsageClient([[{"id": bad_id}]], {})
- sizes = [len(batch) for batch in _coalesced_pages(pages, lambda: None)]
+ with pytest.raises(ValueError, match="no id"):
+ self._run(client, MetronomeWalkStart())
- assert sizes == [2, 2, 2]
- assert max(sizes) <= 3
+ def test_a_cancelled_walk_stops_at_the_next_page(self) -> None:
+ # `cancel_futures` only drops walks that never started, so one already running has to stop
+ # itself, or it keeps spending the account's request budget after the consumer has gone and
+ # holds the pool's threads open on the way out.
+ pages_served: list[int] = []
- @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 _Client:
+ def paginate(self, path, **kwargs):
+ for index in range(5):
+ pages_served.append(index)
+ yield [{"value": index}]
+
+ cancelled = threading.Event()
+ cancelled.set()
+
+ with pytest.raises(_WalkCancelled):
+ _usage_rows_for_customer(cast(Any, _Client()), METRONOME_ENDPOINTS["usage_daily"], {}, "c1", cancelled)
+
+ # It raises rather than returning what it had: the checkpoint records whole customers, so a
+ # partial one must never be mistakable for a finished one.
+ assert pages_served == [0]
class TestMetronomeSourceResponse:
@@ -355,9 +463,9 @@ class TestMetronomeSourceResponse:
),
]
)
- @patch(f"{TRANSPORT}.rest_api_resource")
+ @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_rest_api_resource
+ self, _name, endpoint, watermark, history_start, 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
@@ -371,13 +479,13 @@ class TestMetronomeSourceResponse:
should_use_incremental_field=watermark is not None,
db_incremental_field_last_value=watermark,
history_start=history_start,
- )
+ ).items()
- body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]
+ body = mock_parallel.call_args.args[2]
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:
+ @patch(f"{TRANSPORT}._parallel_usage_pages")
+ def test_resumed_bucketed_run_replays_the_stored_lower_bound(self, mock_parallel) -> 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()
@@ -388,9 +496,9 @@ class TestMetronomeSourceResponse:
metronome_source(
api_key="tok", endpoint="usage_daily", team_id=1, job_id="job-1", resumable_source_manager=manager
- )
+ ).items()
- body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]
+ body = mock_parallel.call_args.args[2]
assert body["starting_on"] == "2026-05-01T00:00:00Z"
assert body["ending_before"] == "2026-06-01T00:00:00Z"
@@ -408,98 +516,84 @@ class TestMetronomeSourceResponse:
@parameterized.expand(
[
- # Stored a cutoff: replay that exact window and resume from its cursor, keeping the key.
+ # Stored a cutoff: replay that exact window and resume where the customer list had
+ # reached, keeping the key.
(
"with_stored_window",
- MetronomeResumeConfig(next_page="cursor-9", ending_before="2020-06-01T00:00:00Z"),
+ MetronomeResumeConfig(parent_cursor="cursor-9", ending_before="2020-06-01T00:00:00Z"),
"2020-06-01T00:00:00Z",
- {"cursor": "cursor-9"},
+ "cursor-9",
False,
),
# A checkpoint written before the cutoff was stored carries none, so the walk restarts
# with a fresh window and no seeded cursor rather than mixing two windows. The stale key
# is cleared so the pipeline's own resume probe doesn't append onto the partial table.
- ("pre_window_checkpoint", MetronomeResumeConfig(next_page="cursor-9"), None, None, True),
+ ("pre_window_checkpoint", MetronomeResumeConfig(parent_cursor="cursor-9"), None, None, True),
]
)
- @patch(f"{TRANSPORT}.rest_api_resource")
+ @patch(f"{TRANSPORT}._parallel_usage_pages")
def test_resumed_usage_run_pins_the_window(
self,
_name,
resume_state,
expected_window,
- expected_paginator_state,
+ expected_parent_cursor,
expect_state_cleared,
- mock_rest_api_resource,
+ mock_parallel,
) -> None:
manager = MagicMock()
manager.can_resume.return_value = True
manager.load_state.return_value = resume_state
- metronome_source(api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager)
+ metronome_source(
+ api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager
+ ).items()
- body = mock_rest_api_resource.call_args.args[0]["resources"][0]["endpoint"]["json"]
+ body = mock_parallel.call_args.args[2]
if expected_window is not None:
assert body["ending_before"] == expected_window
else:
assert body["ending_before"] > EPOCH_RFC_3339
- assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == expected_paginator_state
+ assert mock_parallel.call_args.args[3].parent_cursor == expected_parent_cursor
assert manager.clear_state.called == expect_state_cleared
- @patch(f"{TRANSPORT}.rest_api_resource")
- def test_usage_checkpoint_saves_the_window_it_synced_with(self, mock_rest_api_resource) -> None:
+ @patch(f"{TRANSPORT}._parallel_usage_pages")
+ def test_usage_checkpoint_saves_the_window_it_synced_with(self, mock_parallel) -> None:
# The cutoff written into the request body and the cutoff saved for a resume must be the
# same instant, or a retry can't replay the identical window.
manager = MagicMock()
manager.can_resume.return_value = False
- metronome_source(api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager)
+ metronome_source(
+ api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager
+ ).items()
- 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"})
+ synced_body = mock_parallel.call_args.args[2]
+ commit_checkpoint = mock_parallel.call_args.args[4]
+ commit_checkpoint("cursor-3", ("c1",))
manager.save_state.assert_called_once_with(
MetronomeResumeConfig(
- next_page="cursor-3",
ending_before=synced_body["ending_before"],
starting_on=synced_body["starting_on"],
+ parent_cursor="cursor-3",
+ completed_customers=("c1",),
)
)
- @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:
+ @patch(f"{TRANSPORT}._parallel_usage_pages")
+ def test_a_finished_customer_list_checkpoints_nothing(self, mock_parallel) -> None:
+ # The last page commits with no cursor and nothing outstanding. Persisting that would make
+ # the next attempt resume into a walk with everything still to do.
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
+ metronome_source(
+ api_key="tok", endpoint="usage", team_id=1, job_id="job-1", resumable_source_manager=manager
+ ).items()
+ mock_parallel.call_args.args[4](None, ())
+
+ assert manager.save_state.called is False
@patch(f"{TRANSPORT}.build_dependent_resource")
def test_invoices_fan_out_over_customers(self, mock_build) -> None:
@@ -621,3 +715,32 @@ class TestMetronomeSchemas:
assert schema.supports_incremental is False
assert schema.should_sync_default is True
assert schema.default_incremental_lookback_seconds is None
+
+ @parameterized.expand(
+ [
+ ("hourly_default", "usage_hourly", None, None, 30),
+ ("hourly_chosen", "usage_hourly", 7, None, 7),
+ ("daily_default", "usage_daily", None, None, 365),
+ ("daily_chosen_reads_as_months", "usage_daily", None, 3, 365 / 4),
+ # Held to the range rather than dropped, so a depth nobody can finish cannot be typed in.
+ ("above_the_range_is_held_to_it", "usage_hourly", 999, None, 30),
+ ("below_the_range_is_held_to_it", "usage_daily", None, 0, 365 / 12),
+ ("a_table_with_no_window", "customers", 7, 3, None),
+ ]
+ )
+ def test_the_usage_history_window_follows_the_source_setting(
+ self, _name, schema_name, hourly, daily, expected_days
+ ) -> None:
+ source = MetronomeSource()
+ config = source.parse_config(
+ {"api_key": "tok", "usage_hourly_history_days": hourly, "usage_daily_history_months": daily}
+ )
+
+ window = source.history_lookback_for_schema(schema_name, config)
+
+ assert window == (timedelta(days=expected_days) if expected_days is not None else None)
+
+ 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)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py
index e64e7017dfb7..bbbfd2d765c3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/custom.py
@@ -1,22 +1,23 @@
-import time
import threading
-import contextvars
from collections.abc import Callable, Iterator
-from concurrent.futures import Future, ThreadPoolExecutor
+from concurrent.futures import ThreadPoolExecutor
from typing import Optional, ParamSpec, TypeVar
import stripe as stripe_lib
from stripe import Invoice, InvoiceLineItem, InvoiceService, ListObject, StripeClient
from structlog.types import FilteringBoundLogger
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.request_pacer import (
+ RequestPacer,
+ submit_with_context,
+)
+
# Stripe's test-mode read limit is 25 requests/s and the live-mode limit is 100. Five workers stay
# under both, and the page fetch is the longer leg of an iteration, so more would not shorten a sweep.
LINE_FETCH_CONCURRENCY = 5
# Fast responses could still let five workers exceed the test-mode limit, so request starts are paced
# independently of the worker count. The limit is per account, shared with every other caller.
LINE_REQUESTS_PER_SECOND = 20.0
-# How long a 429 keeps the pool at a reduced rate when Stripe sends no Retry-After.
-RATE_LIMIT_HOLD_SECONDS = 30.0
_P = ParamSpec("_P")
_T = TypeVar("_T")
@@ -26,77 +27,6 @@ RateLimitCallback = Callable[[Optional[float]], None]
ClientFactory = Callable[[RateLimitCallback], StripeClient]
-class _RequestPacer:
- """Spaces request starts across threads and slows the whole pool after a rate limit.
-
- Every worker calls wait_turn() before a request, so the pool never starts more than
- `per_second` requests in any second. A 429 halves the rate for the hold window and, when
- Stripe sends Retry-After, holds every worker until it passes, including workers already
- waiting for a slot. Each quiet window after that doubles the rate back until the base rate
- is restored.
- """
-
- def __init__(
- self,
- per_second: float,
- clock: Callable[[], float] = time.monotonic,
- sleep: Callable[[float], None] = time.sleep,
- ) -> None:
- self._base_interval = 1.0 / per_second
- self._interval = self._base_interval
- self._clock = clock
- self._sleep = sleep
- self._lock = threading.Lock()
- self._next_start = 0.0
- self._hold_until = 0.0
- self._recover_at: Optional[float] = None
-
- def wait_turn(self) -> None:
- start = self._reserve_slot()
- while True:
- delay = start - self._clock()
- if delay > 0:
- self._sleep(delay)
- with self._lock:
- if self._hold_until <= start:
- return
- # A throttle arrived during the sleep and its hold covers this slot: take a later one.
- start = self._reserve_slot()
-
- def _reserve_slot(self) -> float:
- with self._lock:
- now = self._clock()
- if self._recover_at is not None and now >= self._recover_at:
- self._interval = max(self._interval / 2, self._base_interval)
- self._recover_at = None if self._interval == self._base_interval else now + RATE_LIMIT_HOLD_SECONDS
- start = max(now, self._next_start)
- self._next_start = start + self._interval
- return start
-
- def throttled(self, retry_after: Optional[float]) -> None:
- with self._lock:
- now = self._clock()
- if now < self._hold_until:
- # Requests already in flight when the first 429 landed report the same throttle.
- return
- hold = retry_after if retry_after is not None and retry_after > 0 else RATE_LIMIT_HOLD_SECONDS
- self._interval = min(self._interval * 2, self._base_interval * 16)
- if retry_after is not None and retry_after > 0:
- self._hold_until = now + retry_after
- self._next_start = max(self._next_start, self._hold_until)
- self._recover_at = now + hold
-
-
-def _submit(pool: ThreadPoolExecutor, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]:
- """Run `fn` on the pool inside a copy of the caller's context.
-
- Pool threads start with an empty context, which would strip the team and job labels that the
- HTTP observer and structlog read from contextvars.
- """
- ctx = contextvars.copy_context()
- return pool.submit(lambda: ctx.run(fn, *args, **kwargs))
-
-
class InvoiceListWithAllLines:
"""Invoice listing that expands each invoice's line items.
@@ -121,7 +51,7 @@ class InvoiceListWithAllLines:
self.logger = logger
self._client_factory = client_factory
self._concurrency = concurrency
- self._pacer = _RequestPacer(requests_per_second)
+ self._pacer = RequestPacer(requests_per_second)
self._thread_clients = threading.local()
def auto_paging_iter(self) -> Iterator[Invoice]:
@@ -135,9 +65,11 @@ class InvoiceListWithAllLines:
pool = ThreadPoolExecutor(max_workers=self._concurrency + 1, thread_name_prefix="stripe-invoice-lines")
try:
while not page.is_empty:
- next_page = _submit(pool, page.next_page)
+ next_page = submit_with_context(pool, page.next_page)
line_futures = [
- _submit(pool, self._fetch_lines, invoice.id) if invoice.lines.has_more and invoice.id else None
+ submit_with_context(pool, self._fetch_lines, invoice.id)
+ if invoice.lines.has_more and invoice.id
+ else None
for invoice in page.data
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
index a3c61f94d4f8..b338035992cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/stripe/tests/test_stripe_source.py
@@ -80,7 +80,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.con
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.custom import (
InvoiceListWithAllLines,
RateLimitCallback,
- _RequestPacer,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.settings import (
ENDPOINTS,
@@ -696,68 +695,6 @@ class _FakeInvoicePage:
return self._next if self._next is not None else _FakeInvoicePage([])
-class TestRequestPacer:
- def _pacer(self, per_second: float = 10.0) -> tuple[_RequestPacer, dict[str, float], list[float]]:
- clock = {"now": 0.0}
- sleeps: list[float] = []
- return _RequestPacer(per_second, clock=lambda: clock["now"], sleep=sleeps.append), clock, sleeps
-
- def test_spaces_request_starts_at_the_base_rate(self):
- pacer, _clock, sleeps = self._pacer()
-
- for _ in range(3):
- pacer.wait_turn()
-
- assert sleeps == pytest.approx([0.1, 0.2])
-
- def test_a_rate_limit_holds_for_retry_after_and_halves_the_rate(self):
- pacer, _clock, sleeps = self._pacer()
- pacer.wait_turn()
-
- pacer.throttled(retry_after=5)
- pacer.wait_turn()
- pacer.wait_turn()
-
- assert sleeps == pytest.approx([5.0, 5.2])
-
- def test_a_rate_limit_holds_a_worker_that_already_reserved_its_slot(self):
- clock = {"now": 0.0}
- sleeps: list[float] = []
-
- def sleep(seconds: float) -> None:
- sleeps.append(seconds)
- clock["now"] += seconds
- if len(sleeps) == 1:
- pacer.throttled(retry_after=5)
-
- pacer = _RequestPacer(10.0, clock=lambda: clock["now"], sleep=sleep)
- pacer.wait_turn()
- pacer.wait_turn()
-
- assert sleeps == pytest.approx([0.1, 5.0])
-
- def test_rate_limits_reported_during_a_hold_do_not_compound(self):
- pacer, clock, sleeps = self._pacer()
- pacer.throttled(retry_after=5)
- pacer.throttled(retry_after=5)
-
- clock["now"] = 4.9
- pacer.wait_turn()
- pacer.wait_turn()
-
- assert sleeps == pytest.approx([0.1, 0.3])
-
- def test_the_rate_recovers_after_a_quiet_window(self):
- pacer, clock, sleeps = self._pacer()
- pacer.throttled(retry_after=None)
-
- clock["now"] = 31.0
- pacer.wait_turn()
- pacer.wait_turn()
-
- assert sleeps == pytest.approx([0.1])
-
-
class TestInvoiceListWithAllLines:
def test_expands_lines_across_pages_in_list_order(self):
pages = _FakeInvoicePage(