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): bound DoIt requests and stamp report ids (#81058)

estefania3a16529d7c3b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/doit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/doit.py
index 05e0ae694076..322bce316b32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/doit.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/doit.py
@@ -1,5 +1,6 @@
import hashlib
import datetime
+from dataclasses import dataclass
from typing import Any, Optional
import pyarrow as pa
@@ -23,6 +24,20 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# origin family to the forcelist and let the HTTP layer retry them with backoff.
DOIT_RETRY = DEFAULT_RETRY.new(status_forcelist=(*(DEFAULT_RETRY.status_forcelist or ()), 520, 521, 522, 523, 524))
+# `make_tracked_session` leaves `timeout` unset, so an unbounded request holds a worker thread until
+# the enclosing Temporal activity's start-to-close budget (24h full refresh, a week incremental)
+# expires, with the schema stuck in "Running" the whole time — the liveness heartbeat beats from the
+# activity's event loop, not the thread doing the request, so it can't catch this. Split connect from
+# read: the report fetch needs a long read budget for wide date windows, but neither call should sit
+# on a black-holed connect. Read timeouts are socket-inactivity, not total elapsed, so a slow but
+# streaming report is never cut off.
+DOIT_CONNECT_TIMEOUT_SECONDS = 10
+LIST_REPORTS_TIMEOUT_SECONDS = (DOIT_CONNECT_TIMEOUT_SECONDS, 30)
+REPORT_TIMEOUT_SECONDS = (DOIT_CONNECT_TIMEOUT_SECONDS, 300)
+
+# Key under a schema's persisted `schema_metadata` holding the DoIt report id.
+REPORT_ID_METADATA_KEY = "report_id"
+
DOIT_INCREMENTAL_FIELDS: list[IncrementalField] = [
{
"field": "timestamp",
@@ -59,15 +74,30 @@ def build_pyarrow_schema(schema: dict[str, str]) -> pa.Schema:
return pa.schema(fields)
-def doit_list_reports(config: DoItSourceConfig, logger: Optional[FilteringBoundLogger] = None) -> list[tuple[str, str]]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class DoItReport:
+ id: str
+ # Normalized identifier used as the schema row name.
+ name: str
+ # Raw DoIt name, shown as the schema label so a rename stays visible in the UI.
+ report_name: str
+
+
+def doit_list_reports(config: DoItSourceConfig, logger: Optional[FilteringBoundLogger] = None) -> list[DoItReport]:
if logger is None:
logger = structlog.get_logger(__name__)
res = make_tracked_session(retry=DOIT_RETRY).get(
"https://api.doit.com/analytics/v1/reports",
headers={"Authorization": f"Bearer {config.api_key}"},
+ timeout=LIST_REPORTS_TIMEOUT_SECONDS,
)
+ # `DOIT_RETRY` sets `raise_on_status=False`, so a 5xx that outlives the retries lands here as a
+ # normal response; without this guard it surfaces as a JSON/key error with the status code lost.
+ if res.status_code != 200:
+ raise Exception(f"Request to list reports failed with status: {res.status_code}. With body: {res.text}")
+
reports = res.json()["reports"]
result = []
@@ -79,7 +109,7 @@ def doit_list_reports(config: DoItSourceConfig, logger: Optional[FilteringBoundL
continue
try:
normalized = NamingConvention.normalize_identifier(report_name)
- result.append((normalized, report["id"]))
+ result.append(DoItReport(id=report["id"], name=normalized, report_name=report_name))
except ValueError:
logger.warning("Skipping DoIt report with invalid name", report_id=report_id, report_name=report_name)
continue
@@ -87,6 +117,24 @@ def doit_list_reports(config: DoItSourceConfig, logger: Optional[FilteringBoundL
return result
+def resolve_report_id(
+ config: DoItSourceConfig,
+ schema_name: str,
+ schema_metadata: Optional[dict[str, Any]],
+ logger: Optional[FilteringBoundLogger] = None,
+) -> str:
+ # The report id is stamped into schema_metadata at schema creation, so a later rename of the
+ # report in DoIt keeps syncing into the same warehouse table. The re-listing below is only a
+ # safety net for schemas persisted without metadata.
+ if schema_metadata and schema_metadata.get(REPORT_ID_METADATA_KEY):
+ return str(schema_metadata[REPORT_ID_METADATA_KEY])
+
+ matches = [report.id for report in doit_list_reports(config, logger=logger) if report.name == schema_name]
+ if not matches:
+ raise Exception("Report no longer exists")
+ return matches[0]
+
+
def append_primary_key(row: dict[str, Any]) -> dict[str, Any]:
columns_to_ignore = ["timestamp", "cost"]
key = ""
@@ -102,10 +150,10 @@ def append_primary_key(row: dict[str, Any]) -> dict[str, Any]:
# NOTE: This source intentionally remains a SimpleSource and is not a candidate for ResumableSource.
-# `doit_source` does a small fixed request flow: it first lists reports to resolve the selected
-# report ID, then fetches that report for the requested date window. The report-fetch step returns
-# the full requested window in a single response — there is no pagination loop, next-URL,
-# continuation token, parent/child fanout, or other multi-batch checkpoint to persist mid-sync.
+# `doit_source` does a small fixed request flow: a single fetch of the resolved report for the
+# requested date window, which returns that whole window in one response — there is no pagination
+# loop, next-URL, continuation token, parent/child fanout, or other multi-batch checkpoint to
+# persist mid-sync.
# For incremental runs, `db_incremental_field_last_value` already determines `startDate` when
# `should_use_incremental_field` is enabled. For full-refresh runs, there is no resumable progress
# marker today; a retry simply restarts the same full request. If DoIt exposes a paginated reports
@@ -114,17 +162,11 @@ def append_primary_key(row: dict[str, Any]) -> dict[str, Any]:
def doit_source(
config: DoItSourceConfig,
report_name: str,
+ report_id: str,
logger: FilteringBoundLogger,
db_incremental_field_last_value: Optional[Any],
should_use_incremental_field: bool = False,
) -> SourceResponse:
- all_reports = doit_list_reports(config, logger=logger)
- selected_reports = [id for name, id in all_reports if name == report_name]
- if len(selected_reports) == 0:
- raise Exception("Report no longer exists")
-
- report_id = selected_reports[0]
-
def get_rows(report_id: str):
request_uri = f"https://api.doit.com/analytics/v1/reports/{report_id}"
@@ -150,6 +192,7 @@ def doit_source(
res = make_tracked_session(retry=DOIT_RETRY).get(
request_uri,
headers={"Authorization": f"Bearer {config.api_key}"},
+ timeout=REPORT_TIMEOUT_SECONDS,
)
if res.status_code != 200:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/source.py
index 09b4196c36db..c2770f92e7fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/source.py
@@ -14,8 +14,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.doit.doit import (
DOIT_INCREMENTAL_FIELDS,
+ REPORT_ID_METADATA_KEY,
doit_list_reports,
doit_source,
+ resolve_report_id,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.doit import DoItSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -44,12 +46,14 @@ class DoItSource(SimpleSource[DoItSourceConfig]):
schemas = [
SourceSchema(
- name=name,
+ name=report.name,
+ label=report.report_name,
supports_incremental=True,
supports_append=True,
incremental_fields=DOIT_INCREMENTAL_FIELDS,
+ schema_metadata={REPORT_ID_METADATA_KEY: report.id},
)
- for name, _id in reports
+ for report in reports
]
if names is not None:
@@ -59,14 +63,20 @@ class DoItSource(SimpleSource[DoItSourceConfig]):
return schemas
def get_non_retryable_errors(self) -> dict[str, str | None]:
+ report_gone = "The DoIt report no longer exists. It may have been deleted or renamed in DoIt. Reconnect the source or select a different report."
return {
- "Report no longer exists": "The DoIt report no longer exists. It may have been deleted or renamed in DoIt. Please reconnect the source or select a different report.",
+ # Still reachable: rows persisted without a report id fall back to the name lookup.
+ "Report no longer exists": report_gone,
+ # A row that resolves by id hits the fetch directly, so a deleted report surfaces there.
+ "Request to get report failed with status: 404": report_gone,
}
def source_for_pipeline(self, config: DoItSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ report_id = resolve_report_id(config, inputs.schema_name, inputs.schema_metadata, logger=inputs.logger)
return doit_source(
config,
inputs.schema_name,
+ report_id,
logger=inputs.logger,
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit.py b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit.py
new file mode 100644
index 000000000000..83555cbef01b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit.py
@@ -0,0 +1,94 @@
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.doit.doit import (
+ LIST_REPORTS_TIMEOUT_SECONDS,
+ REPORT_TIMEOUT_SECONDS,
+ doit_list_reports,
+ doit_source,
+ resolve_report_id,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.doit import DoItSourceConfig
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.doit.doit"
+
+CONFIG = DoItSourceConfig(api_key="key")
+
+
+def _response(payload: Any, status_code: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload
+ response.text = "body"
+ return response
+
+
+class TestResolveReportId:
+ def test_schema_metadata_short_circuits_without_listing_reports(self) -> None:
+ with patch(f"{_MODULE}.doit_list_reports") as mock_list:
+ assert resolve_report_id(CONFIG, "cost_by_product", {"report_id": "r1"}) == "r1"
+
+ mock_list.assert_not_called()
+
+ @pytest.mark.parametrize("schema_metadata", [None, {}, {"report_id": None}])
+ def test_falls_back_to_name_lookup(self, schema_metadata: dict | None) -> None:
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ {"reports": [{"id": "r7", "reportName": "Cost by product"}]}
+ )
+ assert resolve_report_id(CONFIG, "cost_by_product", schema_metadata) == "r7"
+
+ def test_raises_when_no_report_matches_the_name(self) -> None:
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ {"reports": [{"id": "r7", "reportName": "Cost by product"}]}
+ )
+ with pytest.raises(Exception, match="Report no longer exists"):
+ resolve_report_id(CONFIG, "deleted_report", None)
+
+
+class TestDoitListReports:
+ def test_returns_raw_and_normalized_names(self) -> None:
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ {
+ "reports": [
+ {"id": "r1", "reportName": "Cost by product"},
+ {"id": "r2", "reportName": " "},
+ {"id": "r3"},
+ ]
+ }
+ )
+ reports = doit_list_reports(CONFIG)
+
+ assert [(r.id, r.name, r.report_name) for r in reports] == [("r1", "cost_by_product", "Cost by product")]
+
+ def test_non_200_surfaces_the_status_code(self) -> None:
+ # `DOIT_RETRY` sets raise_on_status=False, so an exhausted 5xx lands here as a response;
+ # without the guard it became a JSON/key error with the status lost.
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response({}, status_code=500)
+ with pytest.raises(Exception, match="failed with status: 500"):
+ doit_list_reports(CONFIG)
+
+
+class TestRequestTimeouts:
+ # An unbounded request holds the worker until the activity's start-to-close budget expires,
+ # leaving the schema stuck in "Running" for a day or more.
+ def test_list_reports_is_bounded(self) -> None:
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response({"reports": []})
+ doit_list_reports(CONFIG)
+
+ assert mock_session.return_value.get.call_args.kwargs["timeout"] == LIST_REPORTS_TIMEOUT_SECONDS
+
+ def test_report_fetch_is_bounded(self) -> None:
+ with patch(f"{_MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response({"result": {"schema": [], "rows": []}})
+ source = doit_source(CONFIG, "cost_by_product", "r1", MagicMock(), None)
+ list(cast(Iterable[Any], source.items()))
+
+ assert mock_session.return_value.get.call_args.kwargs["timeout"] == REPORT_TIMEOUT_SECONDS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit_source.py
index f4688d56e799..146aad26a331 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/doit/tests/test_doit_source.py
@@ -1,10 +1,17 @@
import pytest
+from unittest.mock import MagicMock, patch
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import DEFAULT_RETRY
-from products.warehouse_sources.backend.temporal.data_imports.sources.doit.doit import DOIT_RETRY
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.doit.doit import DOIT_RETRY, DoItReport
from products.warehouse_sources.backend.temporal.data_imports.sources.doit.source import DoItSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.doit import DoItSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.doit.source"
+
+CONFIG = DoItSourceConfig(api_key="key")
+
class TestDoItSource:
def setup_method(self):
@@ -13,12 +20,38 @@ class TestDoItSource:
def test_source_type(self):
assert self.source.source_type == ExternalDataSourceType.DOIT
- @pytest.mark.parametrize("pattern", ["Report no longer exists"])
+ @pytest.mark.parametrize("pattern", ["Report no longer exists", "Request to get report failed with status: 404"])
def test_non_retryable_errors_includes_pattern(self, pattern):
errors = self.source.get_non_retryable_errors()
assert pattern in errors
+ def test_get_schemas_stamps_the_report_id_so_renames_stay_resolvable(self):
+ with patch(
+ f"{_SOURCE_MODULE}.doit_list_reports",
+ return_value=[DoItReport(id="r1", name="cost_by_product", report_name="Cost by product")],
+ ):
+ schemas = self.source.get_schemas(CONFIG, team_id=1)
+
+ assert [(s.name, s.label, s.schema_metadata) for s in schemas] == [
+ ("cost_by_product", "Cost by product", {"report_id": "r1"})
+ ]
+
+ def test_source_for_pipeline_fetches_the_report_id_from_schema_metadata(self):
+ inputs = MagicMock(
+ spec=SourceInputs,
+ schema_name="cost_by_product",
+ schema_metadata={"report_id": "r1"},
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ logger=MagicMock(),
+ )
+
+ with patch(f"{_SOURCE_MODULE}.doit_source") as mock_source:
+ self.source.source_for_pipeline(CONFIG, inputs)
+
+ assert mock_source.call_args.args[1:] == ("cost_by_product", "r1")
+
@pytest.mark.parametrize("status_code", [520, 521, 522, 523, 524])
def test_doit_retry_includes_cloudflare_transient_statuses(self, status_code):
assert status_code in (DOIT_RETRY.status_forcelist or ())