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): survive a per-project failure in OpenAI fan-out (#80259)

posthog[bot]acc4391873ad
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
index c7973c808002..c1d3cf7bf8de 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/__init__.py
@@ -19,7 +19,7 @@ from .config_setup import (
from .jsonpath_utils import TJsonPath
from .paginators import BasePaginator
from .resource import Resource
-from .rest_client import DEFAULT_RETRY_ATTEMPTS, RESTClient
+from .rest_client import DEFAULT_RETRY_ATTEMPTS, RESTClient, RESTClientRetryableError
from .typing import ClientConfig, Endpoint, EndpointResource, HTTPMethodBasic, ResolvedParam, RESTAPIConfig
from .utils import exclude_keys # noqa: F401
@@ -82,12 +82,18 @@ def rest_api_resources(
db_incremental_field_last_value: Optional[Any],
resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,
initial_paginator_state: Optional[dict[str, Any]] = None,
+ on_parent_error: Optional[Callable[[str, Exception], None]] = None,
) -> list[Resource]:
"""Creates a list of resources from a REST API configuration.
Prefer ``rest_api_resource`` (singular) for the common single-resource
case. This function is needed for multi-resource configs like date-chunked
report endpoints or parent/child fanout.
+
+ ``on_parent_error`` opts a parent/child fanout into per-parent fault tolerance: when a parent's
+ child pagination raises ``RESTClientRetryableError`` (a transient failure the client's own
+ retries could not clear), the fanout hands the parent path and error to this callback and moves
+ on to the next parent instead of failing the whole resource. Without it, that error propagates.
"""
client_config = config["client"]
resource_defaults = config.get("resource_defaults") or {}
@@ -112,6 +118,7 @@ def rest_api_resources(
db_incremental_field_last_value=db_incremental_field_last_value,
resume_hook=resume_hook,
initial_paginator_state=initial_paginator_state,
+ on_parent_error=on_parent_error,
)
return list(resources.values())
@@ -131,6 +138,7 @@ def _make_paginate_dependent_resource(
initial_state: Optional[dict[str, Any]] = None,
data_selector_required: bool = False,
data_selector_empty_ok: bool = False,
+ on_parent_error: Optional[Callable[[str, Exception], None]] = None,
) -> Callable[..., Iterator[list[Any]]]:
"""Build the generator for a dependent (child) resource.
@@ -190,23 +198,38 @@ def _make_paginate_dependent_resource(
current_child_state = paginator_state
checkpoint(_path, paginator_state)
- for child_page in client.paginate(
- method=method,
- path=formatted_path,
- params=dict(params),
- paginator=paginator,
- data_selector=data_selector,
- hooks=hooks,
- resume_hook=child_resume_hook if resume_hook is not None else None,
- initial_paginator_state=child_initial,
- data_selector_required=data_selector_required,
- data_selector_empty_ok=data_selector_empty_ok,
- ):
- if parent_record:
- for child_record in child_page:
- child_record.update(parent_record)
-
- yield list(convert_types(child_page, effective_columns_config))
+ try:
+ for child_page in client.paginate(
+ method=method,
+ path=formatted_path,
+ params=dict(params),
+ paginator=paginator,
+ data_selector=data_selector,
+ hooks=hooks,
+ resume_hook=child_resume_hook if resume_hook is not None else None,
+ initial_paginator_state=child_initial,
+ data_selector_required=data_selector_required,
+ data_selector_empty_ok=data_selector_empty_ok,
+ ):
+ if parent_record:
+ for child_record in child_page:
+ child_record.update(parent_record)
+
+ yield list(convert_types(child_page, effective_columns_config))
+ except RESTClientRetryableError as exc:
+ # One parent whose child resource keeps failing after the client exhausts its own
+ # retries must not sink the whole fan-out. When the caller opts in, skip that parent,
+ # hand the failure to the handler, and move on so every other parent's rows land.
+ if on_parent_error is None:
+ raise
+ on_parent_error(formatted_path, exc)
+ if resume_hook is not None:
+ # Clear the in-progress pointer so a later retry re-attempts this parent from the
+ # start; leave it off `completed` so it is never permanently skipped.
+ current_path = None
+ current_child_state = None
+ checkpoint(None, None)
+ continue
if resume_hook is not None:
completed.add(formatted_path)
@@ -227,6 +250,7 @@ def create_resources(
db_incremental_field_last_value: Optional[Any] = None,
resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,
initial_paginator_state: Optional[dict[str, Any]] = None,
+ on_parent_error: Optional[Callable[[str, Exception], None]] = None,
) -> dict[str, Resource]:
resources: dict[str, Resource] = {}
@@ -381,6 +405,7 @@ def create_resources(
initial_state=dependent_initial_state,
data_selector_required=bool(endpoint_config.get("data_selector_required")),
data_selector_empty_ok=bool(endpoint_config.get("data_selector_empty_ok")),
+ on_parent_error=on_parent_error,
)
resources[resource_name] = Resource(
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.py
index 05d8f7e2dd38..b033f088b64e 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
@@ -4,6 +4,7 @@ from collections.abc import Callable
from datetime import UTC, date, datetime
from typing import Any, Optional
+import structlog
from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -26,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.openai.set
PaginationType,
)
+logger = structlog.get_logger(__name__)
+
OPENAI_BASE_URL = "https://api.openai.com"
# Entity list endpoints allow up to 100 per page.
ENTITY_PAGE_SIZE = 100
@@ -385,6 +388,18 @@ def openai_source(
if state:
resumable_source_manager.save_state(OpenAIResumeConfig(fanout_state=state))
+ def skip_failing_project(path: str, exc: Exception) -> None:
+ # A single project whose resource keeps returning a transient 5xx (after the client
+ # exhausts its retries) would otherwise fail the whole schema, with no workaround for the
+ # user. Skip that project, record it, and let every other project's rows land; the next
+ # sync re-attempts the skipped one once OpenAI recovers.
+ logger.warning(
+ "openai_source.skipped_failing_project",
+ endpoint=endpoint,
+ path=path,
+ error=str(exc),
+ )
+
resources = rest_api_resources(
rest_config,
team_id,
@@ -392,6 +407,7 @@ def openai_source(
db_incremental_field_last_value,
resume_hook=save_fanout_checkpoint,
initial_paginator_state=initial_fanout_state,
+ on_parent_error=skip_failing_project,
)
resource = next(r for r in resources if r.name == endpoint)
else:
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.py
index d9a3ffdb4fe3..75558895d4a7 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
@@ -19,6 +19,7 @@ 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.generated_configs.openai import OpenAISourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.openai.openai import (
+ OPENAI_BASE_URL,
OpenAIResumeConfig,
openai_source,
validate_credentials as validate_openai_credentials,
@@ -81,6 +82,19 @@ Create an Admin API key (prefixed `sk-admin...`) in your [OpenAI organization se
"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.",
}
+ def get_retryable_errors(self) -> set[str]:
+ # The shared RESTClient (rest_client.py) already retries 429/5xx responses, connection
+ # resets, timeouts, and malformed-JSON bodies in-process via tenacity (5 attempts,
+ # exponential backoff honoring Retry-After) before re-raising RESTClientRetryableError.
+ # A failure that survives all 5 attempts is a transient OpenAI / edge blip, not a bug —
+ # Temporal's activity retry recovers once the upstream issue clears, so keep it out of
+ # error tracking as noise. The status code and path vary per request; the API host doesn't,
+ # so match on that rather than the volatile parts of the message.
+ return {
+ f"for {OPENAI_BASE_URL}",
+ f"from {OPENAI_BASE_URL}",
+ }
+
def get_schemas(
self,
config: OpenAISourceConfig,
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.py
index 9d71ab6b8960..7f1cfcc73f13 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
@@ -551,6 +551,30 @@ class TestProjectFanOut:
assert [(r["project_id"], r["id"]) for r in rows] == [("proj_1", "user_1")]
+ @mock.patch(TENACITY_SLEEP_PATCH, return_value=None)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_one_project_500ing_is_skipped_and_others_land(self, MockSession, _sleep) -> None:
+ # proj_1's resource keeps returning 500 past the client's retry budget; without per-project
+ # tolerance that would fail the whole schema. The fan-out must skip proj_1 and still yield
+ # proj_2's rows.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _entity_page([{"id": "proj_1"}, {"id": "proj_2"}], has_more=False, last_id="proj_2"),
+ *[_response({}, status=500) for _ in range(5)],
+ _entity_page([{"id": "user_2"}], has_more=False, last_id="user_2"),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("project_users", manager))
+
+ assert [(r["project_id"], r["id"]) for r in rows] == [("proj_2", "user_2")]
+ # The skipped project stays off the completed checkpoint so a later run re-attempts it.
+ final = [call.args[0] for call in manager.save_state.call_args_list][-1].fanout_state
+ assert final["completed"] == [PROJECT_USERS_PATH.format(project_id="proj_2")]
+
def test_saved_state_shapes_still_parse(self) -> None:
# ResumableSourceManager._load_json does dataclass(**saved) — every historical shape must
# keep parsing after the migration.
@@ -642,6 +666,34 @@ class TestNonRetryableErrors:
assert not any(key in other_error for key in non_retryable)
+class TestRetryableErrors:
+ @parameterized.expand(
+ [
+ ("server_error", "HTTP 500 for https://api.openai.com/v1/organization/projects/proj_1/api_keys"),
+ ("rate_limited", "HTTP 429 for https://api.openai.com/v1/organization/costs"),
+ ("connection_error", "Connection error (ConnectionError) for https://api.openai.com/v1/organization/users"),
+ ("timeout", "Request timed out (ReadTimeout) for https://api.openai.com/v1/organization/usage/completions"),
+ (
+ "malformed_json",
+ "Malformed JSON response from https://api.openai.com/v1/organization/costs: Expecting value: line 1 column 1 (char 0)",
+ ),
+ ]
+ )
+ def test_exhausted_transient_failures_are_recognized(self, _name: str, observed_error: str) -> None:
+ retryable = OpenAISource().get_retryable_errors()
+ assert any(pattern in observed_error for pattern in retryable)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.openai.com/v1/organization/users"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.openai.com/v1/organization/costs"),
+ ]
+ )
+ def test_credential_errors_are_not_misclassified(self, _name: str, other_error: str) -> None:
+ retryable = OpenAISource().get_retryable_errors()
+ assert not any(pattern in other_error for pattern in retryable)
+
+
class TestToolCallUsageGroupBy:
# Each tool-usage endpoint advertises a distinct group_by set; requesting a dimension the endpoint
# does not support (e.g. `model` on file_search) makes the live API 400, so guard the composition.