: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(warehouse-sources): fall back to a later start when openai rejects the lookback (#112265)
posthog[bot]e4312fc40afe
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.pyindex 7ca290f83cbe..4c2e11174da4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/openai.py@@ -1,11 +1,11 @@import hashlibimport dataclasses-from collections.abc import Callable-from datetime import UTC, date, datetime+from collections.abc import Callable, Iterable, Iterator+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalimport structlog-from requests import Request, Response+from requests import HTTPError, Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resources,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (ClientConfig,EndpointResource,@@ -36,6 +37,11 @@ ENTITY_PAGE_SIZE = 100# usage or cost data can predate this — starting here rather than the epoch avoids requesting# decades of empty buckets while still pulling all available history.DEFAULT_START_TIME = datetime(2020, 1, 1, tzinfo=UTC)+# Some usage endpoints only report a limited window of history and reject an older `start_time` with+# this error code. OpenAI does not document the window per endpoint, so a rejected start moves+# forward through these steps (days before now) until the API accepts one.+LOOKBACK_EXCEEDED_CODE = "reporting_lookback_exceeded"+LOOKBACK_FALLBACK_DAYS = (730, 365, 180, 90, 30, 7)@dataclasses.dataclass@@ -319,6 +325,50 @@ def _make_fanout_data_map(endpoint: str) -> Callable[[dict[str, Any]], dict[str,return _stamp+def _is_lookback_exceeded(error: HTTPError) -> bool:+ response = error.response+ if response is None or response.status_code != 400:+ return False+ try:+ body = response.json()+ except Exception:+ return False+ detail = body.get("error") if isinstance(body, dict) else None+ return isinstance(detail, dict) and detail.get("code") == LOOKBACK_EXCEEDED_CODE+++def _lookback_fallback_starts(requested_start: Any, now: datetime) -> list[datetime]:+ """Later start times to try if OpenAI rejects `requested_start` as too far back, oldest first."""+ requested = _to_unix_seconds(requested_start)+ starts = [now - timedelta(days=days) for days in LOOKBACK_FALLBACK_DAYS]+ return [start for start in starts if int(start.timestamp()) > requested]+++def _iterate_with_lookback_fallback(+ endpoint: str,+ build_resource: Callable[[Optional[datetime]], Iterable[Any]],+ fallback_starts: list[datetime],+) -> Iterator[Any]:+ # Only the first request can fail this way: later pages reuse the same `start_time`. So a page+ # already yielded means the error has another cause, and it must propagate.+ attempts: list[Optional[datetime]] = [None, *fallback_starts]+ for index, start in enumerate(attempts):+ yielded = False+ try:+ for page in build_resource(start):+ yielded = True+ yield page+ return+ except HTTPError as e:+ if yielded or index == len(attempts) - 1 or not _is_lookback_exceeded(e):+ raise+ logger.warning(+ "openai_source.reporting_lookback_exceeded",+ endpoint=endpoint,+ next_start_time=attempts[index + 1],+ )++def _incremental_param(config: OpenAIEndpointConfig) -> Optional[tuple[str, dict[str, Any]]]:"""Server-side time-filter param for an incremental endpoint, or None for full-refresh lists."""if not config.supports_incremental:@@ -359,6 +409,7 @@ def openai_source(}resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ items: Optional[Callable[[], Iterable[Any]]] = Noneif config.fan_out_over_projects:# Project-scoped resources have no org-wide list endpoint; enumerate the projects and fetch@@ -480,18 +531,36 @@ def openai_source(if state and state.get("cursor"):resumable_source_manager.save_state(OpenAIResumeConfig(cursor=state["cursor"]))- resource = rest_api_resource(- rest_config,- team_id,- job_id,- db_incremental_field_last_value,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,- )+ def build_resource(start_override: Optional[datetime] = None) -> Resource:+ # A start override replaces the rejected start, so a page cursor saved for it is stale.+ return rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if start_override is None else start_override,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state if start_override is None else None,+ )++ resource = build_resource()++ if config.pagination == PaginationType.PAGE:+ requested_start = (+ db_incremental_field_last_value if db_incremental_field_last_value is not None else DEFAULT_START_TIME+ )+ fallback_starts = _lookback_fallback_starts(requested_start, datetime.now(UTC))+ # A recent watermark has no later start to fall back to. Keep the framework resource+ # unwrapped in that case, so the pipeline still reaches its safe points.+ if fallback_starts:+ items = lambda: _iterate_with_lookback_fallback(+ endpoint,+ lambda start: resource if start is None else build_resource(start),+ fallback_starts,+ )return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items if items is not None else lambda: resource,primary_keys=config.primary_keys,sort_mode=config.sort_mode,partition_count=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.pyindex 54be7ec61b65..3a4d7aed2db9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/source.py@@ -78,6 +78,8 @@ Create an Admin API key (prefixed `sk-admin...`) in your [OpenAI organization sereturn {"401 Client Error: Unauthorized for url: https://api.openai.com": "Your OpenAI Admin API key is invalid or has been revoked. Create a new Admin API key in your OpenAI organization settings, then reconnect.","403 Client Error: Forbidden for url: https://api.openai.com": "Your OpenAI API key does not have organization admin access. Use an Admin API key (prefixed sk-admin) created by an organization owner, then reconnect.",+ # Reached only after every later start time in the source's fallback was rejected too.+ "code=reporting_lookback_exceeded": "OpenAI doesn't report data this far back for this table, and PostHog couldn't find a start date that OpenAI accepts. Contact support so we can fix the sync.",}def get_retryable_errors(self) -> set[str]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.pyindex a661d5efda74..30a779f469a7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openai/tests/test_openai.py@@ -54,6 +54,13 @@ def _bucket_page(buckets: list[dict[str, Any]], *, has_more: bool, next_page: streturn _response({"data": buckets, "has_more": has_more, "next_page": next_page})+def _lookback_exceeded() -> Response:+ return _response(+ {"error": {"type": "invalid_request_error", "code": "reporting_lookback_exceeded", "message": "too far back"}},+ status=400,+ )++def _make_manager(resume_state: OpenAIResumeConfig | None = None) -> mock.MagicMock:manager = mock.MagicMock()manager.can_resume.return_value = resume_state is not None@@ -212,6 +219,58 @@ class TestBucketParams:assert params[0]["params"]["start_time"] == int(datetime(2020, 1, 1, tzinfo=UTC).timestamp())assert params[0]["params"]["limit"] == 180+ @parameterized.expand(+ [+ ("initial_sync", None),+ ("stale_watermark", datetime(2021, 6, 1, tzinfo=UTC)),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_lookback_exceeded_retries_with_a_later_start(self, _name: str, last_value: Any, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _lookback_exceeded(),+ _lookback_exceeded(),+ _bucket_page(+ [{"start_time": 1, "end_time": 2, "results": [{"model": "a"}]}], has_more=False, next_page=None+ ),+ ],+ )++ manager = _make_manager(OpenAIResumeConfig(cursor="STALE"))+ rows = _rows(_source("usage_audio_speeches", manager, last_value=last_value))++ assert [r["model"] for r in rows] == ["a"]+ starts = [p["params"]["start_time"] for p in params]+ assert starts[0] < starts[1] < starts[2]+ assert starts[2] > int(datetime.now(UTC).timestamp()) - 400 * 24 * 60 * 60+ # The saved page cursor belongs to the rejected start, so a fallback must not send it.+ assert params[0]["params"]["page"] == "STALE"+ assert "page" not in params[1]["params"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_lookback_exceeded_on_every_start_raises_non_retryable_error(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_lookback_exceeded() for _ in range(10)])++ with pytest.raises(requests.HTTPError) as exc_info:+ _rows(_source("usage_vector_stores", _make_manager()))++ assert session.send.call_count == 7+ non_retryable = OpenAISource().get_non_retryable_errors()+ assert any(key in str(exc_info.value) for key in non_retryable)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_lookback_exceeded_on_recent_watermark_does_not_move_start(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_lookback_exceeded(), _bucket_page([], has_more=False, next_page=None)])++ with pytest.raises(requests.HTTPError):+ _rows(_source("usage_vector_stores", _make_manager(), last_value=datetime.now(UTC)))+ assert session.send.call_count == 1+class TestBucketPagination:@mock.patch(CLIENT_SESSION_PATCH)