: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(data-warehouse): correct stripe subscription discount expand encoding (#61368)
Tom Owersd15dacc4b64a
diff --git a/posthog/temporal/data_imports/sources/stripe/stripe.py b/posthog/temporal/data_imports/sources/stripe/stripe.pyindex 60caee5c2f20..bb11c56f34a6 100644--- a/posthog/temporal/data_imports/sources/stripe/stripe.py+++ b/posthog/temporal/data_imports/sources/stripe/stripe.py@@ -71,15 +71,21 @@ def _call_stripe(method: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:"""Invoke a Stripe SDK list method and rewrite any StripeError it raises with a cleanedmessage — primarily collapsing the long asterisk run from redacted restricted keys.- Re-raises the same exception class (so framework-level non-retryable error matching on+ Re-raises the same exception instance (so framework-level non-retryable error matching on`"PermissionError"` etc. continues to work) but with a shorter, frontend-friendly messagethat still preserves the actionable detail Stripe surfaces (which scope is missing).++ The message is mutated in place rather than reconstructed: StripeError subclasses have+ differing constructor signatures (e.g. InvalidRequestError requires a positional `param`),+ so `type(e)(message=...)` would itself raise a TypeError and mask the original error."""try:return method(*args, **kwargs)except stripe_lib.StripeError as e:- cleaned = _clean_stripe_error_message(str(e))- raise type(e)(message=cleaned) from e+ cleaned = _clean_stripe_error_message(e._message or "")+ e._message = cleaned+ e.args = (cleaned,)+ raisedef _stripe_base_addresses() -> BaseAddresses:@@ -146,7 +152,10 @@ def _build_resources("status": "all",# Expand discount objects so coupon details (amount_off, percent_off, duration) are inline.# Without expansion Stripe returns only discount IDs, which prevents revenue projection.- "expand[]": ["data.discounts", "data.items.data.discounts"],+ # Key must be "expand" (not "expand[]") for a list value: the SDK encodes it as+ # expand[0]=…&expand[1]=…, whereas "expand[]" + a list yields expand[][0]=… (doubled+ # brackets), which Stripe rejects with "Invalid string: {...}".+ "expand": ["data.discounts", "data.items.data.discounts"],},),CREDIT_NOTE_RESOURCE_NAME: StripeResource(method=client.credit_notes.list),diff --git a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.pyindex c422aae4b2fe..de1b4720268b 100644--- a/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py+++ b/posthog/temporal/tests/data_imports/stripe/test_stripe_source.py@@ -5,6 +5,7 @@ import pytestfrom unittest import mockimport stripe as stripe_lib+from stripe._http_client import HTTPClientfrom posthog.models.integration import Integrationfrom posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -25,6 +26,7 @@ from posthog.temporal.data_imports.sources.stripe.stripe import (StripeResumeConfig,StripeValidationError,_build_resources,+ _call_stripe,_clean_stripe_error_message,check_endpoint_permissions,get_rows,@@ -310,7 +312,10 @@ def test_subscription_list_uses_expand_for_discounts():mock_client.subscriptions.list.assert_called_once()call_params = mock_client.subscriptions.list.call_args.kwargs["params"]assert call_params["status"] == "all"- assert call_params["expand[]"] == ["data.discounts", "data.items.data.discounts"]+ # Key must be "expand" (not "expand[]"): a list under "expand[]" encodes to expand[][0]=…+ # (doubled brackets) which Stripe rejects. See _build_resources for the full explanation.+ assert call_params["expand"] == ["data.discounts", "data.items.data.discounts"]+ assert "expand[]" not in call_params@pytest.mark.parametrize("endpoint", WEBHOOK_ONLY_ENDPOINTS)@@ -561,6 +566,70 @@ def test_clean_stripe_error_message_passthrough_when_no_redaction():assert _clean_stripe_error_message(msg) == msg+def test_subscription_expand_encodes_as_array_not_object():+ """End-to-end encoding regression: the discount expand must reach Stripe as+ expand[0]=…&expand[1]=… (a real array), not expand[][0]=… which Stripe parses as an+ array-of-one-object and rejects with "Invalid string: {...}". The mock-based test above+ can't catch this because it intercepts above the SDK's query-string encoding."""+ captured: dict[str, str] = {}++ class RecordingHTTPClient(HTTPClient):+ name = "recording"++ def request_with_retries(self, method, url, headers, post_data=None, max_network_retries=None, *, _usage=None):+ captured["url"] = url+ body = '{"object":"list","data":[],"has_more":false,"url":"/v1/subscriptions"}'+ return body, 200, {"request-id": "req_test"}++ def request_stream_with_retries(+ self, method, url, headers, post_data=None, max_network_retries=None, *, _usage=None+ ):+ raise NotImplementedError++ client = stripe_lib.StripeClient("sk_test_x", http_client=RecordingHTTPClient())+ resources = _build_resources(client)+ subscription = resources[SUBSCRIPTION_RESOURCE_NAME]+ subscription.method(params=subscription.params)++ url = captured["url"]+ assert "expand[0]=data.discounts" in url+ assert "expand[1]=data.items.data.discounts" in url+ # The doubled-bracket form is the bug — Stripe rejects it.+ assert "expand[][0]" not in url+++ "error_factory",+ [+ # InvalidRequestError requires a positional `param` — the regression that broke imports.+ lambda msg: stripe_lib.InvalidRequestError(msg, "expand[]"),+ lambda msg: stripe_lib.PermissionError(msg),+ lambda msg: stripe_lib.AuthenticationError(msg),+ lambda msg: stripe_lib.APIConnectionError(msg),+ ],+)+def test_call_stripe_cleans_message_and_preserves_error_type(error_factory):+ """_call_stripe must re-raise the same StripeError subclass with a cleaned message.+ Reconstructing via `type(e)(message=...)` broke for subclasses with extra required+ args (e.g. InvalidRequestError's `param`), so we mutate the message in place instead."""+ raw = "The provided key 'rk_live_" + ("*" * 80) + "gbeftZ' is invalid"++ def boom():+ raise error_factory(raw)++ with pytest.raises(stripe_lib.StripeError) as exc_info:+ _call_stripe(boom)++ raised = exc_info.value+ assert type(raised) is type(error_factory(raw))+ assert "*" * 80 not in str(raised)+ assert "rk_live_***gbeftZ" in str(raised)+++def test_call_stripe_passes_through_successful_result():+ assert _call_stripe(lambda x: x + 1, 41) == 42++def test_validate_credentials_nested_resources_have_registered_parents():"""Invariant: every StripeNestedResource's `parent_name` must point at a key that isalso registered as a top-level StripeResource in _build_resources. validate_credentials