: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(gladly): handle empty report windows without crashing the sync (#80717)
Tom Owers03693bbcf215
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.pyindex e715a376971e..e7432945a5a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/gladly.py@@ -5,9 +5,9 @@ import jsonimport timeimport hashlibimport dataclasses-from collections.abc import Iterator+from collections.abc import Buffer, Iteratorfrom datetime import UTC, date, datetime, timedelta-from typing import IO, Any, Optional, cast+from typing import Any, Optionalfrom urllib.parse import quote, urlencodeimport requests@@ -28,6 +28,8 @@ REQUEST_TIMEOUT_SECONDS = 300MAX_RETRY_ATTEMPTS = 5# Yield JSONL rows in chunks so big files don't build one giant list.CHUNK_SIZE = 5000+# Pull the report CSV off the wire in 64 KiB reads.+REPORT_CHUNK_BYTES = 1 << 16# Gladly caps report CSVs (100k rows for most reports) and truncates silently,# so a window this full is likely missing rows.REPORT_ROW_WARNING_THRESHOLD = 90_000@@ -47,6 +49,36 @@ class GladlyRetryableError(Exception):pass+class _ResponseByteStream(io.RawIOBase):+ """Read a streaming response body through ``iter_content`` as a binary file.++ Wrapping ``response.raw`` directly crashes on an empty report body: urllib3+ closes the connection the moment it reads EOF, and a ``TextIOWrapper`` over+ the now-closed raw stream raises ``ValueError: I/O operation on closed file``.+ ``iter_content`` yields nothing for an empty body and turns a dropped+ connection into a retryable ``requests`` error mid-stream.+ """++ def __init__(self, response: requests.Response, chunk_size: int) -> None:+ self._chunks = response.iter_content(chunk_size=chunk_size)+ self._buffer = b""++ def readable(self) -> bool:+ return True++ def readinto(self, target: Buffer) -> int:+ while not self._buffer:+ try:+ self._buffer = next(self._chunks)+ except StopIteration:+ return 0+ view = memoryview(target).cast("B")+ take = min(len(view), len(self._buffer))+ view[:take] = self._buffer[:take]+ self._buffer = self._buffer[take:]+ return take++@dataclasses.dataclassclass GladlyResumeConfig:# Jobs are processed oldest-first; persisting the last fully-processed@@ -371,10 +403,11 @@ def _report_rows(})- response.raw.decode_content = True- # Wrap the raw stream rather than iterating lines: CSV values can contain+ # Wrap the byte stream rather than iterating lines: CSV values can contain# newlines inside quoted fields, which line-splitting would tear apart.- text_stream = io.TextIOWrapper(cast(IO[bytes], response.raw), encoding="utf-8-sig", newline="")+ text_stream = io.TextIOWrapper(+ io.BufferedReader(_ResponseByteStream(response, REPORT_CHUNK_BYTES)), encoding="utf-8-sig", newline=""+ )reader = csv.DictReader(text_stream)columns = {name: _normalize_report_column(name) for name in reader.fieldnames or []}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.pyindex 7670b0383943..95d2448a28d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly.py@@ -7,6 +7,7 @@ import pytestfrom freezegun import freeze_timefrom unittest import mock+import urllib3import requestsfrom products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (@@ -54,16 +55,14 @@ def _job(job_id: str, updated_at: str, files: list[str] | None = None) -> dict[sreturn {"id": job_id, "updatedAt": updated_at, "files": files or ["customers.jsonl", "agents.jsonl"]}-class _RawBytes(io.BytesIO):- """BytesIO subclass, so the transport can set decode_content on it."""---def _csv_response(text: str) -> mock.MagicMock:- resp = mock.MagicMock()- resp.raw = _RawBytes(text.encode())- resp.status_code = 200- resp.ok = True- return resp+def _csv_response(text: str) -> requests.Response:+ # A real urllib3-backed response so iter_content streams the body and an empty+ # body closes the connection on EOF exactly as it does in production.+ raw = urllib3.HTTPResponse(body=io.BytesIO(text.encode()), preload_content=False)+ response = requests.Response()+ response.raw = raw+ response.status_code = 200+ return responsedef _error_response(status_code: int) -> mock.MagicMock:@@ -582,6 +581,19 @@ class TestGetReportRows:"2024-03-15",]+ @freeze_time("2024-03-15T10:00:00Z")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_report_body_yields_no_rows_and_advances(self, mock_session):+ # A window with no data returns an empty body; urllib3 closes the stream on+ # EOF, which used to surface as "ValueError: I/O operation on closed file".+ mock_session.return_value.post.side_effect = [_csv_response("")]++ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))+ batches = list(get_rows("myorg", "[email protected]", "token", "conversation_timestamps", mock.MagicMock(), manager))++ assert batches == []+ assert manager.save_state.call_args.args[0].last_report_window_end == "2024-03-15"+@freeze_time("2024-03-15T10:00:00Z")@mock.patch(f"{_MODULE}.make_tracked_session")def test_row_ids_are_deterministic_across_syncs(self, mock_session):