Skip to content

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

fix(warehouse-sources): list quiet forms in the Klaviyo form values report (#98069)

jake sciotto7aae73cdd085
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 04b548b3b539..4c08b7b452f9 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
@@ -537,6 +537,25 @@ def _build_timeframe(report: KlaviyoValuesReportConfig, now: datetime) -> tuple[
return {"start": start.isoformat(), "end": end.isoformat()}, f"last_{report.timeframe_weeks}_weeks"
+def _no_activity_statistics(statistics: list[str]) -> dict[str, Any]:
+ return {statistic: None if statistic.endswith("_rate") else 0 for statistic in statistics}
+
+
+def _rows_for_ids_the_report_omitted(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ report: KlaviyoValuesReportConfig,
+ reported_ids: set[str],
+ common: dict[str, Any],
+) -> Iterator[dict[str, Any]]:
+ assert report.list_all_ids_path is not None
+ id_column = report.group_by[0]
+ for entity_id in _iter_resource_ids(session, headers, logger, report.list_all_ids_path, page_size=100):
+ if entity_id not in reported_ids:
+ yield {id_column: entity_id, **_no_activity_statistics(report.statistics), **common}
+
+
def _get_values_report_rows(
session: requests.Session,
headers: dict[str, str],
@@ -591,6 +610,9 @@ def _get_values_report_rows(
if metric_id:
common["conversion_metric_id"] = metric_id
+ lists_all_ids = report.list_all_ids_path is not None and not report.interval and len(report.group_by) == 1
+ reported_ids: set[str] = set()
+
try:
while True:
data = _fetch_page(session, url, post_headers, logger, json_body=body)
@@ -603,6 +625,8 @@ def _get_values_report_rows(
rows = ({**r.get("groupings", {}), **r.get("statistics", {}), **common} for r in results)
for row in rows:
+ if lists_all_ids and row.get(report.group_by[0]) is not None:
+ reported_ids.add(str(row[report.group_by[0]]))
batcher.batch(row)
if batcher.should_yield():
yield batcher.get_table()
@@ -611,6 +635,12 @@ def _get_values_report_rows(
if not next_url:
break
url = next_url
+
+ if lists_all_ids:
+ for row in _rows_for_ids_the_report_omitted(session, headers, logger, report, reported_ids, common):
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
except requests.HTTPError as exc:
if (
exc.response is not None
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 41bb85a6d6cd..834dab6b6569 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
@@ -73,6 +73,7 @@ class KlaviyoValuesReportConfig:
# Campaign and flow reports require a conversion metric on every request; form and segment
# reports do not accept one, so their requests must omit it and skip the /metrics lookup.
requires_conversion_metric: bool = True
+ list_all_ids_path: Optional[str] = None
def __post_init__(self) -> None:
# Klaviyo requires a timeframe and accepts only one form of it, so a config that sets both
@@ -592,10 +593,12 @@ KLAVIYO_ENDPOINTS: dict[str, KlaviyoEndpointConfig] = {
timeframe_key=VALUES_REPORT_TIMEFRAME_KEY,
group_by=["form_id"],
requires_conversion_metric=False,
+ list_all_ids_path="/forms",
),
description=(
"Klaviyo's own signup-form performance statistics per form over the last 365 days, "
- "replaced in full on every sync"
+ "replaced in full on every sync. A form with no activity in the window is listed with "
+ "zero counts and no submit rate."
),
),
"segment_values_reports": KlaviyoEndpointConfig(
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 9a5e2f725219..4ef47e98164a 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,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.kl
klaviyo_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.klaviyo.settings import (
+ FORM_REPORT_STATISTICS,
KLAVIYO_ENDPOINTS,
SERIES_REPORT_TIMEFRAME_WEEKS,
+ VALUES_REPORT_TIMEFRAME_KEY,
KlaviyoEndpointConfig,
KlaviyoValuesReportConfig,
)
@@ -1197,7 +1199,8 @@ class TestReportVariants:
fetched_urls.append(url)
if json_body is not None:
captured["body"] = json_body
- return {"data": {"attributes": {"results": []}}, "links": {}}
+ return {"data": {"attributes": {"results": []}}, "links": {}}
+ return {"data": [], "links": {}}
with patch.object(klaviyo, "_fetch_page", fake_fetch):
list(
@@ -1212,12 +1215,81 @@ class TestReportVariants:
attributes = captured["body"]["data"]["attributes"]
assert captured["body"]["data"]["type"] == report_type
assert "conversion_metric_id" not in attributes
- assert fetched_urls == [f"https://a.klaviyo.com/api{path}"]
+ assert fetched_urls[0] == f"https://a.klaviyo.com/api{path}"
+ assert all("/metrics" not in url for url in fetched_urls)
if expected_group_by is None:
assert "group_by" not in attributes
else:
assert attributes["group_by"] == expected_group_by
+ def test_form_values_report_lists_every_form_and_zero_fills_the_quiet_ones(self) -> None:
+ fetched_urls: list[str] = []
+
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ fetched_urls.append(url)
+ if json_body is not None:
+ return {
+ "data": {
+ "attributes": {
+ "results": [
+ {
+ "groupings": {"form_id": "FORM_ACTIVE"},
+ "statistics": {"viewed_form": 40, "submits": 4, "submit_rate": 0.1},
+ }
+ ]
+ }
+ },
+ "links": {},
+ }
+ assert url.startswith("https://a.klaviyo.com/api/forms?")
+ return {"data": [{"id": "FORM_ACTIVE"}, {"id": "FORM_QUIET"}], "links": {}}
+
+ with patch.object(klaviyo, "_fetch_page", fake_fetch):
+ rows = [
+ row
+ for table in get_rows(
+ api_key="pk_test",
+ endpoint="form_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ for row in table.to_pylist()
+ ]
+
+ by_form = {row["form_id"]: row for row in rows}
+ assert set(by_form) == {"FORM_ACTIVE", "FORM_QUIET"}
+ assert (by_form["FORM_ACTIVE"]["viewed_form"], by_form["FORM_ACTIVE"]["submits"]) == (40, 4)
+ assert by_form["FORM_ACTIVE"]["submit_rate"] == 0.1
+ quiet = by_form["FORM_QUIET"]
+ assert quiet["timeframe_key"] == VALUES_REPORT_TIMEFRAME_KEY
+ assert quiet["submit_rate"] is None
+ assert all(quiet[statistic] == 0 for statistic in FORM_REPORT_STATISTICS if statistic != "submit_rate")
+ assert len(fetched_urls) == 2
+
+ def test_a_report_without_a_list_all_ids_path_stays_empty(self) -> None:
+ fetched_urls: list[str] = []
+
+ def fake_fetch(
+ session: Any, url: str, headers: dict[str, str], logger: Any, json_body: dict | None = None
+ ) -> dict:
+ fetched_urls.append(url)
+ return {"data": {"attributes": {"results": []}}, "links": {}}
+
+ with patch.object(klaviyo, "_fetch_page", fake_fetch):
+ tables = list(
+ get_rows(
+ api_key="pk_test",
+ endpoint="segment_values_reports",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+
+ assert tables == []
+ assert fetched_urls == ["https://a.klaviyo.com/api/segment-values-reports"]
+
@parameterized.expand(
[
("flow_series_reports",),