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(subscriptions): don't refire delivery on schedule-only edits (#66787)

Vasco de Krijgerb7f6a05bd83a
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index cb7faf2a2eea..c4104f95c925 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -128,6 +128,15 @@ class DashboardExportInsightsField(serializers.Field):
class SubscriptionSerializer(serializers.ModelSerializer):
"""Standard Subscription serializer."""
+ FIELDS_THAT_TRIGGER_REDELIVERY: ClassVar[tuple[str, ...]] = (
+ "target_value",
+ "target_type",
+ "integration_id",
+ "prompt",
+ "insight_id",
+ "dashboard_id",
+ )
+
created_by = UserBasicSerializer(read_only=True)
summary = serializers.CharField(read_only=True, help_text="Human-readable schedule summary, e.g. 'sent daily'.")
invite_message = serializers.CharField(
@@ -515,6 +524,29 @@ class SubscriptionSerializer(serializers.ModelSerializer):
# Telemetry must never poison the validation path.
pass
+ def _capture_update_delivery_decision(
+ self, instance: Subscription, *, delivery_triggered: bool, re_enabled: bool
+ ) -> None:
+ try:
+ posthoganalytics.capture(
+ distinct_id=self._caller_distinct_id(),
+ event="subscription_update_delivery_decision",
+ properties={
+ "subscription_id": instance.id,
+ "team_id": instance.team_id,
+ "resource_type": instance.resource_type,
+ "target_type": instance.target_type,
+ "delivery_triggered": delivery_triggered,
+ "reason": "re_enabled"
+ if re_enabled
+ else ("delivery_field_changed" if delivery_triggered else "no_delivery_relevant_change"),
+ },
+ groups=groups(None, instance.team),
+ )
+ except Exception as e:
+ # Telemetry must never block the update.
+ capture_exception(e)
+
def _evaluate_feature_flag(self, flag_key: str) -> bool:
"""Evaluate a feature flag for the caller's organization.
@@ -680,9 +712,21 @@ class SubscriptionSerializer(serializers.ModelSerializer):
was_disabled = instance.enabled is False
is_delete = not instance.deleted and validated_data.get("deleted") is True
invite_message = validated_data.pop("invite_message", "")
+ # Track payload PRESENCE, not truthiness: an empty list (clearing all exports) is delivery-relevant
+ # too, so `bool(ids)` would miss it. Pop loses presence, so capture it first.
+ export_insights_in_payload = "dashboard_export_insights" in validated_data
dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])
analytics_props = get_request_analytics_properties(request)
+ # Snapshot delivery-relevant scalar values before the write so we can tell, after,
+ # whether the edit actually changed what gets delivered. Only snapshot the
+ # dashboard_export_insights M2M when the payload carries it — that's the only case
+ # `.set()` can mutate the relation, so a schedule/meta-only edit pays no M2M query.
+ old_delivery_values = {field: getattr(instance, field) for field in self.FIELDS_THAT_TRIGGER_REDELIVERY}
+ old_export_insight_ids = (
+ set(instance.dashboard_export_insights.values_list("id", flat=True)) if export_insights_in_payload else None
+ )
+
if is_delete:
with slo_operation(
spec=SloSpec(
@@ -708,24 +752,45 @@ class SubscriptionSerializer(serializers.ModelSerializer):
instance = super().update(instance, validated_data)
_invalidate_summary_quota_cache(instance.team.organization_id)
- if dashboard_export_insight_ids:
+ # Apply the M2M whenever the field is in the payload — including an empty list, which clears it.
+ if export_insights_in_payload:
instance.dashboard_export_insights.set(dashboard_export_insight_ids)
+ is_re_enabling = was_disabled and instance.enabled
+
# Re-enabling clears the stale next_delivery_date that was frozen while
# disabled. Without this, the scheduler picks the sub up on its next tick
# (the past date matches `next_delivery_date__lte=now`) and fires a second
# SCHEDULED delivery right after the immediate TARGET_CHANGE confirmation.
- if was_disabled and instance.enabled:
+ if is_re_enabling:
instance.set_next_delivery_date()
instance.save(update_fields=["next_delivery_date"])
# Skip the workflow trigger when the resulting state is disabled. No delivery
# should fire for a disabled subscription regardless of whether it was just
- # disabled or already disabled. Re-enabling (`enabled: false → true`) DOES
- # trigger the workflow so the user gets immediate confirmation delivery.
+ # disabled or already disabled.
if not instance.enabled:
return instance
+ # Only fire the immediate confirmation delivery when the edit changed *what*
+ # gets delivered, or when re-enabling (`enabled: false → true`) — the user
+ # expects a confirmation delivery in both cases. A schedule/meta-only edit
+ # (frequency, interval, title, summary_*, …) re-saves next_delivery_date via
+ # the model's save() but must not push a fresh delivery.
+ delivery_target_changed = any(
+ getattr(instance, field) != old_value for field, old_value in old_delivery_values.items()
+ ) or (old_export_insight_ids is not None and set(dashboard_export_insight_ids) != old_export_insight_ids)
+
+ # The "<kind> subscription updated" event fires from the post_save signal before this decision is
+ # made, so it can't tell an edit that fired a confirmation from one that intentionally skipped.
+ # Emit the decision explicitly so a regression that silently suppressed deliveries stays observable.
+ delivery_triggered = is_re_enabling or delivery_target_changed
+ self._capture_update_delivery_decision(
+ instance, delivery_triggered=delivery_triggered, re_enabled=is_re_enabling
+ )
+ if not delivery_triggered:
+ return instance
+
temporal = sync_connect()
workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"
asyncio.run(
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index fb55eeea00c8..6f0cd9a09d96 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from typing import Optional
from uuid import uuid4
@@ -206,6 +207,168 @@ class TestSubscriptionTemporal(APILicensedTest):
assert activity_inputs.previous_value == "[email protected]"
assert activity_inputs.invite_message == "hi new user"
+ # Each setup builds a subscription and returns (sub_id, patch_payload) for the parameterized
+ # delivery test below. Cases vary only in fixtures and payload; the fire/no-fire assertion is shared.
+ # Reusable builders for the inline case factories below. Anything a lambda can't express (multi-row
+ # ORM setup, the verbose dashboard POST, tile side effects) lives here; the per-case payload stays inline.
+ def _basic_sub(self) -> int:
+ return self._create_subscription(invite_message=None).json()["id"]
+
+ def _disabled_email_sub(self) -> int:
+ return Subscription.objects.create(
+ team=self.team,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="daily",
+ start_date=timezone.now(),
+ insight=self.insight,
+ title="t",
+ enabled=False,
+ ).id
+
+ def _dashboard_sub(self, tile_insights: list[Insight], export_insights: list[Insight]) -> int:
+ # Dashboard subscriptions can only export insights that are dashboard tiles, so add a tile per
+ # insight before posting. export_insights is the initial selection a case then patches.
+ for insight in tile_insights:
+ self.dashboard.tiles.create(insight=insight)
+ return self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ {
+ "dashboard": self.dashboard.id,
+ "dashboard_export_insights": [insight.id for insight in export_insights],
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": "2022-01-01T00:00:00",
+ "title": "Dash",
+ },
+ ).json()["id"]
+
+ # Each case is (name, build, should_fire, expected_reason); build(test) -> (sub_id, patch_payload).
+ # The inline factory keeps each case's setup next to its expected outcome.
+ @parameterized.expand(
+ [
+ # Schedule/meta-only edits must NOT re-fire a delivery.
+ ("frequency", lambda t: (t._basic_sub(), {"frequency": "daily"}), False, "no_delivery_relevant_change"),
+ ("interval", lambda t: (t._basic_sub(), {"interval": 3}), False, "no_delivery_relevant_change"),
+ ("title", lambda t: (t._basic_sub(), {"title": "Renamed"}), False, "no_delivery_relevant_change"),
+ # Delivery-relevant edits MUST fire a confirmation — what (or where) gets delivered changed,
+ # or the subscription was re-enabled.
+ (
+ "target_value",
+ lambda t: (t._basic_sub(), {"target_value": "[email protected],[email protected]"}),
+ True,
+ "delivery_field_changed",
+ ),
+ (
+ "target_type", # switching channel routes delivery elsewhere — needs a Slack integration
+ lambda t: (
+ t._basic_sub(),
+ {
+ "target_type": "slack",
+ "target_value": "#general",
+ "integration_id": Integration.objects.create(team=t.team, kind="slack", config={}).id,
+ },
+ ),
+ True,
+ "delivery_field_changed",
+ ),
+ ("re_enable", lambda t: (t._disabled_email_sub(), {"enabled": True}), True, "re_enabled"),
+ (
+ "integration_swap", # Slack routing depends on the workspace, not just target_value
+ lambda t: (
+ Subscription.objects.create(
+ team=t.team,
+ target_type="slack",
+ target_value="#general",
+ integration=Integration.objects.create(team=t.team, kind="slack", config={}),
+ frequency="daily",
+ start_date=timezone.now(),
+ insight=t.insight,
+ title="t",
+ ).id,
+ {"integration_id": Integration.objects.create(team=t.team, kind="slack", config={}).id},
+ ),
+ True,
+ "delivery_field_changed",
+ ),
+ (
+ "dashboard_export_change", # changing the exported insight set hits the M2M branch
+ lambda t: (
+ t._dashboard_sub(
+ [t.insight, (other := Insight.objects.create(team=t.team, name="other"))],
+ [t.insight],
+ ),
+ {"dashboard_export_insights": [t.insight.id, other.id]},
+ ),
+ True,
+ "delivery_field_changed",
+ ),
+ # ...except re-submitting the identical export set, which changes nothing.
+ (
+ "dashboard_export_resubmit_same",
+ lambda t: (
+ t._dashboard_sub([t.insight], [t.insight]),
+ {"dashboard_export_insights": [t.insight.id], "title": "Renamed"},
+ ),
+ False,
+ "no_delivery_relevant_change",
+ ),
+ ]
+ )
+ def test_update_fires_delivery_only_when_delivery_relevant_field_changes(
+ self,
+ _name: str,
+ build: Callable[["TestSubscriptionTemporal"], tuple[int, dict]],
+ should_fire: bool,
+ expected_reason: str,
+ ):
+ sub_id, patch_payload = build(self)
+ self.mock_temporal_client.start_workflow.reset_mock()
+
+ with patch("ee.api.subscription.posthoganalytics.capture") as mock_capture:
+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", patch_payload)
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ # The workflow fires only when the edit warrants a confirmation delivery...
+ if should_fire:
+ self.mock_temporal_client.start_workflow.assert_called_once()
+ else:
+ self.mock_temporal_client.start_workflow.assert_not_called()
+
+ # ...and the decision is always emitted so a silent suppression is observable — the post_save
+ # "<kind> subscription updated" event fires pre-decision and can't carry this signal.
+ decision_calls = [
+ call
+ for call in mock_capture.call_args_list
+ if call.kwargs.get("event") == "subscription_update_delivery_decision"
+ ]
+ assert len(decision_calls) == 1
+ properties = decision_calls[0].kwargs["properties"]
+ assert properties["delivery_triggered"] is should_fire
+ assert properties["reason"] == expected_reason
+
+ def test_schedule_only_update_still_recomputes_next_delivery_date(self):
+ # A schedule edit must not fire a delivery but MUST still reschedule — the model
+ # save() recomputes next_delivery_date; this guards that the no-fire short-circuit
+ # doesn't accidentally skip the reschedule.
+ sub_id = self._create_subscription(invite_message=None, frequency="weekly").json()["id"]
+ before = Subscription.objects.get(id=sub_id).next_delivery_date
+ self.mock_temporal_client.start_workflow.reset_mock()
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"frequency": "daily"},
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+ self.mock_temporal_client.start_workflow.assert_not_called()
+ after = Subscription.objects.get(id=sub_id).next_delivery_date
+ # Daily cadence brings the next delivery strictly earlier than the weekly one.
+ assert before is not None
+ assert after is not None
+ assert after < before
+
def test_can_create_dashboard_subscription_with_dashboard_export_insights(self):
self.dashboard.tiles.create(insight=self.insight)
response = self.client.post(
@@ -1515,9 +1678,11 @@ class TestSubscriptionTemporal(APILicensedTest):
@parameterized.expand(
[
- # Locks the workflow-trigger matrix across all four (initial, final) enabled states.
- ("enabled_to_enabled_field_edit", True, {"title": "renamed"}, True),
- ("redundant_enable", True, {"enabled": True}, True),
+ # The confirmation-delivery workflow fires only on a re-enable or a delivery-relevant change —
+ # not on a meta-only edit (title) or a redundant enable that changes nothing. (This narrows the
+ # previous "every edit to an enabled sub fires" matrix; see FIELDS_THAT_TRIGGER_REDELIVERY.)
+ ("enabled_to_enabled_field_edit", True, {"title": "renamed"}, False),
+ ("redundant_enable", True, {"enabled": True}, False),
("disable_enabled", True, {"enabled": False}, False),
("redundant_disable", False, {"enabled": False}, False),
("enable_disabled", False, {"enabled": True}, True),
@@ -2476,12 +2641,13 @@ class TestAISubscriptionAPI(APILicensedTest):
def test_can_update_ai_subscription_prompt(self, mock_is_cloud, mock_flag, mock_sync):
self._enable_ai()
- self._mock_temporal(mock_sync)
+ mock_client = self._mock_temporal(mock_sync)
create_resp = self.client.post(
f"/api/projects/{self.team.id}/subscriptions",
self._make_ai_payload(),
)
sub_id = create_resp.json()["id"]
+ mock_client.start_workflow.reset_mock()
update_resp = self.client.patch(
f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
@@ -2489,6 +2655,9 @@ class TestAISubscriptionAPI(APILicensedTest):
)
assert update_resp.status_code == status.HTTP_200_OK, update_resp.json()
assert update_resp.json()["prompt"] == "Show me new error events"
+ # prompt is delivery-relevant for AI subscriptions; editing it must re-fire the
+ # confirmation delivery so recipients see the updated report.
+ mock_client.start_workflow.assert_called_once()
def test_resource_type_is_derived_and_read_only(self, mock_is_cloud, mock_flag, mock_sync):
# resource_type is derived from the populated target and read-only — a client can
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 8c95e64f66ec..b6999ebdabac 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -396,6 +396,10 @@ field_exclusions: dict[AuditableScope, list[str]] = {
# Scheduler-derived field; keep it out of user-facing change diffs even when another
# field changes in the same save (signal_exclusions only governs whether the signal fires).
"next_delivery_date",
+ # FK to a connected Slack integration. The generic field-diff captures the related object,
+ # which isn't JSON-serializable for the change detail (same reason FeatureFlag/Experiment
+ # exclude their FK relations) — without this, editing a subscription's integration 500s the save.
+ "integration",
],
"Cohort": [
"version",