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): keep marketo export stream open to EOF (#104532)

jake sciotto3be81159610c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
index 5e6f367b8db5..ec572b193874 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/marketo.py
@@ -373,24 +373,27 @@ def _download_bulk_export(
int_columns: tuple[str, ...],
) -> Iterator[list[dict[str, Any]]]:
response = client.request("GET", f"/bulk/v1/{obj}/export/{export_id}/file.json", stream=True)
+ try:
+ if "application/json" in (response.headers.get("Content-Type") or ""):
+ # A failed download comes back as a Marketo error envelope instead of CSV.
+ raise_for_marketo_errors(response.json())
+ return
- if "application/json" in (response.headers.get("Content-Type") or ""):
- # A failed download comes back as a Marketo error envelope instead of CSV.
- raise_for_marketo_errors(response.json())
- return
-
- response.raw.decode_content = True
- # Wrap the raw stream rather than iterating lines: exported text columns can contain
- # newlines inside quoted fields, which line-splitting would tear apart.
- stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8", newline="")
- batch: list[dict[str, Any]] = []
- for row in csv.DictReader(stream):
- batch.append(_normalize_row(row, int_columns))
- if len(batch) >= BULK_CHUNK_ROWS:
+ response.raw.decode_content = True
+ response.raw.auto_close = False
+ # Wrap the raw stream rather than iterating lines: exported text columns can contain
+ # newlines inside quoted fields, which line-splitting would tear apart.
+ stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8", newline="")
+ batch: list[dict[str, Any]] = []
+ for row in csv.DictReader(stream):
+ batch.append(_normalize_row(row, int_columns))
+ if len(batch) >= BULK_CHUNK_ROWS:
+ yield batch
+ batch = []
+ if batch:
yield batch
- batch = []
- if batch:
- yield batch
+ finally:
+ response.close()
def _bulk_rows(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
index 1f025f5c6b9b..60b429fc6c11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketo/tests/test_marketo.py
@@ -7,6 +7,7 @@ from typing import Any, Optional, cast
import pytest
from unittest import mock
+import urllib3
import requests
from requests import Response
from requests.structures import CaseInsensitiveDict
@@ -622,6 +623,18 @@ class TestMarketo:
assert [len(batch) for batch in batches] == [BULK_CHUNK_ROWS, 5]
+ def test_download_empty_export_body_yields_no_rows(self) -> None:
+ # A real urllib3 stream (unlike the BytesIO fake) closes itself at EOF, so an empty export
+ # body must finish with no rows rather than raising "I/O operation on closed file".
+ response = Response()
+ response.status_code = 200
+ response.headers = CaseInsensitiveDict({"Content-Type": "text/csv;charset=UTF-8"})
+ response.raw = urllib3.response.HTTPResponse(body=io.BytesIO(b""), preload_content=False)
+ client = mock.MagicMock()
+ client.request.return_value = response
+
+ assert _drain(_download_bulk_export(client, "leads", "exp-1", ("id",))) == []
+
@pytest.mark.parametrize(
"row,int_columns,expected",
[