Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add per-webhook payloadGeneration to opt out of deferred payloads (#19916) (#19920)
Marcin Wcisło3dd4bf79a461
diff --git a/docs/adr/0011-deferred-webhook-payloads-reflect-state-at-generation-time.md b/docs/adr/0011-deferred-webhook-payloads-reflect-state-at-generation-time.mdnew file mode 100644index 0000000000..300705f40d--- /dev/null+++ b/docs/adr/0011-deferred-webhook-payloads-reflect-state-at-generation-time.md@@ -0,0 +1,78 @@+# Deferred webhook payloads reflect state at generation time, not at trigger time++**Tags:** webhook, orders, checkout, concurrency++For the high-volume async events (orders, draft orders, fulfillments, checkouts, per-channel+stock and discounted-price changes) the subscription-webhook payload is not built in the request+that triggered the event. The request records only a pointer (the object's identity, the+requestor and the request time), creates `PENDING` deliveries with no payload, and enqueues a+background task. That task re-reads the object and resolves the subscription query against the+database as it is at that moment. Whether an event is deferred is a per-event flag in+`WebhookEventAsyncType.EVENT_MAP`.++The motivation is request latency. Resolving a subscription query for a large order means+running GraphQL resolvers, dataloaders and often sync webhook calls such as tax calculation, and+doing that once per subscribed app inside the mutation made the heaviest order and checkout+mutations noticeably slower. Moving it to a worker keeps the mutation's cost independent of how+many apps subscribe and how deep their queries are.++The accepted consequence is that an async webhook is a notification that something happened,+carrying the object's current state, not a snapshot of the state at the time it happened. If a+field was `A` when the mutation ran and `B` by the time the task runs, every pending delivery for+that object carries `B`. Two mutations in quick succession produce two deliveries that are+indistinguishable to the receiver. If the object is deleted before the task runs, the deliveries+are marked `FAILED` and no webhook is sent. Consumers that need the previous value must keep it+themselves. The snapshot alternative, serializing the payload in the request and storing it, is+exactly the cost the decision removes, so it was rejected rather than offered as an opt-in.++This applies to subscription webhooks only. Legacy webhooks without a subscription query still+serialize their payload inline and therefore do see the request-time state. The same event can+reach a legacy receiver with `A` and a subscription receiver with `B`.++The task reads from the read replica, and the replica may lag behind the write that created the+deliveries. Instead of reading from the writer, the task waits: it checks that the delivery rows+are visible on the replica and retries with backoff until they are, pinning the check and the+payload generation to a single replica connection so they see one snapshot. Reading from the+writer would move the full payload-generation load onto the primary, which is the database that+every pod shares and the scaling bottleneck.++## Per-webhook opt-out++Deferral is right by default but not for every consumer. An integration that applies each+`ORDER_METADATA_UPDATED` in sequence, expecting the metadata as written by each request, breaks+when several pending deliveries all carry the final state. Each webhook therefore carries a+`payloadGeneration` choice, `DEFERRED` by default or `IMMEDIATE`, set by the app that registers it+through the mutations or the manifest. An `IMMEDIATE` subscription webhook on a deferred event has+its payload built by whatever triggered the event, as every webhook did before deferral, and only+that webhook pays the cost. For events fired from a request that is the mutation's latency. For+events fired from a background task, such as the variant price and stock events, it is that task's+run time, which is why those events were deferred from the start. An app that sets `IMMEDIATE` on+such an event takes that cost knowingly. Because such a task may fire the event with a replica-allowed+manager right after its own write, an `IMMEDIATE` payload on a deferrable event is resolved against the+writer, so the dataloader-resolved fields cannot predate the write. Fields read from the subscribable+object itself still reflect where the caller loaded it from. The choice is ignored where it cannot apply: legacy+webhooks without a subscription query, sync events, and events that are not deferred.++## When each event became deferred++Deferral was rolled out event by event, so the version in which a consumer starts seeing+generation-time state depends on the event. Dates are merge dates on `main`. The release is the+first tagged version that ships the change.++| Event | Deferred since | Release | Change |+|---|---|---|---|+| `CHECKOUT_CREATED`, `CHECKOUT_UPDATED` | 2024-11-15 | 3.21.0 | Introduced the mechanism (#16999) |+| `ORDER_CREATED`, `ORDER_CONFIRMED`, `ORDER_PAID`, `ORDER_FULLY_PAID`, `ORDER_REFUNDED`, `ORDER_FULLY_REFUNDED`, `ORDER_UPDATED`, `ORDER_CANCELLED`, `ORDER_EXPIRED`, `ORDER_FULFILLED`, `ORDER_METADATA_UPDATED` | 2026-02-17 | 3.23.0 | Moved from inline to deferred (#18809) |+| `DRAFT_ORDER_CREATED`, `DRAFT_ORDER_UPDATED` | 2026-02-17 | 3.23.0 | Moved from inline to deferred (#18809) |+| `FULFILLMENT_CANCELED`, `FULFILLMENT_METADATA_UPDATED`, `FULFILLMENT_TRACKING_NUMBER_UPDATED` | 2026-02-17 | 3.23.0 | Moved from inline to deferred (#18809) |+| `PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED` | 2026-03-31 | 3.23.0, backported to 3.22.45 | New event, deferred from the start (#19004, #18973) |+| `PRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL`, `PRODUCT_VARIANT_BACK_IN_STOCK_IN_CHANNEL`, `PRODUCT_VARIANT_OUT_OF_STOCK_FOR_CLICK_AND_COLLECT`, `PRODUCT_VARIANT_BACK_IN_STOCK_FOR_CLICK_AND_COLLECT` | 2026-04-21 | 3.23.2 | New events, deferred from the start (#19144) |++`FULFILLMENT_CREATED` and `FULFILLMENT_APPROVED` were flagged as deferred together with the other+order events on 2026-02-17 and reverted to inline on 2026-04-02 (#19012), before 3.23.0 was+released. Their subscribable object is a plain dict rather than a model or a registered dataclass,+so it cannot be reconstructed in the task. No released version delivers them deferred.++Everything not listed, including `ORDER_BULK_CREATED`, `DRAFT_ORDER_DELETED` and all events+outside orders, checkout and variant stock or price, still builds its payload inline and carries+request-time state.diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 5672b41254..ef3a6f8ff3 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -316,6 +316,7 @@ def install_app(subscription_query=webhook["query"],custom_headers=webhook.get("customHeaders", None),identifier=webhook.get("identifier"),+ payload_generation=webhook["payloadGeneration"],)for webhook in manifest_data.get("webhooks", []))diff --git a/saleor/app/manifest_schema.py b/saleor/app/manifest_schema.pyindex ccf4c8cf85..6d0b91f6ec 100644--- a/saleor/app/manifest_schema.py+++ b/saleor/app/manifest_schema.py@@ -76,6 +76,7 @@ class ManifestWebhookSchema(BaseModel):sync_events: list[str] = []custom_headers: dict | None = Noneidentifier: str | None = None+ payload_generation: str | None = None@field_validator("target_url")@classmethoddiff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.pyindex 35c7880d57..e5c84448d1 100644--- a/saleor/app/manifest_validations.py+++ b/saleor/app/manifest_validations.py@@ -22,6 +22,7 @@ from ..permission.enums import ()from ..permission.models import Permissionfrom ..webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ..webhook.models import WebhookPayloadGenerationfrom ..webhook.validators import custom_headers_validatorfrom .error_codes import AppErrorCodefrom .manifest_schema import (@@ -292,6 +293,31 @@ def _clean_webhook_identifier(webhook, seen_identifiers, errors):seen_identifiers.add(identifier)+def _clean_webhook_payload_generation(webhook, errors):+ """Map the manifest's `payloadGeneration` enum name to its stored value.++ Accepts the GraphQL enum names (`DEFERRED`, `IMMEDIATE`), like event names+ do. A missing value means `DEFERRED`.+ """+ payload_generation_values = {+ str_to_enum(value): value for value, _ in WebhookPayloadGeneration.CHOICES+ }+ raw_value = webhook.get("payloadGeneration")+ if raw_value is None:+ webhook["payloadGeneration"] = WebhookPayloadGeneration.DEFERRED+ return+ try:+ webhook["payloadGeneration"] = payload_generation_values[raw_value]+ except KeyError:+ allowed = ", ".join(payload_generation_values)+ errors["webhooks"].append(+ ValidationError(+ f"Invalid payload generation: {raw_value}. Allowed values: {allowed}.",+ code=AppErrorCode.INVALID.value,+ )+ )++def _clean_webhooks(manifest_data, errors):webhooks = manifest_data.get("webhooks", [])@@ -305,6 +331,7 @@ def _clean_webhooks(manifest_data, errors):seen_identifiers: set[str] = set()for webhook in webhooks:_clean_webhook_identifier(webhook, seen_identifiers, errors)+ _clean_webhook_payload_generation(webhook, errors)webhook["isActive"] = webhook.get("isActive", True)diff --git a/saleor/app/tests/test_installation_utils.py b/saleor/app/tests/test_installation_utils.pyindex c61036fe3d..fdd6a6558b 100644--- a/saleor/app/tests/test_installation_utils.py+++ b/saleor/app/tests/test_installation_utils.py@@ -15,6 +15,7 @@ from requests_hardened import HTTPSessionfrom ... import __version__, schema_versionfrom ...core.utils.json_serializer import CustomJsonEncoderfrom ...webhook.event_types import WebhookEventAsyncType+from ...webhook.models import WebhookPayloadGenerationfrom ...webhook.payloads import generate_meta, generate_requestorfrom ..error_codes import AppErrorCodefrom ..installation_utils import (@@ -1131,3 +1132,43 @@ def test_install_app_with_too_long_deprecation_reason_does_not_fail_install(# thenassert app.deprecation_reason == expectedassert len(app.deprecation_reason) == DEPRECATION_REASON_MAX_LENGTH+++def test_install_app_with_webhook_payload_generation(+ app_manifest, app_manifest_webhook, app_installation, monkeypatch+):+ # given+ app_manifest_webhook["payloadGeneration"] = "IMMEDIATE"+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())++ # when+ app, _ = install_app(app_installation, activate=True)++ # then+ webhook = app.webhooks.get()+ assert webhook.payload_generation == WebhookPayloadGeneration.IMMEDIATE+++def test_install_app_without_webhook_payload_generation_defaults_to_deferred(+ app_manifest, app_manifest_webhook, app_installation, monkeypatch+):+ # given+ assert "payloadGeneration" not in app_manifest_webhook+ app_manifest["webhooks"] = [app_manifest_webhook]++ mocked_get_response = Mock()+ mocked_get_response.json.return_value = app_manifest+ monkeypatch.setattr(HTTPSession, "request", Mock(return_value=mocked_get_response))+ monkeypatch.setattr("saleor.app.installation_utils.send_app_token", Mock())++ # when+ app, _ = install_app(app_installation, activate=True)++ # then+ webhook = app.webhooks.get()+ assert webhook.payload_generation == WebhookPayloadGeneration.DEFERREDdiff --git a/saleor/app/tests/test_manifest_validations.py b/saleor/app/tests/test_manifest_validations.pyindex 1e2844ad71..a13d9f5c18 100644--- a/saleor/app/tests/test_manifest_validations.py+++ b/saleor/app/tests/test_manifest_validations.py@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationErrorfrom pydantic import ValidationError as PydanticValidationErrorfrom ...permission.enums import AppPermission, ProductPermissions+from ...webhook.models import WebhookPayloadGenerationfrom ..error_codes import AppErrorCodefrom ..manifest_schema import (EXTENSION_IDENTIFIER_MAX_LENGTH,@@ -436,7 +437,7 @@ def _extension(label, identifier=None):return extension-def _webhook(name, identifier=None):+def _webhook(name, identifier=None, payload_generation=None):webhook = {"name": name,"targetUrl": "https://example.com/webhook",@@ -444,6 +445,8 @@ def _webhook(name, identifier=None):}if identifier is not None:webhook["identifier"] = identifier+ if payload_generation is not None:+ webhook["payloadGeneration"] = payload_generationreturn webhook@@ -770,3 +773,60 @@ def test_manifest_schema_deprecated_fields_accepted():# then — original dict is untouched; downstream readers can still access the valuesassert manifest_data["dataPrivacy"] == data_privacyassert manifest_data["configurationUrl"] == configuration_url+++def test_clean_manifest_data_maps_webhook_payload_generation_to_stored_value():+ # given+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", payload_generation="IMMEDIATE")],+ }++ # when+ clean_manifest_data(manifest_data)++ # then+ assert (+ manifest_data["webhooks"][0]["payloadGeneration"]+ == WebhookPayloadGeneration.IMMEDIATE+ )+++def test_clean_manifest_data_defaults_webhook_payload_generation_to_deferred():+ # given+ manifest_data = {**MINIMAL_MANIFEST, "webhooks": [_webhook("First")]}++ # when+ clean_manifest_data(manifest_data)++ # then+ assert (+ manifest_data["webhooks"][0]["payloadGeneration"]+ == WebhookPayloadGeneration.DEFERRED+ )+++def test_clean_manifest_data_rejects_unknown_webhook_payload_generation():+ # given+ invalid_value = "immediate"+ manifest_data = {+ **MINIMAL_MANIFEST,+ "webhooks": [_webhook("First", payload_generation=invalid_value)],+ }++ # when+ with pytest.raises(ValidationError) as exc_info:+ clean_manifest_data(manifest_data)++ # then+ webhook_errors = exc_info.value.error_dict["webhooks"]+ assert len(webhook_errors) == 1+ error = webhook_errors[0]+ assert error.code == AppErrorCode.INVALID.value+ assert error.message == (+ f"Invalid payload generation: {invalid_value}. "+ "Allowed values: DEFERRED, IMMEDIATE."+ )diff --git a/saleor/graphql/meta/tests/mutations/test_order.py b/saleor/graphql/meta/tests/mutations/test_order.pyindex 851a287ca5..baeb1d5bf2 100644--- a/saleor/graphql/meta/tests/mutations/test_order.py+++ b/saleor/graphql/meta/tests/mutations/test_order.py@@ -1,12 +1,15 @@+import jsonfrom unittest.mock import ANY, patchimport graphene+import pytestfrom django.test import override_settingsfrom .....core.models import EventDeliveryfrom .....order import OrderStatusfrom .....payment.models import TransactionItemfrom .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from .....webhook.models import WebhookPayloadGenerationfrom . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUEfrom .test_delete_metadata import (execute_clear_public_metadata_for_item,@@ -787,3 +790,115 @@ def test_change_in_private_metadata_triggers_webhooks(filter_shipping_delivery.event_type== WebhookEventSyncType.ORDER_FILTER_SHIPPING_METHODS)+++ORDER_METADATA_UPDATED_METADATA_SUBSCRIPTION = """+ subscription {+ event {+ ... on OrderMetadataUpdated {+ order {+ id+ metadata {+ key+ value+ }+ }+ }+ }+ }+"""+++def order_metadata_subscription_webhook(subscription_webhook):+ return subscription_webhook(+ ORDER_METADATA_UPDATED_METADATA_SUBSCRIPTION,+ WebhookEventAsyncType.ORDER_METADATA_UPDATED,+ )+++@patch(+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_consecutive_metadata_updates_immediate_webhook_carries_each_value(+ mocked_send_webhook_request_async,+ mocked_generate_deferred_payloads,+ order_metadata_subscription_webhook,+ staff_api_client,+ order,+ permission_manage_orders,+):+ # given+ webhook = order_metadata_subscription_webhook+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ order_id = graphene.Node.to_global_id("Order", order.pk)+ existing_metadata = dict(order.metadata)+ key = "status"+ first_value = "picking"+ second_value = "packed"++ # when+ execute_update_public_metadata_for_item(+ staff_api_client, None, order_id, "Order", key, first_value+ )+ execute_update_public_metadata_for_item(+ staff_api_client, None, order_id, "Order", key, second_value+ )++ # then - each delivery carries the metadata written by its own request+ mocked_generate_deferred_payloads.assert_not_called()+ deliveries = list(EventDelivery.objects.filter(webhook=webhook).order_by("pk"))+ assert len(deliveries) == 2+ first_payload = json.loads(deliveries[0].payload.get_payload())+ second_payload = json.loads(deliveries[1].payload.get_payload())+ assert {+ item["key"]: item["value"] for item in first_payload["order"]["metadata"]+ } == {**existing_metadata, key: first_value}+ assert {+ item["key"]: item["value"] for item in second_payload["order"]["metadata"]+ } == {**existing_metadata, key: second_value}+ assert mocked_send_webhook_request_async.call_count == 2+++@patch(+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+@patch(+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])+def test_consecutive_metadata_updates_deferred_webhook_defers_both_payloads(+ mocked_send_webhook_request_async,+ mocked_generate_deferred_payloads,+ order_metadata_subscription_webhook,+ staff_api_client,+ order,+ permission_manage_orders,+):+ # given+ webhook = order_metadata_subscription_webhook+ assert webhook.payload_generation == WebhookPayloadGeneration.DEFERRED+ staff_api_client.user.user_permissions.add(permission_manage_orders)+ order_id = graphene.Node.to_global_id("Order", order.pk)+ key = "status"++ # when+ execute_update_public_metadata_for_item(+ staff_api_client, None, order_id, "Order", key, "picking"+ )+ execute_update_public_metadata_for_item(+ staff_api_client, None, order_id, "Order", key, "packed"+ )++ # then - no payload exists yet; both will be built from the final state+ deliveries = list(EventDelivery.objects.filter(webhook=webhook).order_by("pk"))+ assert len(deliveries) == 2+ assert [delivery.payload for delivery in deliveries] == [None, None]+ assert mocked_generate_deferred_payloads.call_count == 2+ mocked_send_webhook_request_async.assert_not_called()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 808b74640e..f7bac3747a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1792,6 +1792,13 @@ type Webhook implements Node @doc(category: "Webhooks") {"""Custom headers, which will be added to HTTP request."""customHeaders: JSONString++ """+ Determines when the subscription payload is built for asynchronous events that defer payload generation. Ignored for webhooks without a subscription query, for synchronous events and for events that do not defer their payload.++ Added in Saleor 3.23.+ """+ payloadGeneration: WebhookPayloadGenerationEnum!}"""An object with an ID"""@@ -14585,6 +14592,20 @@ input EventDeliveryFilterInput {eventType: WebhookEventTypeEnum}+"""+Determines when the subscription payload of an asynchronous webhook is built for events that defer payload generation.++`DEFERRED`: the payload is built in a background task and reflects the object's state at the time the task runs.++`IMMEDIATE`: the payload is built by whatever triggered the event, a request or a background task, and reflects the object's state at that moment, at the cost of slowing that request or task.++Added in Saleor 3.23.+"""+enum WebhookPayloadGenerationEnum @doc(category: "Webhooks") {+ DEFERRED+ IMMEDIATE+}+enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {ACCOUNT_CONFIRMATION_REQUESTEDACCOUNT_CHANGE_EMAIL_REQUESTED@@ -23137,6 +23158,13 @@ input WebhookCreateInput @doc(category: "Webhooks") {Custom headers, which will be added to HTTP request. There is a limitation of 5 headers per webhook and 998 characters per header.Only `X-*`, `Authorization*`, and `BrokerProperties` keys are allowed."""customHeaders: JSONString++ """+ Determines when the subscription payload is built for asynchronous events that defer payload generation. Defaults to `DEFERRED`. Ignored for webhooks without a subscription query, for synchronous events and for events that do not defer their payload.++ Added in Saleor 3.23.+ """+ payloadGeneration: WebhookPayloadGenerationEnum}"""@@ -23200,6 +23228,13 @@ input WebhookUpdateInput @doc(category: "Webhooks") {Custom headers, which will be added to HTTP request. There is a limitation of 5 headers per webhook and 998 characters per header.Only `X-*`, `Authorization*`, and `BrokerProperties` keys are allowed."""customHeaders: JSONString++ """+ Determines when the subscription payload is built for asynchronous events that defer payload generation. Omit to keep the current value, `null` resets it to `DEFERRED`. Ignored for webhooks without a subscription query, for synchronous events and for events that do not defer their payload. A change applies to events triggered after the update. Deliveries already created finish the way they started, so around a change a newer delivery can be sent before an older one.++ Added in Saleor 3.23.+ """+ payloadGeneration: WebhookPayloadGenerationEnum}"""diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.pyindex 912a342764..7767a2ec32 100644--- a/saleor/graphql/webhook/enums.py+++ b/saleor/graphql/webhook/enums.py@@ -1,6 +1,7 @@import graphenefrom ...webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType+from ...webhook.models import WebhookPayloadGenerationfrom ..core.descriptions import (ADDED_IN_323,DEFAULT_DEPRECATION_REASON,@@ -356,3 +357,21 @@ class EventDeliveryStatusEnum(BaseEnum):class Meta:doc_category = DOC_CATEGORY_WEBHOOKS+++class WebhookPayloadGenerationEnum(BaseEnum):+ DEFERRED = WebhookPayloadGeneration.DEFERRED+ IMMEDIATE = WebhookPayloadGeneration.IMMEDIATE++ class Meta:+ description = (+ "Determines when the subscription payload of an asynchronous webhook "+ "is built for events that defer payload generation."+ "\n\n`DEFERRED`: the payload is built in a background task and "+ "reflects the object's state at the time the task runs."+ "\n\n`IMMEDIATE`: the payload is built by whatever triggered the "+ "event, a request or a background task, and reflects the object's "+ "state at that moment, at the cost of slowing that request or task."+ + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_WEBHOOKSdiff --git a/saleor/graphql/webhook/mutations/webhook_create.py b/saleor/graphql/webhook/mutations/webhook_create.pyindex 23cb7d41d2..c1acc1e3db 100644--- a/saleor/graphql/webhook/mutations/webhook_create.py+++ b/saleor/graphql/webhook/mutations/webhook_create.py@@ -75,6 +75,15 @@ class WebhookCreateInput(BaseInputObjectType):f"Only `X-*`, `Authorization*`, and `BrokerProperties` keys are allowed.",required=False,)+ payload_generation = enums.WebhookPayloadGenerationEnum(+ description=(+ "Determines when the subscription payload is built for asynchronous "+ "events that defer payload generation. Defaults to `DEFERRED`. "+ "Ignored for webhooks without a subscription query, for synchronous "+ "events and for events that do not defer their payload." + ADDED_IN_323+ ),+ required=False,+ )class Meta:doc_category = DOC_CATEGORY_WEBHOOKSdiff --git a/saleor/graphql/webhook/mutations/webhook_trigger.py b/saleor/graphql/webhook/mutations/webhook_trigger.pyindex a244d59706..9d0082cc1f 100644--- a/saleor/graphql/webhook/mutations/webhook_trigger.py+++ b/saleor/graphql/webhook/mutations/webhook_trigger.py@@ -16,7 +16,7 @@ from ....graphql.utils import get_user_or_app_from_contextfrom ....permission.auth_filters import AuthorizationFiltersfrom ....webhook.error_codes import WebhookTriggerErrorCodefrom ....webhook.event_types import WebhookEventAsyncType-from ....webhook.models import Webhook+from ....webhook.models import Webhook, WebhookPayloadGenerationfrom ....webhook.transport.asynchronous.transport import (create_deliveries_for_subscriptions,generate_deferred_payloads,@@ -168,7 +168,12 @@ class WebhookTrigger(BaseMutation):]:object = [object]- is_deferred_payload = get_is_deferred_payload(event_type)+ # The webhook's `payload_generation` is read here, once, when the+ # delivery is created. See `Webhook.payload_generation`.+ is_deferred_payload = (+ get_is_deferred_payload(event_type)+ and webhook.payload_generation == WebhookPayloadGeneration.DEFERRED+ )if is_deferred_payload:delivery = core_models.EventDelivery(status=EventDeliveryStatus.PENDING,@@ -192,7 +197,11 @@ class WebhookTrigger(BaseMutation):)else:deliveries = create_deliveries_for_subscriptions(- event_type, object, [webhook]+ event_type,+ object,+ [webhook],+ requestor=requestor,+ request_time=info.context.request_time,)if deliveries:delivery = deliveries[0]diff --git a/saleor/graphql/webhook/mutations/webhook_update.py b/saleor/graphql/webhook/mutations/webhook_update.pyindex b3bb80e140..080fb131ff 100644--- a/saleor/graphql/webhook/mutations/webhook_update.py+++ b/saleor/graphql/webhook/mutations/webhook_update.py@@ -74,6 +74,19 @@ class WebhookUpdateInput(BaseInputObjectType):f"Only `X-*`, `Authorization*`, and `BrokerProperties` keys are allowed.",required=False,)+ payload_generation = enums.WebhookPayloadGenerationEnum(+ description=(+ "Determines when the subscription payload is built for asynchronous "+ "events that defer payload generation. Omit to keep the current "+ "value, `null` resets it to `DEFERRED`. Ignored for webhooks without "+ "a subscription query, for "+ "synchronous events and for events that do not defer their payload. "+ "A change applies to events triggered after the update. Deliveries "+ "already created finish the way they started, so around a change a "+ "newer delivery can be sent before an older one." + ADDED_IN_323+ ),+ required=False,+ )class Meta:doc_category = DOC_CATEGORY_WEBHOOKSdiff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py b/saleor/graphql/webhook/tests/mutations/test_webhook_create.pyindex 07c94ff6bf..88b1f515da 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_create.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_create.py@@ -6,9 +6,13 @@ import pytestfrom .....app.error_codes import AppErrorCodefrom .....webhook.error_codes import WebhookErrorCode-from .....webhook.models import Webhook+from .....webhook.models import Webhook, WebhookPayloadGenerationfrom ....tests.utils import assert_no_permission, get_graphql_content-from ...enums import WebhookEventTypeAsyncEnum, WebhookEventTypeSyncEnum+from ...enums import (+ WebhookEventTypeAsyncEnum,+ WebhookEventTypeSyncEnum,+ WebhookPayloadGenerationEnum,+)WEBHOOK_CREATE = """mutation webhookCreate($input: WebhookCreateInput!){@@ -21,6 +25,7 @@ WEBHOOK_CREATE = """webhook {ididentifier+ payloadGenerationasyncEvents {eventType}@@ -604,3 +609,70 @@ def test_webhook_create_assigns_filterable_channel_slugs_above_max_limit(error = content["data"]["webhookCreate"]["errors"][0]assert error["field"] == "query"assert error["code"] == WebhookErrorCode.INVALID.name+++def test_webhook_create_with_immediate_payload_generation(+ app_api_client, permission_manage_orders+):+ # given+ variables = {+ "input": {+ "name": "New integration",+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_METADATA_UPDATED.name],+ "payloadGeneration": WebhookPayloadGenerationEnum.IMMEDIATE.name,+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == []+ assert (+ data["webhook"]["payloadGeneration"]+ == WebhookPayloadGenerationEnum.IMMEDIATE.name+ )+ assert Webhook.objects.get().payload_generation == (+ WebhookPayloadGeneration.IMMEDIATE+ )+++def test_webhook_create_without_payload_generation_defaults_to_deferred(+ app_api_client, permission_manage_orders+):+ # given+ variables = {+ "input": {+ "name": "New integration",+ "targetUrl": "https://www.example.com",+ "asyncEvents": [WebhookEventTypeAsyncEnum.ORDER_METADATA_UPDATED.name],+ }+ }++ # when+ response = app_api_client.post_graphql(+ WEBHOOK_CREATE,+ variables=variables,+ permissions=[permission_manage_orders],+ check_no_permissions=False,+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookCreate"]+ assert data["errors"] == []+ assert (+ data["webhook"]["payloadGeneration"]+ == WebhookPayloadGenerationEnum.DEFERRED.name+ )+ assert Webhook.objects.get().payload_generation == (+ WebhookPayloadGeneration.DEFERRED+ )diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.pyindex 6b8bf52473..71f3f785ce 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_trigger.py@@ -10,7 +10,7 @@ from .....core import EventDeliveryStatusfrom .....graphql.tests.utils import get_graphql_contentfrom .....webhook.error_codes import WebhookTriggerErrorCodefrom .....webhook.event_types import WebhookEventAsyncType-from .....webhook.models import Webhook+from .....webhook.models import Webhook, WebhookPayloadGenerationfrom .....webhook.transport.asynchronous.transport import generate_deferred_payloadsfrom ....tests.utils import assert_no_permissionfrom ...subscription_types import WEBHOOK_TYPES_MAP@@ -33,6 +33,23 @@ WEBHOOK_TRIGGER_MUTATION = """}"""+CHECKOUT_UPDATED_WITH_ISSUING_PRINCIPAL_SUBSCRIPTION = """+subscription {+ event {+ ... on CheckoutUpdated {+ issuingPrincipal {+ ... on User {+ id+ }+ }+ checkout {+ id+ }+ }+ }+}+"""+DRAFT_ORDER_DELETE_SUBSCRIPTION = """subscription {event {@@ -435,3 +452,53 @@ def test_webhook_trigger_for_deferred_payload(assert mocked_send_webhook_request_async.calledsend_webhook_kwargs = mocked_send_webhook_request_async.call_args.kwargs["kwargs"]assert send_webhook_kwargs["event_delivery_id"] == delivery_pk+++ "saleor.webhook.transport.asynchronous.transport.send_webhook_using_scheme_method"+)[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+def test_webhook_trigger_immediate_webhook_on_deferred_event(+ mocked_generate_deferred_payloads,+ mocked_send_sync_webhook,+ mocked_send_webhook_using_scheme_method,+ staff_api_client,+ checkout,+ subscription_webhook,+ permission_manage_checkouts,+ webhook_response,+):+ # given+ mocked_send_webhook_using_scheme_method.return_value = webhook_response+ staff_api_client.user.user_permissions.add(permission_manage_checkouts)+ webhook = subscription_webhook(+ CHECKOUT_UPDATED_WITH_ISSUING_PRINCIPAL_SUBSCRIPTION,+ WebhookEventAsyncType.CHECKOUT_UPDATED,+ )+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.id)+ variables = {"webhookId": webhook_id, "objectId": checkout_id}+ mocked_send_sync_webhook.return_value = []++ # when+ response = staff_api_client.post_graphql(WEBHOOK_TRIGGER_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookTrigger"]+ assert data["errors"] == []+ mocked_generate_deferred_payloads.assert_not_called()++ # the payload was built in the request and sent right away+ mocked_send_webhook_using_scheme_method.assert_called_once()+ sent_data = json.loads(mocked_send_webhook_using_scheme_method.call_args.args[4])+ assert sent_data["checkout"]["id"] == checkout_id+ # the requestor is carried into the payload, as on the deferred path+ assert sent_data["issuingPrincipal"]["id"] == graphene.Node.to_global_id(+ "User", staff_api_client.user.pk+ )diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py b/saleor/graphql/webhook/tests/mutations/test_webhook_update.pyindex f2679e8328..4b0e1392b3 100644--- a/saleor/graphql/webhook/tests/mutations/test_webhook_update.py+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_update.py@@ -5,10 +5,10 @@ import grapheneimport pytestfrom .....app.models import App-from .....webhook.models import Webhook+from .....webhook.models import Webhook, WebhookPayloadGenerationfrom ....core.enums import WebhookErrorCodefrom ....tests.utils import assert_no_permission, get_graphql_content-from ...enums import WebhookEventTypeAsyncEnum+from ...enums import WebhookEventTypeAsyncEnum, WebhookPayloadGenerationEnumWEBHOOK_UPDATE = """mutation webhookUpdate ($id: ID!, $input: WebhookUpdateInput!) {@@ -20,6 +20,7 @@ WEBHOOK_UPDATE = """}webhook {identifier+ payloadGenerationsyncEvents {eventType}@@ -812,3 +813,55 @@ def test_webhook_update_null_identifier_never_matches_webhook_without_identifier]webhook.refresh_from_db(fields=("is_active",))assert webhook.is_active is True+++def test_webhook_update_payload_generation(app_api_client, webhook):+ # given+ assert webhook.payload_generation == WebhookPayloadGeneration.DEFERRED+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ variables = {+ "id": webhook_id,+ "input": {+ "payloadGeneration": WebhookPayloadGenerationEnum.IMMEDIATE.name,+ },+ }++ # when+ response = app_api_client.post_graphql(WEBHOOK_UPDATE, variables=variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookUpdate"]+ assert data["errors"] == []+ assert (+ data["webhook"]["payloadGeneration"]+ == WebhookPayloadGenerationEnum.IMMEDIATE.name+ )+ webhook.refresh_from_db(fields=("payload_generation",))+ assert webhook.payload_generation == WebhookPayloadGeneration.IMMEDIATE+++def test_webhook_update_without_payload_generation_keeps_current_value(+ app_api_client, webhook+):+ # given+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ webhook_id = graphene.Node.to_global_id("Webhook", webhook.pk)+ new_name = "Renamed webhook"+ variables = {"id": webhook_id, "input": {"name": new_name}}++ # when+ response = app_api_client.post_graphql(WEBHOOK_UPDATE, variables=variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["webhookUpdate"]+ assert data["errors"] == []+ assert (+ data["webhook"]["payloadGeneration"]+ == WebhookPayloadGenerationEnum.IMMEDIATE.name+ )+ webhook.refresh_from_db(fields=("name", "payload_generation"))+ assert webhook.name == new_name+ assert webhook.payload_generation == WebhookPayloadGeneration.IMMEDIATEdiff --git a/saleor/graphql/webhook/types.py b/saleor/graphql/webhook/types.pyindex 812ded558c..98d594a46f 100644--- a/saleor/graphql/webhook/types.py+++ b/saleor/graphql/webhook/types.py@@ -204,6 +204,15 @@ class Webhook(ModelObjectType[models.Webhook]):custom_headers = JSONString(description="Custom headers, which will be added to HTTP request.")+ payload_generation = enums.WebhookPayloadGenerationEnum(+ required=True,+ description=(+ "Determines when the subscription payload is built for asynchronous "+ "events that defer payload generation. Ignored for webhooks without a "+ "subscription query, for synchronous events and for events that do "+ "not defer their payload." + ADDED_IN_323+ ),+ )class Meta:description = "Webhook."diff --git a/saleor/webhook/migrations/0015_webhook_payload_generation.py b/saleor/webhook/migrations/0015_webhook_payload_generation.pynew file mode 100644index 0000000000..fc8c33c23a--- /dev/null+++ b/saleor/webhook/migrations/0015_webhook_payload_generation.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.18 on 2026-10-14 14:12++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("webhook", "0014_webhook_identifier_unique_constraint"),+ ]++ operations = [+ migrations.AddField(+ model_name="webhook",+ name="payload_generation",+ field=models.CharField(+ choices=[("deferred", "Deferred"), ("immediate", "Immediate")],+ db_default="deferred",+ default="deferred",+ max_length=32,+ ),+ ),+ ]diff --git a/saleor/webhook/migrations/0016_merge_20261016_0603.py b/saleor/webhook/migrations/0016_merge_20261016_0603.pynew file mode 100644index 0000000000..449a6a55ea--- /dev/null+++ b/saleor/webhook/migrations/0016_merge_20261016_0603.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.18 on 2026-10-16 06:03++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("webhook", "0015_drop_export_completed_events"),+ ("webhook", "0015_webhook_payload_generation"),+ ]++ operations = []diff --git a/saleor/webhook/models.py b/saleor/webhook/models.pyindex 8003aea8d9..67da5c3482 100644--- a/saleor/webhook/models.py+++ b/saleor/webhook/models.py@@ -15,6 +15,16 @@ class WebhookURLField(models.URLField):]+class WebhookPayloadGeneration:+ DEFERRED = "deferred"+ IMMEDIATE = "immediate"++ CHOICES = [+ (DEFERRED, "Deferred"),+ (IMMEDIATE, "Immediate"),+ ]++class Webhook(models.Model):name = models.CharField(max_length=255, null=True, blank=True)app = models.ForeignKey(App, related_name="webhooks", on_delete=models.CASCADE)@@ -41,6 +51,19 @@ class Webhook(models.Model):# that doesn't set an identifier. Empty string stays blocked by the# identifier_not_blank CheckConstraint below.identifier = models.CharField(max_length=256, null=True, blank=True)+ # How the subscription payload is built for async events that defer payload+ # generation (`is_deferred_payload` in the event map). The value is read once,+ # when a delivery is created by whatever triggered the event, a request or a+ # background task. Changing it never affects deliveries already created or+ # tasks already queued: those finish the way they started. It is ignored for+ # webhooks without a subscription query, for sync events and for events that+ # do not defer payload generation.+ payload_generation = models.CharField(+ max_length=32,+ choices=WebhookPayloadGeneration.CHOICES,+ default=WebhookPayloadGeneration.DEFERRED,+ db_default=WebhookPayloadGeneration.DEFERRED,+ )class Meta:ordering = ("pk",)diff --git a/saleor/webhook/tests/test_models.py b/saleor/webhook/tests/test_models.pyindex 3fa819b164..d90ebc5290 100644--- a/saleor/webhook/tests/test_models.py+++ b/saleor/webhook/tests/test_models.py@@ -3,7 +3,7 @@ from django.db import IntegrityErrorfrom django.db.transaction import atomicfrom ...app.models import App-from ..models import Webhook+from ..models import Webhook, WebhookPayloadGenerationTARGET_URL = "http://www.example.com/test"@@ -47,3 +47,12 @@ def test_webhook_identifier_cannot_be_blank(app):# given / when / then - a blank identifier is rejected at the database levelwith pytest.raises(IntegrityError, match="webhook_identifier_not_blank"), atomic():Webhook.objects.create(app=app, target_url=TARGET_URL, identifier="")+++def test_webhook_payload_generation_defaults_to_deferred(app):+ # when+ webhook = Webhook.objects.create(app=app, target_url="http://www.example.com")++ # then+ webhook.refresh_from_db(fields=("payload_generation",))+ assert webhook.payload_generation == WebhookPayloadGeneration.DEFERREDdiff --git a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.pyindex 84c1338da4..6c73606e0d 100644--- a/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py+++ b/saleor/webhook/transport/asynchronous/tests/test_deferred_payload.py@@ -21,6 +21,7 @@ from .....warehouse.tests.webhooks.subscriptions.test_channel_stock_events imporPRODUCT_VARIANT_OUT_OF_STOCK_IN_CHANNEL,)from ....event_types import WebhookEventAsyncType+from ....models import WebhookPayloadGenerationfrom ....tests.subscription_webhooks.subscription_queries import (PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED,)@@ -29,6 +30,7 @@ from ..transport import (DeferredPayloadData,_reconstruct_subscribable_object,generate_deferred_payloads,+ initialize_request,trigger_webhooks_async,)@@ -86,6 +88,360 @@ def test_call_trigger_webhook_async_deferred_payload(assert delivery.webhook == checkout_updated_webhook[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+def test_call_trigger_webhook_async_immediate_webhook_builds_payload_in_request(+ mocked_generate_deferred_payloads,+ mocked_send_webhook_request_async,+ mocked_send_sync_webhook,+ checkout_with_item,+ setup_checkout_webhooks,+ staff_user,+):+ # given+ checkout = checkout_with_item+ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED+ assert WebhookEventAsyncType.EVENT_MAP[event_type]["is_deferred_payload"] is True+ _, _, _, checkout_updated_webhook = setup_checkout_webhooks(event_type)+ checkout_updated_webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ checkout_updated_webhook.save(update_fields=["payload_generation"])+ webhooks = get_webhooks_for_event(event_type)+ mocked_send_sync_webhook.return_value = []++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=checkout,+ requestor=staff_user,+ )++ # then+ mocked_generate_deferred_payloads.assert_not_called()++ delivery = EventDelivery.objects.get(webhook=checkout_updated_webhook)+ assert delivery.event_type == event_type+ payload = json.loads(delivery.payload.get_payload())+ assert payload["issuingPrincipal"]["id"] == graphene.Node.to_global_id(+ "User", staff_user.pk+ )+ assert set(payload["checkout"]) == {+ "shippingMethods",+ "shippingPrice",+ "totalPrice",+ }++ mocked_send_webhook_request_async.assert_called_once()+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk+++ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+def test_call_trigger_webhook_async_immediate_webhook_with_dataclass(+ mocked_generate_deferred_payloads,+ mocked_send_webhook_request_async,+ variant_with_many_stocks,+ channel_USD,+ subscription_webhook,+ staff_user,+):+ # given+ variant = variant_with_many_stocks+ event_type = WebhookEventAsyncType.PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED+ assert WebhookEventAsyncType.EVENT_MAP[event_type]["is_deferred_payload"] is True+ webhook = subscription_webhook(PRODUCT_VARIANT_DISCOUNTED_PRICE_UPDATED, event_type)+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ webhooks = get_webhooks_for_event(event_type)++ previous_price = Decimal("10.00")+ new_price = Decimal("8.00")+ currency = channel_USD.currency_code+ price_info = VariantDiscountedPriceChange(+ variant_id=variant.id,+ channel_slug=channel_USD.slug,+ previous_price_amount=previous_price,+ new_price_amount=new_price,+ currency=currency,+ )++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=price_info,+ requestor=staff_user,+ )++ # then+ mocked_generate_deferred_payloads.assert_not_called()++ delivery = EventDelivery.objects.get(webhook=webhook)+ assert delivery.event_type == event_type+ payload = json.loads(delivery.payload.get_payload())+ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)+ assert payload["productVariant"]["id"] == graphene.Node.to_global_id(+ "ProductVariant", variant.pk+ )+ assert payload["productVariant"]["pricing"]["price"]["gross"]["amount"] == (+ variant_channel_listing.discounted_price_amount+ )+ assert payload["channel"]["slug"] == channel_USD.slug+ assert payload["previousPrice"] == {+ "amount": float(previous_price),+ "currency": currency,+ }+ assert payload["newPrice"] == {+ "amount": float(new_price),+ "currency": currency,+ }++ mocked_send_webhook_request_async.assert_called_once()+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk+++ ("event_type", "expected_allow_replica"),+ [+ (WebhookEventAsyncType.CHECKOUT_UPDATED, False),+ (WebhookEventAsyncType.CHECKOUT_FULLY_PAID, True),+ ],+)[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+ "saleor.webhook.transport.asynchronous.transport.initialize_request",+ wraps=initialize_request,+)+def test_call_trigger_webhook_async_immediate_webhook_reads_from_writer_on_deferrable_event(+ mocked_initialize_request,+ mocked_send_webhook_request_async,+ mocked_send_sync_webhook,+ event_type,+ expected_allow_replica,+ checkout_with_item,+ setup_checkout_webhooks,+ staff_user,+):+ # given+ checkout = checkout_with_item+ is_deferrable_event = WebhookEventAsyncType.EVENT_MAP[event_type].get(+ "is_deferred_payload", False+ )+ assert is_deferrable_event is not expected_allow_replica+ _, _, _, webhook = setup_checkout_webhooks(event_type)+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ webhooks = get_webhooks_for_event(event_type)+ mocked_send_sync_webhook.return_value = []++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=checkout,+ requestor=staff_user,+ allow_replica=True,+ )++ # then+ mocked_initialize_request.assert_called_once()+ call_kwargs = mocked_initialize_request.call_args.kwargs+ assert call_kwargs["allow_replica"] is expected_allow_replica+ assert call_kwargs["app"] == webhook.app+ delivery = EventDelivery.objects.get(webhook=webhook)+ assert delivery.event_type == event_type+ mocked_send_webhook_request_async.assert_called_once()++[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+def test_call_trigger_webhook_async_splits_deferred_and_immediate_webhooks(+ mocked_generate_deferred_payloads,+ mocked_send_webhook_request_async,+ mocked_send_sync_webhook,+ checkout_with_item,+ setup_checkout_webhooks,+ subscription_webhook,+ staff_user,+):+ # given+ checkout = checkout_with_item+ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED+ _, _, _, deferred_webhook = setup_checkout_webhooks(event_type)+ immediate_webhook = subscription_webhook(+ deferred_webhook.subscription_query, event_type, name="Immediate"+ )+ immediate_webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ immediate_webhook.save(update_fields=["payload_generation"])+ webhooks = get_webhooks_for_event(event_type)+ assert {webhook.pk for webhook in webhooks} == {+ deferred_webhook.pk,+ immediate_webhook.pk,+ }+ mocked_send_sync_webhook.return_value = []++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=checkout,+ requestor=staff_user,+ )++ # then+ deferred_delivery = EventDelivery.objects.get(webhook=deferred_webhook)+ assert deferred_delivery.payload is None+ mocked_generate_deferred_payloads.assert_called_once()+ deferred_call_kwargs = mocked_generate_deferred_payloads.call_args.kwargs+ assert deferred_call_kwargs["kwargs"]["event_delivery_ids"] == [+ deferred_delivery.pk+ ]++ immediate_delivery = EventDelivery.objects.get(webhook=immediate_webhook)+ immediate_payload = json.loads(immediate_delivery.payload.get_payload())+ assert immediate_payload["issuingPrincipal"]["id"] == graphene.Node.to_global_id(+ "User", staff_user.pk+ )+ assert set(immediate_payload["checkout"]) == {+ "shippingMethods",+ "shippingPrice",+ "totalPrice",+ }+ mocked_send_webhook_request_async.assert_called_once()+ send_call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert send_call_kwargs["kwargs"]["event_delivery_id"] == immediate_delivery.pk++[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+ "saleor.webhook.transport.asynchronous.transport.generate_deferred_payloads.apply_async"+)+def test_call_trigger_webhook_async_immediate_webhook_on_non_deferred_event(+ mocked_generate_deferred_payloads,+ mocked_send_webhook_request_async,+ mocked_send_sync_webhook,+ checkout_with_item,+ setup_checkout_webhooks,+ staff_user,+):+ # given+ checkout = checkout_with_item+ event_type = WebhookEventAsyncType.CHECKOUT_FULLY_PAID+ assert "is_deferred_payload" not in WebhookEventAsyncType.EVENT_MAP[event_type]+ _, _, _, webhook = setup_checkout_webhooks(event_type)+ webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ webhook.save(update_fields=["payload_generation"])+ webhooks = get_webhooks_for_event(event_type)+ mocked_send_sync_webhook.return_value = []++ # when+ trigger_webhooks_async(+ data=None,+ event_type=event_type,+ webhooks=webhooks,+ subscribable_object=checkout,+ requestor=staff_user,+ )++ # then+ mocked_generate_deferred_payloads.assert_not_called()+ delivery = EventDelivery.objects.get(webhook=webhook)+ payload = json.loads(delivery.payload.get_payload())+ assert payload["issuingPrincipal"]["id"] == graphene.Node.to_global_id(+ "User", staff_user.pk+ )+ assert set(payload["checkout"]) == {+ "shippingMethods",+ "shippingPrice",+ "totalPrice",+ }+ mocked_send_webhook_request_async.assert_called_once()+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk++[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")+ "saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"+)+def test_generate_deferred_payload_ignores_payload_generation_changed_after_trigger(+ mocked_send_webhook_request_async,+ mocked_send_sync_webhook,+ checkout_with_item,+ setup_checkout_webhooks,+ staff_user,+ fetch_kwargs,+):+ # given - a delivery created while the webhook was DEFERRED+ checkout = checkout_with_item+ fetch_checkout_data(**fetch_kwargs).get()+ deferred_request_time = datetime.datetime(2020, 10, 5, tzinfo=datetime.UTC)+ event_type = WebhookEventAsyncType.CHECKOUT_UPDATED+ _, _, _, checkout_updated_webhook = setup_checkout_webhooks(event_type)+ assert (+ checkout_updated_webhook.payload_generation == WebhookPayloadGeneration.DEFERRED+ )+ deferred_payload_data = DeferredPayloadData(+ model_name="checkout.checkout",+ object_id=checkout.pk,+ requestor_model_name="account.user",+ requestor_object_id=staff_user.pk,+ request_time=deferred_request_time,+ )+ delivery = EventDelivery.objects.create(+ event_type=event_type,+ webhook=checkout_updated_webhook,+ status=EventDeliveryStatus.PENDING,+ )+ mocked_send_sync_webhook.return_value = []++ # given - the webhook is switched to IMMEDIATE before the task runs+ checkout_updated_webhook.payload_generation = WebhookPayloadGeneration.IMMEDIATE+ checkout_updated_webhook.save(update_fields=["payload_generation"])++ # when+ generate_deferred_payloads.delay(+ event_delivery_ids=[delivery.pk],+ deferred_payload_data=asdict(deferred_payload_data),+ )++ # then - the delivery completes the way it started+ delivery.refresh_from_db()+ payload = json.loads(delivery.payload.get_payload())+ assert payload["issuedAt"] == deferred_request_time.isoformat()+ assert payload["issuingPrincipal"]["email"] == staff_user.email++ mocked_send_webhook_request_async.assert_called_once()+ call_kwargs = mocked_send_webhook_request_async.call_args.kwargs+ assert call_kwargs["kwargs"]["event_delivery_id"] == delivery.pk++@mock.patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")@mock.patch("saleor.webhook.transport.asynchronous.transport.send_webhook_request_async.apply_async"diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 9e12363fe8..ebb97e635a 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -27,6 +27,7 @@ from ....core.telemetry import ()from ....core.tracing import webhooks_otel_tracefrom ....core.utils import get_domain+from ....core.utils.events import get_is_deferred_payloadfrom ....core.utils.url import sanitize_url_for_loggingfrom ....graphql.webhook.subscription_payload import (generate_payload_promise_from_subscription,@@ -35,6 +36,7 @@ from ....graphql.webhook.subscription_payload import ()from ... import observabilityfrom ...event_types import WebhookEventAsyncType, WebhookEventSyncType+from ...models import WebhookPayloadGenerationfrom ...observability import WebhookDatafrom ..metrics import record_external_request, record_first_delivery_attempt_delayfrom ..utils import (@@ -299,6 +301,27 @@ def group_webhooks_by_subscription(return legacy, subscription+def group_subscription_webhooks_by_payload_generation(+ webhooks: Sequence["Webhook"],+) -> tuple[list["Webhook"], list["Webhook"]]:+ """Group subscription webhooks by their `payload_generation` setting.++ Returns a tuple of two lists: webhooks whose payload is built in the deferred+ task and webhooks whose payload is built immediately, in the request.+ """+ deferred = [+ webhook+ for webhook in webhooks+ if webhook.payload_generation == WebhookPayloadGeneration.DEFERRED+ ]+ immediate = [+ webhook+ for webhook in webhooks+ if webhook.payload_generation != WebhookPayloadGeneration.DEFERRED+ ]+ return deferred, immediate++@allow_writer()def create_event_delivery_list_for_webhooks(webhooks: Sequence["Webhook"],@@ -359,9 +382,7 @@ def trigger_webhooks_async_for_multiple_objects(legacy_webhooks, subscription_webhooks = group_webhooks_by_subscription(webhooks)- is_deferred_payload = WebhookEventAsyncType.EVENT_MAP.get(event_type, {}).get(- "is_deferred_payload", False- )+ is_deferrable_event = get_is_deferred_payload(event_type)# List of deliveries with payloads.deliveries: list[EventDelivery] = []@@ -401,24 +422,40 @@ def trigger_webhooks_async_for_multiple_objects(webhook_payload_data.subscribable_objectfor webhook_payload_data in webhook_payloads_data]- if is_deferred_payload:+ # A webhook's `payload_generation` is read here, once, when its deliveries+ # are created. Deliveries and tasks created earlier are not affected by a+ # later change of the setting.+ deferred_webhooks: list[Webhook] = []+ immediate_webhooks = subscription_webhooks+ if is_deferrable_event:+ deferred_webhooks, immediate_webhooks = (+ group_subscription_webhooks_by_payload_generation(subscription_webhooks)+ )+ if deferred_webhooks:deferred_deliveries_per_object = (create_deliveries_for_deferred_payload_subscriptions(event_type=event_type,subscribable_objects=subscribable_objects,- webhooks=subscription_webhooks,+ webhooks=deferred_webhooks,requestor=requestor,allow_replica=allow_replica,request_time=request_time,))- else:+ if immediate_webhooks:+ # A deferrable event can be fired by a task right after it wrote the+ # object on the writer, with a manager that allows the replica. The+ # deferred task waits for the replica to catch up before it resolves+ # the payload, but this path resolves it now, so the fields it loads+ # through dataloaders are read from the writer instead. Fields taken+ # from the subscribable object itself still reflect wherever the+ # caller loaded that object from.delivery_promise = create_deliveries_for_multiple_subscription_objects(event_type=event_type,subscribable_objects=subscribable_objects,- webhooks=subscription_webhooks,+ webhooks=immediate_webhooks,requestor=requestor,- allow_replica=allow_replica,+ allow_replica=allow_replica and not is_deferrable_event,pre_save_payloads=pre_save_payloads,request_time=request_time,)@@ -546,6 +583,12 @@ def generate_deferred_payloads(*,telemetry_context: TelemetryTaskContext,):+ """Build subscription payloads for deferred deliveries and send them.++ This task must not read the webhook's `payload_generation`. The deliveries it+ receives were created under the setting's value at trigger time, and a change+ made since must not alter how they complete.+ """if not event_delivery_ids:logger.warning("No event delivery IDs provided for deferred payload generation task."