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(data-warehouse): stream bing ads reports instead of holding them in memory (#105434)

Tom Owers12bc554d2718
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py
index d1af5c1889a2..235c944e8e62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/client.py
@@ -15,13 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.int
)
from .schemas import REPORT_CONFIG, RESOURCE_SCHEMAS, BingAdsResource
-from .utils import (
- ENVIRONMENT,
- REPORT_POLL_INTERVAL_MS,
- build_report_request,
- download_and_extract_report_csv,
- parse_csv_to_dicts,
-)
+from .utils import ENVIRONMENT, REPORT_POLL_INTERVAL_MS, build_report_request, iter_report_row_pages
logger = structlog.get_logger(__name__)
@@ -226,7 +220,7 @@ class BingAdsClient:
customer_id: int,
start_date: datetime,
end_date: datetime,
- ) -> list[dict[str, Any]]:
+ ) -> Generator[list[dict[str, Any]]]:
report_config = REPORT_CONFIG[resource]
schema = RESOURCE_SCHEMAS[resource]
@@ -256,7 +250,9 @@ class BingAdsClient:
end_date=end_date,
)
- csv_data = download_and_extract_report_csv(
+ # Yielded from inside the working directory so the SDK keeps it for the whole read,
+ # and from inside the try so a fault raised mid-download still reports its detail.
+ yield from iter_report_row_pages(
reporting_service_manager=reporting_service_manager,
report_request=report_request,
report_type=report_config["report_type"],
@@ -265,8 +261,6 @@ class BingAdsClient:
except Exception as e:
raise _wrap_with_fault_detail(e, f"Failed to generate {resource.value} report") from e
- return parse_csv_to_dicts(csv_data)
-
def get_data_by_resource(
self,
resource: BingAdsResource,
@@ -281,6 +275,6 @@ class BingAdsClient:
elif resource in REPORT_CONFIG:
if not start_date or not end_date:
raise ValueError("start_date and end_date required for performance reports")
- yield self.get_performance_report(resource, account_id, customer_id, start_date, end_date)
+ yield from self.get_performance_report(resource, account_id, customer_id, start_date, end_date)
else:
raise ValueError(f"Unsupported resource: {resource}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
index 68fe5e186986..13bfd98454e7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads.py
@@ -1,5 +1,7 @@
+import io
+import zipfile
import datetime as dt
-from collections.abc import Iterable
+from collections.abc import Iterable, Iterator
import pytest
from unittest.mock import MagicMock, Mock, patch
@@ -19,9 +21,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.s
from products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.utils import (
REPORT_GENERATION_ATTEMPTS,
BingAdsResumeConfig,
- download_and_extract_report_csv,
fetch_data_in_yearly_chunks,
- parse_csv_to_dicts,
+ iter_csv_row_pages,
+ iter_report_row_pages,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.types import IncrementalFieldType
@@ -39,30 +41,58 @@ def _mock_resumable_manager(
class TestBingAdsHelperFunctions:
"""Test helper functions in bing_ads.py and utils.py."""
- def test_parse_csv_to_dicts_valid_data(self):
+ def test_iter_csv_row_pages_valid_data(self):
csv_data = """TimePeriod,CampaignId,CampaignName,Impressions,Clicks
2024-01-01,123,Test Campaign,1000,50
2024-01-02,123,Test Campaign,1200,60"""
- result = parse_csv_to_dicts(csv_data)
+ pages = list(iter_csv_row_pages(io.StringIO(csv_data, newline="")))
- assert len(result) == 2
- assert result[0]["TimePeriod"] == "2024-01-01"
- assert result[0]["CampaignId"] == "123"
- assert result[0]["Impressions"] == "1000"
- assert result[1]["TimePeriod"] == "2024-01-02"
+ assert len(pages) == 1
+ rows = pages[0]
+ assert len(rows) == 2
+ assert rows[0]["TimePeriod"] == "2024-01-01"
+ assert rows[0]["CampaignId"] == "123"
+ assert rows[0]["Impressions"] == "1000"
+ assert rows[1]["TimePeriod"] == "2024-01-02"
- def test_parse_csv_to_dicts_with_null_values(self):
+ def test_iter_csv_row_pages_with_null_values(self):
csv_data = """TimePeriod,CampaignId,CampaignName,Impressions,Clicks
2024-01-01,123,Test Campaign,--,
2024-01-02,456,--,1000,50"""
- result = parse_csv_to_dicts(csv_data)
+ rows = [row for page in iter_csv_row_pages(io.StringIO(csv_data, newline="")) for row in page]
- assert len(result) == 2
- assert result[0]["Impressions"] is None
- assert result[0]["Clicks"] is None
- assert result[1]["CampaignName"] is None
+ assert len(rows) == 2
+ assert rows[0]["Impressions"] is None
+ assert rows[0]["Clicks"] is None
+ assert rows[1]["CampaignName"] is None
+
+ @parameterized.expand([(1, [1, 1, 1, 1, 1]), (2, [2, 2, 1]), (5, [5]), (50, [5])])
+ def test_iter_csv_row_pages_splits_into_bounded_pages(self, page_rows: int, expected_sizes: list[int]):
+ header = "TimePeriod,CampaignId\n"
+ body = "".join(f"2024-01-0{day},{day}\n" for day in range(1, 6))
+
+ pages = list(iter_csv_row_pages(io.StringIO(header + body, newline=""), page_rows=page_rows))
+
+ assert [len(page) for page in pages] == expected_sizes
+ assert [row["CampaignId"] for page in pages for row in page] == ["1", "2", "3", "4", "5"]
+
+ def test_iter_csv_row_pages_reads_lazily(self):
+ # Draining the source before the first page would hold the whole report, whatever the page size.
+ header = "TimePeriod,CampaignId\n"
+ lines_read = 0
+
+ def counting_lines() -> Iterator[str]:
+ nonlocal lines_read
+ for line in [header, *(f"2024-01-0{day},{day}\n" for day in range(1, 6))]:
+ lines_read += 1
+ yield line
+
+ pages = iter_csv_row_pages(counting_lines(), page_rows=2)
+ next(pages)
+
+ assert lines_read < 6
def test_fetch_data_in_yearly_chunks_single_chunk(self):
mock_client = Mock()
@@ -218,23 +248,48 @@ class TestBingAdsHelperFunctions:
# The skipped chunk still advances the checkpoint, so all three chunks are accounted for
assert manager.save_state.call_count == 3
- def test_download_and_extract_report_csv_no_file_returns_empty(self):
+ def test_iter_report_row_pages_streams_the_zipped_csv(self, tmp_path):
+ # The BOM Bing prefixes the report with must not survive into the first column name.
+ report_zip = tmp_path / "report.zip"
+ with zipfile.ZipFile(report_zip, "w") as archive:
+ rows = "".join(f"2024-01-0{day},{day}\n" for day in range(1, 5))
+ archive.writestr("report.csv", ("\ufeffTimePeriod,CampaignId\n" + rows).encode("utf-8"))
+
+ manager = Mock()
+ manager.download_file.return_value = str(report_zip)
+
+ pages = list(
+ iter_report_row_pages(
+ reporting_service_manager=manager,
+ report_request=Mock(),
+ report_type="CampaignPerformanceReportRequest",
+ account_id=12345,
+ page_rows=3,
+ )
+ )
+
+ assert [len(page) for page in pages] == [3, 1]
+ assert pages[0][0] == {"TimePeriod": "2024-01-01", "CampaignId": "1"}
+
+ def test_iter_report_row_pages_no_file_yields_nothing(self):
# Bing returns no file (download_file -> None) when a report has zero rows for the range;
# treat it as an empty report instead of crashing on Path(None).
manager = Mock()
manager.download_file.return_value = None
- result = download_and_extract_report_csv(
- reporting_service_manager=manager,
- report_request=Mock(),
- report_type="CampaignPerformanceReportRequest",
- account_id=12345,
+ result = list(
+ iter_report_row_pages(
+ reporting_service_manager=manager,
+ report_request=Mock(),
+ report_type="CampaignPerformanceReportRequest",
+ account_id=12345,
+ )
)
- assert result == ""
+ assert result == []
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.utils.time.sleep")
- def test_download_and_extract_report_csv_resubmits_failed_report_generation(self, _mock_sleep):
+ def test_iter_report_row_pages_resubmits_failed_report_generation(self, _mock_sleep):
# Bing sometimes finishes building a report in a failed state and the SDK raises a detail-free
# ReportingException. Resubmitting recovers it, instead of failing the run over a Bing-side flake.
manager = Mock()
@@ -243,29 +298,33 @@ class TestBingAdsHelperFunctions:
None,
]
- result = download_and_extract_report_csv(
- reporting_service_manager=manager,
- report_request=Mock(),
- report_type="KeywordPerformanceReportRequest",
- account_id=12345,
+ result = list(
+ iter_report_row_pages(
+ reporting_service_manager=manager,
+ report_request=Mock(),
+ report_type="KeywordPerformanceReportRequest",
+ account_id=12345,
+ )
)
- assert result == ""
+ assert result == []
assert manager.download_file.call_count == 2
@patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.utils.time.sleep")
- def test_download_and_extract_report_csv_gives_up_after_repeated_generation_failures(self, _mock_sleep):
+ def test_iter_report_row_pages_gives_up_after_repeated_generation_failures(self, _mock_sleep):
# A report that keeps failing to build propagates, so the sync fails and the pipeline can
# retry it, instead of recording an empty report.
manager = Mock()
manager.download_file.side_effect = ReportingException("Exceptions while reporting download.", "Error")
with pytest.raises(ReportingException):
- download_and_extract_report_csv(
- reporting_service_manager=manager,
- report_request=Mock(),
- report_type="KeywordPerformanceReportRequest",
- account_id=12345,
+ list(
+ iter_report_row_pages(
+ reporting_service_manager=manager,
+ report_request=Mock(),
+ report_type="KeywordPerformanceReportRequest",
+ account_id=12345,
+ )
)
assert manager.download_file.call_count == REPORT_GENERATION_ATTEMPTS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py
index 0fe5980e6fe6..1e05b397cb9a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/tests/test_bing_ads_client.py
@@ -247,12 +247,12 @@ class TestBingAdsClient:
assert not any(pattern in message for pattern in non_retryable_patterns)
@mock.patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.download_and_extract_report_csv"
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.iter_report_row_pages"
)
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.build_report_request")
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bing_ads.client.reporting")
def test_get_performance_report_gives_sdk_private_existing_working_directory(
- self, mock_reporting, _mock_build_request, mock_download
+ self, mock_reporting, _mock_build_request, mock_iter_pages
):
"""The bingads SDK defaults every ReportingServiceManager to a shared /tmp/BingAdsSDKPython that it
creates with a non-atomic check-then-makedirs; concurrent report fetches race and one dies with
@@ -272,15 +272,18 @@ class TestBingAdsClient:
return mock.MagicMock()
mock_reporting.ReportingServiceManager.side_effect = fake_manager
- mock_download.return_value = ""
+ mock_iter_pages.return_value = iter([])
client = BingAdsClient(self.access_token, self.refresh_token, self.developer_token)
- client.get_performance_report(
- resource=BingAdsResource.AD_PERFORMANCE_REPORT,
- account_id=self.account_id,
- customer_id=self.customer_id,
- start_date=dt.datetime(2024, 1, 1),
- end_date=dt.datetime(2024, 12, 31),
+ # The report is a generator now, so the manager is only built once it is drained.
+ list(
+ client.get_performance_report(
+ resource=BingAdsResource.AD_PERFORMANCE_REPORT,
+ account_id=self.account_id,
+ customer_id=self.customer_id,
+ start_date=dt.datetime(2024, 1, 1),
+ end_date=dt.datetime(2024, 12, 31),
+ )
)
# A private, already-existing directory means the SDK's racy makedirs never runs.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/utils.py
index 28cbb0dabf80..7e3ed4fd0e68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_ads/utils.py
@@ -1,3 +1,4 @@
+import io
import csv
import time
import uuid
@@ -5,7 +6,7 @@ import zipfile
import datetime as dt
import tempfile
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Iterable, Iterator
from pathlib import Path
from typing import Any
@@ -45,21 +46,25 @@ REPORT_TIMEOUT_MS = 1_800_000
# report queue fails the whole run, and the pipeline's own retry refetches the chunk from scratch.
REPORT_GENERATION_ATTEMPTS = 3
REPORT_GENERATION_RETRY_DELAY_SECONDS = 30
+# The batcher only caps what it accumulates between items, so one oversized item passes straight
+# through and sets the activity's peak memory on its own. Paging the report keeps that peak bounded.
+REPORT_PAGE_ROWS = 50_000
-def parse_csv_to_dicts(csv_data: str) -> list[dict[str, Any]]:
- """Parse Bing Ads CSV report data into list of dictionaries."""
- if not csv_data or not csv_data.strip():
- return []
+def iter_csv_row_pages(csv_lines: Iterable[str], page_rows: int = REPORT_PAGE_ROWS) -> Iterator[list[dict[str, Any]]]:
+ """Parse Bing Ads report CSV into pages of at most `page_rows` dictionaries.
- # Remove BOM if present
- if csv_data.startswith("\ufeff"):
- csv_data = csv_data[1:]
-
- reader = csv.DictReader(csv_data.strip().split("\n"))
+ Bing writes an absent metric as "--", which the rest of the pipeline expects as None.
+ """
+ page: list[dict[str, Any]] = []
+ for row in csv.DictReader(csv_lines):
+ page.append({key: None if value in ("--", "") else value for key, value in row.items()})
+ if len(page) >= page_rows:
+ yield page
+ page = []
- # Convert "--" and empty strings to None
- return [{key: None if value in ("--", "") else value for key, value in row.items()} for row in reader]
+ if page:
+ yield page
def fetch_data_in_yearly_chunks(
@@ -204,16 +209,18 @@ def download_report_file(
return reporting_service_manager.download_file(download_params)
-def download_and_extract_report_csv(
+def iter_report_row_pages(
reporting_service_manager: Any,
report_request: Any,
report_type: str,
account_id: int,
-) -> str:
- """Download report ZIP file and extract CSV content.
+ page_rows: int = REPORT_PAGE_ROWS,
+) -> Iterator[list[dict[str, Any]]]:
+ """Download the report ZIP and yield its CSV rows in bounded pages.
- Bing Ads Reporting API returns reports as ZIP files containing a single CSV.
- This function handles the download, extraction, and cleanup.
+ The CSV inside the ZIP is as large as the account's history, so every step stays streaming and
+ peak memory follows `page_rows` rather than the report. The temporary directory lives for as
+ long as the caller iterates, so a caller that abandons the iterator early must close it.
"""
with tempfile.TemporaryDirectory() as tmpdir:
filename = f"{report_type}_{account_id}_{uuid.uuid4()}.zip"
@@ -232,13 +239,16 @@ def download_and_extract_report_csv(
# (e.g. a date window with no campaign activity). Treat that as an empty report instead of
# crashing on Path(None).
if result_file_path is None:
- return ""
+ return
result_path = Path(result_file_path)
with zipfile.ZipFile(result_path, "r") as zip_file:
csv_files = [name for name in zip_file.namelist() if name.endswith(".csv")]
if not csv_files:
raise ValueError("No CSV file found in report ZIP")
- csv_data = zip_file.read(csv_files[0]).decode("utf-8")
- return csv_data
+ with zip_file.open(csv_files[0]) as raw_csv:
+ # `utf-8-sig` drops the BOM Bing prefixes the report with, and `newline=""` leaves
+ # newlines inside quoted fields for the csv module to handle.
+ csv_lines = io.TextIOWrapper(raw_csv, encoding="utf-8-sig", newline="")
+ yield from iter_csv_row_pages(csv_lines, page_rows=page_rows)