Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(klaviyo): send a custom timeframe for weekly series reports (#93890)

posthog[bot]57503b88fa2d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
index e121ec752d2b..34c6078bee1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/canonical_descriptions.py
@@ -45,7 +45,7 @@ _CATALOG_SHARED_COLUMNS = {
# Both values reports return the same statistics; only the grouping columns differ. Rate statistics
# come back as fractions between 0 and 1.
_VALUES_REPORT_STATISTIC_COLUMNS = {
- "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "timeframe_key": "The timeframe the statistics were computed over.",
"conversion_metric_id": "ID of the metric conversion statistics were attributed to.",
"send_channel": "The channel the message was sent through (email, sms, push-notification, or whatsapp).",
"average_order_value": "Average value of the orders attributed to the message.",
@@ -88,7 +88,7 @@ _SERIES_REPORT_DATE_TIME_COLUMN = {
# Form reports take their own statistic set. Rate statistics come back as fractions between 0 and 1.
_FORM_REPORT_STATISTIC_COLUMNS = {
- "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "timeframe_key": "The timeframe the statistics were computed over.",
"closed_form": "Number of times the form was closed.",
"closed_form_uniques": "Number of people who closed the form.",
"qualified_form": "Number of times the form qualified to show.",
@@ -105,7 +105,7 @@ _FORM_REPORT_STATISTIC_COLUMNS = {
# Segment reports report on membership churn over the window.
_SEGMENT_REPORT_STATISTIC_COLUMNS = {
- "timeframe_key": "The Klaviyo timeframe the statistics were computed over.",
+ "timeframe_key": "The timeframe the statistics were computed over.",
"members_added": "Number of profiles added to the segment.",
"members_removed": "Number of profiles removed from the segment.",
"net_members_changed": "Net change in the segment's membership (added minus removed).",
@@ -317,8 +317,8 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"flow_series_reports": {
"description": (
- "Klaviyo's own flow-message performance statistics bucketed by week over the last 365 "
- "days, one row per flow message per week. Each sync updates the weeks Klaviyo still "
+ "Klaviyo's own flow-message performance statistics bucketed by week over the last 51 "
+ "weeks, one row per flow message per week. Each sync updates the weeks Klaviyo still "
"reports and keeps the weeks it no longer returns, so the table builds a history past "
"Klaviyo's one-year limit."
),
@@ -343,8 +343,8 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"form_series_reports": {
"description": (
- "Klaviyo's own signup-form performance statistics bucketed by week over the last 365 "
- "days, one row per form per week. Each sync updates the weeks Klaviyo still reports and "
+ "Klaviyo's own signup-form performance statistics bucketed by week over the last 51 "
+ "weeks, one row per form per week. Each sync updates the weeks Klaviyo still reports and "
"keeps the weeks it no longer returns, so the table builds a history past Klaviyo's "
"one-year limit."
),
@@ -368,7 +368,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
"segment_series_reports": {
"description": (
- "Klaviyo's own segment membership statistics bucketed by week over the last 365 days, "
+ "Klaviyo's own segment membership statistics bucketed by week over the last 51 weeks, "
"one row per segment per week. Each sync updates the weeks Klaviyo still reports and "
"keeps the weeks it no longer returns, so the table builds a history past Klaviyo's "
"one-year limit."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
index 0f49cdd17d21..e3d4d49a7dbc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
@@ -1,7 +1,8 @@
import dataclasses
from collections.abc import Iterator
-from datetime import UTC, date, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta, tzinfo
from typing import Any, Optional
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import requests
from structlog.types import FilteringBoundLogger
@@ -18,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.se
KLAVIYO_ENDPOINTS,
KlaviyoEndpointConfig,
KlaviyoFanOutConfig,
+ KlaviyoValuesReportConfig,
)
KLAVIYO_BASE_URL = "https://a.klaviyo.com/api"
@@ -478,6 +480,41 @@ def _series_rows(
yield row
+def _get_account_timezone(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> tzinfo:
+ """Read the IANA timezone of the account the API key belongs to.
+
+ Klaviyo ignores the offset on a custom timeframe's start and end and reads both as wall-clock
+ times in this timezone, so a window computed in any other timezone is off by the difference.
+ """
+ accounts = _fetch_page(session, f"{KLAVIYO_BASE_URL}/accounts", headers, logger).get("data") or []
+ name = accounts[0].get("attributes", {}).get("timezone") if accounts else None
+ if isinstance(name, str):
+ try:
+ return ZoneInfo(name)
+ except (ValueError, ZoneInfoNotFoundError):
+ pass
+ logger.warning(f"Klaviyo: account timezone {name!r} is unknown, computing the report window in UTC")
+ return UTC
+
+
+def _build_timeframe(report: KlaviyoValuesReportConfig, now: datetime) -> tuple[dict[str, str], str]:
+ """Build a report's timeframe attribute, and the label every row records the window under.
+
+ Klaviyo takes a timeframe either as one of its predefined keys or as a custom start/end pair.
+ A window no key matches goes as the custom pair: `timeframe_weeks` calendar weeks that open on
+ a Monday, Klaviyo's first day of the week, and end at `now`, which must be in the account's
+ timezone because Klaviyo reads the pair as wall-clock times in it.
+ """
+ if report.timeframe_weeks is None:
+ assert report.timeframe_key is not None
+ return {"key": report.timeframe_key}, report.timeframe_key
+
+ end = now.replace(microsecond=0)
+ this_monday = datetime.combine(end.date() - timedelta(days=end.weekday()), datetime.min.time(), tzinfo=end.tzinfo)
+ start = this_monday - timedelta(weeks=report.timeframe_weeks - 1)
+ return {"start": start.isoformat(), "end": end.isoformat()}, f"last_{report.timeframe_weeks}_weeks"
+
+
def _get_values_report_rows(
session: requests.Session,
headers: dict[str, str],
@@ -508,9 +545,11 @@ def _get_values_report_rows(
)
return
+ account_tz = _get_account_timezone(session, headers, logger) if report.timeframe_weeks is not None else UTC
+ timeframe, timeframe_label = _build_timeframe(report, datetime.now(account_tz))
attributes: dict[str, Any] = {
"statistics": report.statistics,
- "timeframe": {"key": report.timeframe_key},
+ "timeframe": timeframe,
}
if report.group_by:
attributes["group_by"] = report.group_by
@@ -526,7 +565,7 @@ def _get_values_report_rows(
# Tagged onto every row so each row records the window (and conversion metric)
# it was computed over.
- common: dict[str, Any] = {"timeframe_key": report.timeframe_key}
+ common: dict[str, Any] = {"timeframe_key": timeframe_label}
if metric_id:
common["conversion_metric_id"] = metric_id
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
index d82f7d903a8d..94e1d97a5d59 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/settings.py
@@ -26,6 +26,28 @@ class KlaviyoFanOutConfig:
grandparent: Optional["KlaviyoFanOutConfig"] = None
+# The timeframe keys Klaviyo's reporting API publishes. It rejects anything else with a 400, so a
+# window none of these covers goes as a custom start/end pair instead.
+KLAVIYO_TIMEFRAME_KEYS = frozenset(
+ {
+ "today",
+ "yesterday",
+ "this_week",
+ "last_week",
+ "this_month",
+ "last_month",
+ "this_year",
+ "last_year",
+ "last_7_days",
+ "last_30_days",
+ "last_90_days",
+ "last_365_days",
+ "last_3_months",
+ "last_12_months",
+ }
+)
+
+
@frozen
class KlaviyoValuesReportConfig:
"""A Klaviyo reporting query: POST a statistics request, get one row back per grouping.
@@ -36,8 +58,13 @@ class KlaviyoValuesReportConfig:
report_type: str # JSON:API resource type the request body declares
statistics: list[str] # statistics to request; rate statistics come back as fractions [0, 1]
- timeframe_key: str # Klaviyo's predefined timeframe key, capped at one year by the API
group_by: list[str] # grouping attributes; empty means the report groups by its own default
+ # The window the report covers. Set exactly one of these two. `timeframe_key` is one of
+ # Klaviyo's predefined keys, sent as {"key": ...}. `timeframe_weeks` is a number of calendar
+ # weeks ending with the current one, sent as a custom {"start": ..., "end": ...} pair computed
+ # in the account's timezone, for a window no key matches.
+ timeframe_key: Optional[str] = None
+ timeframe_weeks: Optional[int] = None
# Set for a series report, which buckets the window by this interval and returns each grouping's
# statistics as arrays aligned to a top-level date_times list. The source expands them into one
# row per bucket tagged with `date_time`. Left None for a values report, which returns one scalar
@@ -47,6 +74,14 @@ class KlaviyoValuesReportConfig:
# reports do not accept one, so their requests must omit it and skip the /metrics lookup.
requires_conversion_metric: bool = True
+ def __post_init__(self) -> None:
+ # Klaviyo requires a timeframe and accepts only one form of it, so a config that sets both
+ # or neither 400s every request the endpoint makes.
+ if (self.timeframe_key is None) == (self.timeframe_weeks is None):
+ raise ValueError(f"{self.report_type}: set exactly one of timeframe_key or timeframe_weeks")
+ if self.timeframe_key is not None and self.timeframe_key not in KLAVIYO_TIMEFRAME_KEYS:
+ raise ValueError(f"{self.report_type}: {self.timeframe_key} is not a Klaviyo timeframe key")
+
@dataclass
class KlaviyoEndpointConfig:
@@ -120,18 +155,23 @@ VALUES_REPORT_STATISTICS = [
# The widest window Klaviyo's reporting API allows is one year.
VALUES_REPORT_TIMEFRAME_KEY = "last_365_days"
-# Klaviyo caps weekly-interval series reports at exactly 52 weeks. last_365_days (365 days) exceeds
-# that by one day (52 * 7 = 364), so series reports need their own shorter timeframe key.
-SERIES_REPORT_TIMEFRAME_KEY = "last_52_weeks"
+# Klaviyo caps a weekly-interval series report at 52 weeks and publishes no timeframe key that long:
+# its keys step from three months straight to last_365_days, one day over the cap. Series reports
+# therefore send a custom start/end window of this many calendar weeks, the current week included.
+# The window opens on a Monday, which is where Klaviyo starts a week, so every bucket but the current
+# one is a complete week and re-syncing never shrinks a stored week. 52 weeks would put the window at
+# 52 weeks minus one second late on a Sunday, and a DST change inside the window adds up to an hour to
+# the elapsed time Klaviyo measures, so one week of margin keeps every request under the cap.
+SERIES_REPORT_TIMEFRAME_WEEKS = 51
# Series reports bucket the window by an interval. Klaviyo caps an hourly interval at 7 days and a
# daily one at 60, so a weekly interval gives the fullest view within the 52-week series limit
-# (52 rows per grouping).
+# (51 rows per grouping).
SERIES_REPORT_INTERVAL = "weekly"
# A series row is one time bucket, so date_time is a real per-row cursor even though the request
# always asks for the whole window. Selecting it makes the sync merge on the primary key rather than
-# replace the table, so buckets that age out of Klaviyo's 52-week window stay in the warehouse while
+# replace the table, so buckets that age out of the window stay in the warehouse while
# the buckets still inside it keep getting corrected.
SERIES_REPORT_INCREMENTAL_FIELDS: list[IncrementalField] = [
{
@@ -525,12 +565,12 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
values_report=KlaviyoValuesReportConfig(
report_type="flow-series-report",
statistics=VALUES_REPORT_STATISTICS,
- timeframe_key=SERIES_REPORT_TIMEFRAME_KEY,
+ timeframe_weeks=SERIES_REPORT_TIMEFRAME_WEEKS,
group_by=["flow_id", "flow_message_id", "send_channel"],
interval=SERIES_REPORT_INTERVAL,
),
description=(
- "Klaviyo's own flow-message performance statistics bucketed by week over the last 52 "
+ "Klaviyo's own flow-message performance statistics bucketed by week over the last 51 "
"weeks, one row per flow message per week. Weeks stay in the table after Klaviyo stops "
"returning them"
),
@@ -582,13 +622,13 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
values_report=KlaviyoValuesReportConfig(
report_type="form-series-report",
statistics=FORM_REPORT_STATISTICS,
- timeframe_key=SERIES_REPORT_TIMEFRAME_KEY,
+ timeframe_weeks=SERIES_REPORT_TIMEFRAME_WEEKS,
group_by=["form_id"],
interval=SERIES_REPORT_INTERVAL,
requires_conversion_metric=False,
),
description=(
- "Klaviyo's own signup-form performance statistics bucketed by week over the last 52 "
+ "Klaviyo's own signup-form performance statistics bucketed by week over the last 51 "
"weeks, one row per form per week. Weeks stay in the table after Klaviyo stops returning "
"them"
),
@@ -603,13 +643,13 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
values_report=KlaviyoValuesReportConfig(
report_type="segment-series-report",
statistics=SEGMENT_REPORT_STATISTICS,
- timeframe_key=SERIES_REPORT_TIMEFRAME_KEY,
+ timeframe_weeks=SERIES_REPORT_TIMEFRAME_WEEKS,
group_by=[],
interval=SERIES_REPORT_INTERVAL,
requires_conversion_metric=False,
),
description=(
- "Klaviyo's own segment membership statistics bucketed by week over the last 52 weeks, "
+ "Klaviyo's own segment membership statistics bucketed by week over the last 51 weeks, "
"one row per segment per week. Weeks stay in the table after Klaviyo stops returning "
"them"
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
index 7c6654dcbcc0..d035acd49644 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/test_klaviyo.py
@@ -29,8 +29,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.kl
)
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.settings import (
KLAVIYO_ENDPOINTS,
- SERIES_REPORT_TIMEFRAME_KEY,
+ SERIES_REPORT_TIMEFRAME_WEEKS,
KlaviyoEndpointConfig,
+ KlaviyoValuesReportConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.source import KlaviyoSource
@@ -1047,6 +1048,9 @@ class TestValuesReports:
class TestReportVariants:
+ # Monday 03:30 UTC, which is still Sunday evening in the account's timezone. A window computed in
+ # UTC would open a week later and end seven hours ahead of the account's clock.
+ @freeze_time("2026-09-14T03:30:00Z")
def test_series_report_carries_interval_and_expands_each_bucket_into_a_row(self, monkeypatch: Any) -> None:
# Series reports return each statistic as an array aligned to a top-level date_times list;
# keeping the arrays nested would leave the table unqueryable and collapse the weekly rows.
@@ -1076,6 +1080,8 @@ class TestReportVariants:
},
"links": {},
}
+ if url.endswith("/accounts"):
+ return {"data": [{"id": "A1", "attributes": {"timezone": "America/Los_Angeles"}}]}
return {"data": [{"id": "M_ORDER", "attributes": {"name": "Placed Order"}}], "links": {}}
monkeypatch.setattr(klaviyo, "_fetch_page", fake_fetch)
@@ -1090,7 +1096,13 @@ class TestReportVariants:
for row in table.to_pylist()
]
- assert captured["body"]["data"]["attributes"]["interval"] == "weekly"
+ attributes = captured["body"]["data"]["attributes"]
+ assert attributes["interval"] == "weekly"
+ # Klaviyo rejects a weekly series report whose window is over 52 weeks, and rejects any
+ # timeframe key it does not publish, so the window goes as a custom start/end pair. Klaviyo
+ # ignores the offset on the pair and reads it in the account's timezone, so the pair must be
+ # computed there: 51 weeks that open on a Monday and end at the account's current time.
+ assert attributes["timeframe"] == {"start": "2025-09-22T00:00:00-07:00", "end": "2026-09-13T20:30:00-07:00"}
assert rows == [
{
"flow_id": "F1",
@@ -1098,7 +1110,7 @@ class TestReportVariants:
"send_channel": "email",
"date_time": "2026-01-05T00:00:00+00:00",
"opens": 1,
- "timeframe_key": SERIES_REPORT_TIMEFRAME_KEY,
+ "timeframe_key": f"last_{SERIES_REPORT_TIMEFRAME_WEEKS}_weeks",
"conversion_metric_id": "M_ORDER",
},
{
@@ -1107,7 +1119,7 @@ class TestReportVariants:
"send_channel": "email",
"date_time": "2026-01-12T00:00:00+00:00",
"opens": 2,
- "timeframe_key": SERIES_REPORT_TIMEFRAME_KEY,
+ "timeframe_key": f"last_{SERIES_REPORT_TIMEFRAME_WEEKS}_weeks",
"conversion_metric_id": "M_ORDER",
},
]
@@ -1162,7 +1174,7 @@ class TestReportVariants:
]
)
def test_series_reports_key_on_the_time_bucket(self, endpoint: str) -> None:
- # Without date_time in the primary key, the ~52 weekly rows per grouping collapse to one on
+ # Without date_time in the primary key, the ~51 weekly rows per grouping collapse to one on
# merge, silently discarding the whole time series. Without date_time as a cursor the table
# syncs full refresh, so every sync rebuilds it from Klaviyo's rolling window and drops the
# weeks that have since left it, which no later sync can fetch again.
@@ -1170,10 +1182,23 @@ class TestReportVariants:
assert "date_time" in config.primary_keys
assert [f["field"] for f in config.incremental_fields] == ["date_time"]
assert config.default_incremental_field == "date_time"
- # Klaviyo caps weekly-interval series reports at 52 weeks; last_365_days (365 days) exceeds
- # that by one day and causes a 400. All series endpoints must use the shorter key.
+ # Klaviyo caps a weekly series report at 52 weeks, which rules out last_365_days, and
+ # rejects any key outside its published set, which rules out inventing a 52-week one. Both
+ # rejections are 400s that fail the whole sync, so the window must go as a custom pair.
assert config.values_report is not None
- assert config.values_report.timeframe_key == SERIES_REPORT_TIMEFRAME_KEY
+ assert config.values_report.timeframe_key is None
+ assert config.values_report.timeframe_weeks == SERIES_REPORT_TIMEFRAME_WEEKS
+
+ def test_a_timeframe_key_klaviyo_does_not_publish_is_refused(self) -> None:
+ # An unpublished key reads like a real one but 400s every request the endpoint makes, so
+ # the config has to refuse it here rather than at sync time.
+ with pytest.raises(ValueError):
+ KlaviyoValuesReportConfig(
+ report_type="flow-series-report",
+ statistics=["opens"],
+ group_by=["flow_id"],
+ timeframe_key="last_52_weeks",
+ )
class TestEndpointRequestParams: