: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(meta-ads): drop heavy fields when meta refuses the smallest entity page (#123488)
posthog[bot]0f6e68e684ab
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.pyindex 78b08105b4ab..1f6b9b8d7e44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py@@ -212,7 +212,8 @@ class MetaAdsSchema:single_object: bool = False# Scalar columns to copy out of the nested objects in each row (see `HoistedColumn`).hoisted_columns: tuple[HoistedColumn, ...] = ()- # Fields Meta can refuse to serve for a single row (see `META_REFUSED_CREATIVE_ERROR_SUBCODES`).+ # Fields Meta can refuse to serve for a single row (see `META_REFUSED_CREATIVE_ERROR_SUBCODES`), or+ # heavy fields that can make even the smallest page too much data. Both read them back per row.refusable_fields: tuple[str, ...] = ()@@ -918,9 +919,10 @@ def _iter_simple_pagination(then raised as retryable (see ``ENTITY_PAGE_REFUSED_ERROR_MESSAGE``).When Meta refuses a page for one row's ``refusable_fields`` (see- ``META_REFUSED_CREATIVE_ERROR_SUBCODES``), the same page is fetched- again without those fields, and the fields are read back per row from- ``node_lookup_url``. The next page asks for every field again.+ ``META_REFUSED_CREATIVE_ERROR_SUBCODES``), or the smallest page is still+ too much data, the same page is fetched again without those fields, and+ the fields are read back per row from ``node_lookup_url``. The next page+ asks for every field again."""access_token = params["access_token"]current_limit = PAGE_LIMIT_FALLBACK_SIZES[0]@@ -976,6 +978,12 @@ def _iter_simple_pagination(current_limit = smallerresponse = _issue()continue+ # A Meta refusal that persists at the smallest page is the same request every time, so+ # backoff alone never clears it when a few rows carry very large heavy fields.+ if refusable_fields and node_lookup_url is not None and not without_refusable_fields:+ without_refusable_fields = True+ response = _issue()+ continueif smallest_limit_retries < SMALLEST_PAGE_LIMIT_MAX_RETRIES:smallest_limit_retries += 1_backoff_sleep(smallest_limit_retries)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.pyindex 3845987b8c60..b87fcc682e7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/schemas.py@@ -367,6 +367,8 @@ RESOURCE_SCHEMAS: dict[MetaAdsResource, dict[str, Any]] = {"partition_mode": "datetime","partition_format": "week","partition_keys": ["created_time"],+ # An adset's targeting spec can be large enough that Meta refuses even the smallest page.+ "refusable_fields": ("targeting", "promoted_object"),},MetaAdsResource.AdsetStats: {"primary_keys": ["adset_id", "account_id", "date_start"],diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.pyindex e46ef313719b..c9a02fa88022 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/test_meta_ads.py@@ -336,6 +336,64 @@ class TestSimplePaginationLimitFallback:assert batches == [[{"id": "1"}]]assert mock_get.return_value.get.call_args_list[-1].kwargs["params"]["limit"] == PAGE_LIMIT_FALLBACK_SIZES[-1]+ def test_smallest_limit_refusal_drops_refusable_fields_and_reads_them_per_row(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)+ manager = _build_manager()+ params = {**self.PARAMS, "fields": "id,name,targeting"}+ get_responses = [+ *(_mock_response(500, self.REDUCE_BODY) for _ in PAGE_LIMIT_FALLBACK_SIZES),+ _mock_response(200, {"data": [{"id": "1", "name": "a"}], "paging": {}}),+ ]+ batch_response = mock.MagicMock()+ batch_response.status_code = 200+ batch_response.json.return_value = [+ {"code": 200, "body": json.dumps({"id": "1", "targeting": {"age_min": 18}})}+ ]++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"+ ) as mock_get:+ mock_get.return_value.get.side_effect = get_responses+ mock_get.return_value.post.side_effect = [batch_response]+ batches = list(+ _iter_simple_pagination(+ self.INITIAL_URL, params, None, manager, ("targeting",), "https://graph.facebook.com/v20/"+ )+ )++ assert batches == [[{"id": "1", "name": "a", "targeting": {"age_min": 18}}]]+ get_calls = mock_get.return_value.get.call_args_list+ # Every rung of the ladder is tried with the full field list before any field is dropped.+ assert len(get_calls) == len(PAGE_LIMIT_FALLBACK_SIZES) + 1+ assert all(call.kwargs["params"]["fields"] == "id,name,targeting" for call in get_calls[:-1])+ assert get_calls[-1].kwargs["params"]["fields"] == "id,name"+ assert get_calls[-1].kwargs["params"]["limit"] == PAGE_LIMIT_FALLBACK_SIZES[-1]++ def test_smallest_limit_refusal_without_refusable_fields_still_raises_retryable_error(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(meta_ads_module, "_backoff_sleep", lambda attempt: None)+ manager = _build_manager()+ params = {**self.PARAMS, "fields": "id,name,targeting"}+ attempts = len(PAGE_LIMIT_FALLBACK_SIZES) + 1 + SMALLEST_PAGE_LIMIT_MAX_RETRIES+ responses = [_mock_response(500, self.REDUCE_BODY) for _ in range(attempts)]++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.meta_ads.make_tracked_session"+ ) as mock_get:+ mock_get.return_value.get.side_effect = responses+ with pytest.raises(Exception, match="smallest page size"):+ list(+ _iter_simple_pagination(+ self.INITIAL_URL, params, None, manager, ("targeting",), "https://graph.facebook.com/v20/"+ )+ )++ assert mock_get.return_value.get.call_count == attempts+ mock_get.return_value.post.assert_not_called()+def test_non_timeout_error_does_not_retry(self) -> None:manager = _build_manager()# A generic application error outside Meta's documented transient codes (1, 2) — not a