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(gladly): fail report syncs on a header missing the key columns (#82159)

jake sciotto7ec9554fe9c2
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.py
index e7432945a5a0..bbfc0178ff61 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
@@ -49,6 +49,23 @@ class GladlyRetryableError(Exception):
pass
+class GladlyReportHeaderError(Exception):
+ """A report body whose header is missing the columns the stream is keyed on.
+
+ A body that isn't the promised CSV still parses: its first line becomes the
+ header, so the rows come out carrying junk columns or nothing but the injected
+ `_row_id`, and the sync then fails much later with a misleading complaint about
+ the incremental field. Stop at the source instead. Keep the message matching
+ the entry in the source's non-retryable errors.
+ """
+
+ def __init__(self, metric_set: str, missing: list[str], present: list[str]) -> None:
+ super().__init__(
+ f"Gladly report is missing required columns {missing} for metricSet={metric_set}. "
+ f"Columns returned: {present!r:.300}"
+ )
+
+
class _ResponseByteStream(io.RawIOBase):
"""Read a streaming response body through ``iter_content`` as a binary file.
@@ -144,6 +161,23 @@ def _normalize_report_column(name: str) -> str:
return re.sub(r"[^a-z0-9]+", "_", name.strip().lower()).strip("_")
+def _report_csv_lines(stream: io.TextIOBase) -> Iterator[str]:
+ """Yield the report body with any blank lines before the header removed.
+
+ csv.DictReader takes the first line it reads as the header, so a leading blank
+ line becomes a single empty field name and every real column is then dropped
+ from the rows that follow. Lines keep their terminators, so csv still
+ reassembles values that contain a newline inside quotes.
+ """
+ header_seen = False
+ for line in stream:
+ if not header_seen:
+ if not line.strip():
+ continue
+ header_seen = True
+ yield line
+
+
def _report_row_id(row: dict[str, Any]) -> str:
"""Deterministic id for report rows that carry no natural key.
@@ -384,6 +418,11 @@ def _report_rows(
logger=logger,
)
inject_row_id = config.primary_key == REPORT_ROW_ID_COLUMN
+ # The columns the stream is keyed on. An injected `_row_id` is built from the row
+ # rather than read from the report, so it is never required of the header.
+ required_columns = {incremental_field["field"] for incremental_field in config.incremental_fields}
+ if not inject_row_id:
+ required_columns.add(config.primary_key)
is_first_request = True
while window_start <= today:
@@ -408,8 +447,20 @@ def _report_rows(
text_stream = io.TextIOWrapper(
io.BufferedReader(_ResponseByteStream(response, REPORT_CHUNK_BYTES)), encoding="utf-8-sig", newline=""
)
- reader = csv.DictReader(text_stream)
+ reader = csv.DictReader(_report_csv_lines(text_stream))
columns = {name: _normalize_report_column(name) for name in reader.fieldnames or []}
+ present = sorted({column for column in columns.values() if column})
+ missing = sorted(required_columns.difference(present))
+ # An empty body has no header at all and is a legitimately empty window, so only
+ # a header that parsed and came back wrong is a contract break. Log it before
+ # raising: the exception message is replaced by user guidance on the way to the
+ # customer, so this is the only place the real shape is recorded.
+ if reader.fieldnames and missing:
+ logger.error(
+ f"Gladly: {config.name} report window {window_start} - {window_end} returned a header "
+ f"missing {missing}. Header row: {reader.fieldnames!r:.500}"
+ )
+ raise GladlyReportHeaderError(metric_set, missing, present)
row_count = 0
chunk: list[dict[str, Any]] = []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py
index 1201249b958f..4458b043113b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/source.py
@@ -67,17 +67,23 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):
return {
"401 Client Error: Unauthorized for url": "Gladly authentication failed. Please check your agent email and API token.",
"403 Client Error: Forbidden for url": "Gladly denied access. Please check that the agent has the API User permission.",
+ # Raised by `_report_rows` when a report header is missing the columns the stream is
+ # keyed on. Gladly returns the same body for that window on a retry, so stop and tell
+ # the customer rather than replaying it.
+ "Gladly report is missing required columns": (
+ "Gladly returned a report without the columns this table syncs on, so there was no "
+ "data to sync. Re-enable the sync to try again, and contact support if it keeps happening."
+ ),
}
def get_retryable_errors(self) -> set[str]:
- # `_report_rows` reads the report CSV straight off `response.raw` (see gladly.py) rather
- # than through `iter_content`, so a stall in Gladly's report generation past
- # REQUEST_TIMEOUT_SECONDS raises the bare urllib3 read-timeout while streaming rows —
- # after `generate_report`'s own retry-on-`requests.ReadTimeout` has already returned a
- # response, so it isn't caught there either. Temporal's activity retry regenerates the
- # report and re-streams it; the resumable window state means only the in-flight window is
- # redone, deduped on merge, so this is self-recovering rather than a tracked-exception-worthy
- # failure.
+ # `_report_rows` streams the report CSV while it yields rows (see gladly.py), so a stall in
+ # Gladly's report generation past REQUEST_TIMEOUT_SECONDS raises the bare urllib3
+ # read-timeout mid-stream, after `generate_report`'s own retry-on-`requests.ReadTimeout` has
+ # already returned a response, so it isn't caught there either. Temporal's activity retry
+ # regenerates the report and re-streams it; the resumable window state means only the
+ # in-flight window is redone, deduped on merge, so this is self-recovering rather than a
+ # tracked-exception-worthy failure.
return {"Read timed out"}
@property
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.py
index 95d2448a28d1..b6c7fce95a46 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
@@ -12,6 +12,7 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (
CHUNK_SIZE,
+ GladlyReportHeaderError,
GladlyResumeConfig,
GladlyRetryableError,
_base_url,
@@ -635,7 +636,11 @@ class TestGetReportRows:
@freeze_time("2024-03-15T10:00:00Z")
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_large_report_windows_are_chunked(self, mock_session):
- csv_text = "Conversation ID\n" + "\n".join(f"conv-{i}" for i in range(CHUNK_SIZE + 1)) + "\n"
+ csv_text = (
+ "Timestamp,Conversation ID\n"
+ + "\n".join(f"2024-03-15T09:00:00.000Z,conv-{i}" for i in range(CHUNK_SIZE + 1))
+ + "\n"
+ )
mock_session.return_value.post.side_effect = [_csv_response(csv_text)]
manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
@@ -647,7 +652,11 @@ class TestGetReportRows:
@mock.patch(f"{_MODULE}.REPORT_ROW_WARNING_THRESHOLD", 2)
@mock.patch(f"{_MODULE}.make_tracked_session")
def test_windows_near_the_report_row_cap_log_a_truncation_warning(self, mock_session):
- mock_session.return_value.post.side_effect = [_csv_response("Conversation ID\nconv-1\nconv-2\n")]
+ mock_session.return_value.post.side_effect = [
+ _csv_response(
+ "Timestamp,Conversation ID\n2024-03-15T09:00:00.000Z,conv-1\n2024-03-15T10:00:00.000Z,conv-2\n"
+ )
+ ]
manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
logger = mock.MagicMock()
@@ -655,6 +664,48 @@ class TestGetReportRows:
logger.warning.assert_called_once()
+ @freeze_time("2024-03-15T10:00:00Z")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_blank_lines_before_the_header_do_not_erase_the_columns(self, mock_session):
+ mock_session.return_value.post.side_effect = [
+ _csv_response("\r\n\r\nTimestamp,Contact ID\r\n2024-03-15T09:00:00.000Z,ct-1\r\n")
+ ]
+
+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
+ batches = list(get_rows("myorg", "[email protected]", "token", "contact_timestamps", mock.MagicMock(), manager))
+
+ flat = [row for batch in batches for row in batch]
+ assert [(row["timestamp"], row["contact_id"]) for row in flat] == [("2024-03-15T09:00:00.000Z", "ct-1")]
+
+ @freeze_time("2024-03-15T10:00:00Z")
+ @pytest.mark.parametrize(
+ "endpoint,body",
+ [
+ ("contact_timestamps", '[\n{"timestamp":"2024-03-15T09:00:00.000Z"}\n]\n'),
+ ("contact_timestamps", "<html>\n<body>\nGladly is unavailable\n</body>\n</html>\n"),
+ ("contact_timestamps", "Event Type,Contact ID\nCONTACT/STARTED,ct-1\n"),
+ ("conversations", "Conversation ID,Status\nconv-1,OPEN\n"),
+ ],
+ ids=["json_body", "html_body", "cursor_column_renamed", "primary_key_column_renamed"],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_a_report_missing_the_columns_it_syncs_on_fails_at_the_source(self, mock_session, endpoint, body):
+ mock_session.return_value.post.side_effect = [_csv_response(body)]
+
+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
+ with pytest.raises(GladlyReportHeaderError, match="missing required columns"):
+ list(get_rows("myorg", "[email protected]", "token", endpoint, mock.MagicMock(), manager))
+
+ @freeze_time("2024-03-15T10:00:00Z")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_a_whitespace_only_body_is_treated_as_an_empty_window(self, mock_session):
+ mock_session.return_value.post.side_effect = [_csv_response("\r\n")]
+
+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
+ batches = list(get_rows("myorg", "[email protected]", "token", "contact_timestamps", mock.MagicMock(), manager))
+
+ assert batches == []
+
class TestGladlySourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))