: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
feat(warehouse_sources): size shopify orders pages from the query cost (#116522)
Daniel RCde37b14880cd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.pyindex 48dd803e49c5..9f738f66bcb9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/constants.py@@ -45,8 +45,13 @@ PRODUCTS = "products"SHOP = "shop"SUBSCRIPTION_CONTRACTS = "subscriptionContracts"-# graphql will reject the orders endpoint query for "complexity cost" if the page size is above ~35-SHOPIFY_PAGE_SIZE_OVERRIDES = {ORDERS: 20}+# Shopify rejects a query whose requested cost is above 1000 points, and the cost grows with the+# page size. An object listed here starts at a page size that is known to fit. The request layer+# then grows the page from the cost Shopify reports.+SHOPIFY_COST_LIMITED_START_PAGE_SIZES = {ORDERS: 20}+SHOPIFY_MAX_QUERY_COST = 1000+# The largest `first` Shopify accepts on a connection.+SHOPIFY_MAX_PAGE_SIZE = 250# NOTE: some of the permissions queries may seem random. not every field on a given graphql objectdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.pyindex 05089fd8b4ee..15ad3a27e1c5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/shopify.py@@ -37,9 +37,11 @@ from .constants import (SHOPIFY_ACCESS_TOKEN_URL,SHOPIFY_API_URL,SHOPIFY_API_VERSION_2026_07,+ SHOPIFY_COST_LIMITED_START_PAGE_SIZES,SHOPIFY_DEFAULT_PAGE_SIZE,SHOPIFY_GRAPHQL_OBJECTS,- SHOPIFY_PAGE_SIZE_OVERRIDES,+ SHOPIFY_MAX_PAGE_SIZE,+ SHOPIFY_MAX_QUERY_COST,)logger = structlog.get_logger(__name__)@@ -300,6 +302,51 @@ def _shopify_retry_wait(retry_state: RetryCallState) -> float:return backoff+# The share of Shopify's single-query cost limit that a resized page aims for.+_SHOPIFY_QUERY_COST_TARGET = 0.9+# The share of the store's cost bucket that one request can ask for. Shopify throttles a request+# when the bucket holds less than its requested cost, and every table of the source uses the bucket.+_SHOPIFY_COST_BUCKET_SHARE = 0.5++_SHOPIFY_MAX_COST_EXCEEDED_CODE = "MAX_COST_EXCEEDED"+_SHOPIFY_MAX_COST_EXCEEDED_MESSAGE = "exceeds the single query max cost limit"+++class ShopifyQueryCostExceededError(Exception):+ """Shopify rejected the query because its requested cost is above the single-query limit."""+++def _is_max_cost_exceeded(errors: Any) -> bool:+ if not isinstance(errors, list):+ return False+ for error in errors:+ if not isinstance(error, dict):+ continue+ extensions = error.get("extensions")+ if isinstance(extensions, dict) and extensions.get("code") == _SHOPIFY_MAX_COST_EXCEEDED_CODE:+ return True+ if _SHOPIFY_MAX_COST_EXCEEDED_MESSAGE in str(error.get("message", "")):+ return True+ return False+++def _page_size_for_cost(page_size: int, payload: Any) -> int:+ """The page size that brings the requested cost of this query near Shopify's single-query limit.++ Shopify sizes the requested cost from the `first` arguments, not from the rows it returns, so+ the cost of one page predicts the cost of a larger one. Returns `page_size` when the response+ has no usable cost.+ """+ requested, ok = safe_unwrap(payload, path="extensions.cost.requestedQueryCost")+ if not ok or isinstance(requested, bool) or not isinstance(requested, int | float) or requested <= 0:+ return page_size+ target = SHOPIFY_MAX_QUERY_COST * _SHOPIFY_QUERY_COST_TARGET+ bucket_size, ok = safe_unwrap(payload, path="extensions.cost.throttleStatus.maximumAvailable")+ if ok and not isinstance(bucket_size, bool) and isinstance(bucket_size, int | float) and bucket_size > 0:+ target = min(target, bucket_size * _SHOPIFY_COST_BUCKET_SHARE)+ return min(SHOPIFY_MAX_PAGE_SIZE, int(page_size * target / requested))++def _make_paginated_shopify_request(url: str,sess: requests.Session,@@ -345,6 +392,8 @@ def _make_paginated_shopify_request(if "errors" in payload:error_messages = [e.get("message", "") for e in payload["errors"]]joined = "; ".join(error_messages)+ if _is_max_cost_exceeded(payload["errors"]):+ raise ShopifyQueryCostExceededError(f"Shopify GraphQL error: {joined}")raise Exception(f"Shopify GraphQL error: {joined}")if "data" not in payload:@@ -352,8 +401,9 @@ def _make_paginated_shopify_request(return payload- pageSize = SHOPIFY_PAGE_SIZE_OVERRIDES.get(graphql_object.name, SHOPIFY_DEFAULT_PAGE_SIZE)- vars: dict[str, Any] = {"pageSize": pageSize}+ starting_page_size = SHOPIFY_COST_LIMITED_START_PAGE_SIZES.get(graphql_object.name, SHOPIFY_DEFAULT_PAGE_SIZE)+ size_page_from_cost = graphql_object.name in SHOPIFY_COST_LIMITED_START_PAGE_SIZES+ vars: dict[str, Any] = {"pageSize": starting_page_size}logger.debug(f"Using page size {vars['pageSize']} for object {graphql_object.name}")if query:vars.update({"query": query})@@ -362,7 +412,34 @@ def _make_paginated_shopify_request(has_next_page = Truewhile has_next_page:logger.debug(f"Querying shopify endpoint {graphql_object.name} with vars: {vars}")- payload = execute(vars)+ try:+ payload = execute(vars)+ except (+ ShopifyQueryCostExceededError,+ ShopifyRetryableError,+ requests.exceptions.ConnectionError,+ requests.exceptions.Timeout,+ ) as e:+ if not size_page_from_cost or vars["pageSize"] <= starting_page_size:+ raise+ # A grown page can be too costly or too slow for Shopify to answer. The starting size+ # is known to work, so read the same cursor again at that size and stop growing.+ logger.debug(+ f"Shopify could not serve page size {vars['pageSize']} for {graphql_object.name}, "+ f"using {starting_page_size}. {e}"+ )+ size_page_from_cost = False+ vars["pageSize"] = starting_page_size+ continue+ if size_page_from_cost:+ # The starting size already works, so the cost only ever grows the page from it.+ next_page_size = max(starting_page_size, _page_size_for_cost(vars["pageSize"], payload))+ if next_page_size != vars["pageSize"]:+ logger.debug(+ f"Changing page size for {graphql_object.name} from {vars['pageSize']} to {next_page_size}. "+ f"Query cost: {payload['extensions']['cost']}"+ )+ vars["pageSize"] = next_page_sizedata = unwrap(payload, path=f"data.{graphql_object.name}.nodes")if endpoint_config is not None:if endpoint_config.incremental_field_resolver:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_resumable.pyindex 5d4f2aafcd3a..7f17f2781cbf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shopify/tests/test_resumable.py@@ -3,6 +3,8 @@ from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch+import requests+from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.constants import (ABANDONED_CHECKOUTS,ORDERS,@@ -12,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.shopify.shPHASE_ALL,PHASE_EARLIEST,PHASE_LATEST,+ ShopifyQueryCostExceededError,ShopifyResumeConfig,_make_paginated_shopify_request,shopify_source,@@ -90,6 +93,113 @@ class TestMakePaginatedShopifyRequest:assert saved_configs[0] == ShopifyResumeConfig(phase=PHASE_ALL, cursor="cursor-1")assert saved_configs[1] == ShopifyResumeConfig(phase=PHASE_ALL, cursor="cursor-2")+ @pytest.mark.parametrize(+ "object_name, cost, expected_page_sizes",+ [+ # 450 points at 20 rows leaves room for 40 rows under the 900 point target.+ (ORDERS, {"requestedQueryCost": 450}, [20, 40]),+ (ORDERS, {"requestedQueryCost": 10}, [20, 250]),+ # Half of a 400 point bucket is 200 points, which is 40 rows at 5 points a row.+ (ORDERS, {"requestedQueryCost": 100, "throttleStatus": {"maximumAvailable": 400}}, [20, 40]),+ (ABANDONED_CHECKOUTS, {"requestedQueryCost": 450}, [100, 100]),+ ],+ )+ def test_grows_page_from_reported_cost_only_for_cost_limited_objects(+ self, object_name: str, cost: dict[str, Any], expected_page_sizes: list[int]+ ) -> None:+ sess = MagicMock()+ first_page = _build_response(object_name, [{"id": "1"}], has_next_page=True, end_cursor="cursor-1")+ first_page.json.return_value["extensions"] = {"cost": cost}+ captured = _record_post_vars(+ sess, [first_page, _build_response(object_name, [{"id": "2"}], has_next_page=False, end_cursor=None)]+ )++ list(+ _make_paginated_shopify_request(+ "https://example.invalid/graphql", sess, SHOPIFY_GRAPHQL_OBJECTS[object_name], MagicMock()+ )+ )++ assert [variables["pageSize"] for variables in captured] == expected_page_sizes++ @pytest.mark.parametrize(+ "failed_requests",+ [+ [{"errors": [{"message": "Query cost is too high", "extensions": {"code": "MAX_COST_EXCEEDED"}}]}],+ [{"errors": [{"message": "Query cost is 1057, which exceeds the single query max cost limit (1000)."}]}],+ [requests.exceptions.ReadTimeout("Read timed out")] * 5,+ ],+ ids=["cost_error_code", "cost_error_message", "timeouts_until_retries_run_out"],+ )+ @patch("tenacity.nap.time.sleep")+ def test_grown_page_that_fails_is_read_again_at_the_starting_size_for_the_rest_of_the_read(+ self, _mock_sleep: MagicMock, failed_requests: list[Any]+ ) -> None:+ def page(node_id: str, end_cursor: str | None) -> MagicMock:+ response = _build_response(+ ORDERS, [{"id": node_id}], has_next_page=end_cursor is not None, end_cursor=end_cursor+ )+ response.json.return_value["extensions"] = {"cost": {"requestedQueryCost": 450}}+ return response++ def failure(outcome: Any) -> Any:+ if isinstance(outcome, Exception):+ return outcome+ response = MagicMock()+ response.status_code = 200+ response.json.return_value = outcome+ return response++ outcomes = [+ page("1", "cursor-1"),+ *[failure(outcome) for outcome in failed_requests],+ page("2", "cursor-2"),+ page("3", None),+ ]+ captured: list[tuple[int, str | None]] = []+ sess = MagicMock()++ def post(url: str, json: dict[str, Any]) -> MagicMock:+ captured.append((json["variables"]["pageSize"], json["variables"].get("cursor")))+ outcome = outcomes[len(captured) - 1]+ if isinstance(outcome, Exception):+ raise outcome+ return outcome++ sess.post.side_effect = post++ batches = list(+ _make_paginated_shopify_request(+ "https://example.invalid/graphql", sess, SHOPIFY_GRAPHQL_OBJECTS[ORDERS], MagicMock()+ )+ )++ assert batches == [[{"id": "1"}], [{"id": "2"}], [{"id": "3"}]]+ assert captured == [+ (20, None),+ *[(40, "cursor-1")] * len(failed_requests),+ (20, "cursor-1"),+ (20, "cursor-2"),+ ]++ def test_cost_rejection_at_the_starting_size_fails_after_one_request(self) -> None:+ sess = MagicMock()+ rejected = MagicMock()+ rejected.status_code = 200+ rejected.json.return_value = {+ "errors": [{"message": "Query cost is too high", "extensions": {"code": "MAX_COST_EXCEEDED"}}]+ }+ sess.post.return_value = rejected++ with pytest.raises(ShopifyQueryCostExceededError):+ list(+ _make_paginated_shopify_request(+ "https://example.invalid/graphql", sess, SHOPIFY_GRAPHQL_OBJECTS[ORDERS], MagicMock()+ )+ )++ assert sess.post.call_count == 1+def test_seeds_initial_cursor_on_resume(self) -> None:graphql_object = SHOPIFY_GRAPHQL_OBJECTS[ABANDONED_CHECKOUTS]logger = MagicMock()