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): retry a Gladly report served as an error body (#98061)

jake sciotto286ad025e8c1
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 bbfc0178ff61..7edad3f9f3eb 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,7 +5,7 @@ import json
import time
import hashlib
import dataclasses
-from collections.abc import Buffer, Iterator
+from collections.abc import Buffer, Iterator, Sequence
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
from urllib.parse import quote, urlencode
@@ -50,15 +50,6 @@ class GladlyRetryableError(Exception):
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}. "
@@ -66,6 +57,18 @@ class GladlyReportHeaderError(Exception):
)
+class GladlyReportUnavailableError(Exception):
+ def __init__(self, metric_set: str, header: list[str]) -> None:
+ super().__init__(
+ f"Gladly returned no report for metricSet={metric_set}: the response body is not a CSV report. "
+ f"First line: {header!r:.300}"
+ )
+
+
+def _header_is_an_error_line(fieldnames: Sequence[str]) -> bool:
+ return len(fieldnames) == 1
+
+
class _ResponseByteStream(io.RawIOBase):
"""Read a streaming response body through ``iter_content`` as a binary file.
@@ -424,23 +427,14 @@ def _report_rows(
if not inject_row_id:
required_columns.add(config.primary_key)
- is_first_request = True
- while window_start <= today:
- window_end = min(window_start + timedelta(days=config.report_window_days - 1), today)
- if not is_first_request:
- time.sleep(REPORT_REQUEST_INTERVAL_SECONDS)
- is_first_request = False
- response = generate_report(
- {
- "metricSet": metric_set,
- # Explicit UTC keeps window boundaries and rendered timestamps
- # stable even if the organization's default timezone changes.
- "timezone": "UTC",
- # endAt is inclusive: the report covers through the end of that day.
- "startAt": window_start.isoformat(),
- "endAt": window_end.isoformat(),
- }
- )
+ @retry(
+ retry=retry_if_exception_type(GladlyReportUnavailableError),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=2, max=90),
+ reraise=True,
+ )
+ def open_report(payload: dict[str, str], window_start: date, window_end: date) -> "csv.DictReader[str]":
+ response = generate_report(payload)
# Wrap the byte stream rather than iterating lines: CSV values can contain
# newlines inside quoted fields, which line-splitting would tear apart.
@@ -460,7 +454,31 @@ def _report_rows(
f"Gladly: {config.name} report window {window_start} - {window_end} returned a header "
f"missing {missing}. Header row: {reader.fieldnames!r:.500}"
)
+ if _header_is_an_error_line(reader.fieldnames):
+ raise GladlyReportUnavailableError(metric_set, list(reader.fieldnames))
raise GladlyReportHeaderError(metric_set, missing, present)
+ return reader
+
+ is_first_request = True
+ while window_start <= today:
+ window_end = min(window_start + timedelta(days=config.report_window_days - 1), today)
+ if not is_first_request:
+ time.sleep(REPORT_REQUEST_INTERVAL_SECONDS)
+ is_first_request = False
+ reader = open_report(
+ {
+ "metricSet": metric_set,
+ # Explicit UTC keeps window boundaries and rendered timestamps
+ # stable even if the organization's default timezone changes.
+ "timezone": "UTC",
+ # endAt is inclusive: the report covers through the end of that day.
+ "startAt": window_start.isoformat(),
+ "endAt": window_end.isoformat(),
+ },
+ window_start,
+ window_end,
+ )
+ columns = {name: _normalize_report_column(name) for name in reader.fieldnames or []}
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 9d2c9316bcb2..1d96480b4991 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,11 +67,10 @@ 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 body is missing the columns the stream is
- # keyed on: usually Gladly returned an error in place of the CSV, but a renamed keyed
- # column trips it too. The same window returns the same body on a retry, so neither the
- # sync nor the incremental-field picker can fix it. The copy names Gladly first and
- # PostHog support as the fallback for the renamed-column case, where the report exists.
+ # Raised by `_report_rows` when a CSV report lacks a keyed column. The same window returns
+ # the same header on a retry, so neither the sync nor the incremental-field picker can
+ # fix it. The copy names Gladly first and PostHog support as the fallback for the
+ # renamed-column case, where the report exists.
"Gladly report is missing required columns": (
"Gladly returned data that doesn't match the report this table needs, so there was "
"no data to sync. This usually means Gladly could not build the report for your "
@@ -88,7 +87,16 @@ class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):
# 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"}
+ return {"Read timed out", "Gladly returned no report"}
+
+ def get_retry_exhausted_errors(self) -> dict[str, str]:
+ return {
+ "Gladly returned no report": (
+ "Gladly returned an error instead of the report this table syncs from, so this run "
+ "did not finish. This is usually a short problem in Gladly's report generation. The "
+ "sync will run again on its next schedule."
+ ),
+ }
@property
def get_source_config(self) -> SourceConfig:
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 b6c7fce95a46..b06fc7f0c8c0 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
@@ -13,6 +13,7 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.gladly.gladly import (
CHUNK_SIZE,
GladlyReportHeaderError,
+ GladlyReportUnavailableError,
GladlyResumeConfig,
GladlyRetryableError,
_base_url,
@@ -681,12 +682,10 @@ class TestGetReportRows:
@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"],
+ ids=["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):
@@ -696,6 +695,46 @@ class TestGetReportRows:
with pytest.raises(GladlyReportHeaderError, match="missing required columns"):
list(get_rows("myorg", "[email protected]", "token", endpoint, mock.MagicMock(), manager))
+ assert mock_session.return_value.post.call_count == 1
+
+ @freeze_time("2024-03-15T10:00:00Z")
+ @pytest.mark.parametrize(
+ "body",
+ [
+ "Unexpected error occurred",
+ '[\n{"timestamp":"2024-03-15T09:00:00.000Z"}\n]\n',
+ "<html>\n<body>\nGladly is unavailable\n</body>\n</html>\n",
+ ],
+ ids=["plain_text_error", "json_body", "html_body"],
+ )
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_an_error_body_in_place_of_the_report_is_retried_and_stays_retryable(self, mock_session, _sleep, body):
+ mock_session.return_value.post.side_effect = [_csv_response(body) for _ in range(5)]
+
+ manager = _make_manager(GladlyResumeConfig(last_report_window_end="2024-03-15"))
+ with pytest.raises(GladlyReportUnavailableError, match="Gladly returned no report"):
+ list(get_rows("myorg", "[email protected]", "token", "contact_timestamps", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.post.call_count == 5
+ manager.save_state.assert_not_called()
+
+ @freeze_time("2024-03-15T10:00:00Z")
+ @mock.patch("time.sleep")
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_an_error_body_in_place_of_the_report_recovers_on_the_next_request(self, mock_session, _sleep):
+ mock_session.return_value.post.side_effect = [
+ _csv_response("Unexpected error occurred"),
+ _csv_response("Timestamp,Contact ID\n2024-03-15T09:00:00.000Z,ct-1\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")]
+ manager.save_state.assert_called_once()
+
@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):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py
index 8cea1fcc706a..29687ae63586 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gladly/tests/test_gladly_source.py
@@ -101,3 +101,11 @@ class TestGladlySource:
def test_get_schemas_filtered_unknown_name_returns_empty(self):
assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_a_missing_report_body_is_classified_retryable_with_exhaustion_copy(self):
+ retryable = self.source.get_retryable_errors()
+ exhausted = self.source.get_retry_exhausted_errors()
+
+ assert "Gladly returned no report" in retryable
+ assert set(exhausted) <= retryable
+ assert not any("Gladly returned no report" in key for key in self.source.get_non_retryable_errors())