: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
chore(subscriptions): swap patched() to deprecate_patch() for content_snapshot gate (#55986)
Vasco de Krijgeradca72c91a26
diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.pyindex d2dc5bd4fe03..93521e57323c 100644--- a/posthog/temporal/subscriptions/activities.py+++ b/posthog/temporal/subscriptions/activities.py@@ -630,11 +630,14 @@ async def update_delivery_record(inputs: UpdateDeliveryRecordInputs) -> None:delivery.exported_asset_ids = inputs.exported_asset_idsupdate_fields.append("exported_asset_ids")if inputs.content_snapshot is not None:- # Rolling-deploy compat: an in-flight pre-rollout workflow may still- # issue this call with a populated content_snapshot (from the old- # Phase 2.5 early-write). Merge so its insights aren't lost while the- # old workflow finishes draining. New workflows do not populate this- # field — the snapshot is written from inside create_export_assets.+ # Rolling-deploy compat (TODO slug: subscriptions-patched-cleanup):+ # an in-flight pre-rollout workflow may still issue this call with a+ # populated content_snapshot (from the old Phase 2.5 early-write).+ # DO NOT change to plain assignment — the shallow-merge here+ # preserves `id`, `short_id`, and other keys written by+ # `create_delivery_record` / `create_export_assets` that the legacy+ # replay payload does not include. New workflows do not populate+ # this field; the snapshot is written from inside create_export_assets.delivery.content_snapshot = {**(delivery.content_snapshot or {}), **inputs.content_snapshot}update_fields.append("content_snapshot")if inputs.recipient_results is not None:diff --git a/posthog/temporal/subscriptions/workflows.py b/posthog/temporal/subscriptions/workflows.pyindex 7fffaad299fb..e654ca17e616 100644--- a/posthog/temporal/subscriptions/workflows.py+++ b/posthog/temporal/subscriptions/workflows.py@@ -1,6 +1,5 @@import jsonimport uuid-import typingimport asyncioimport datetime as dtimport dataclasses@@ -34,7 +33,6 @@ from posthog.temporal.subscriptions.snapshot_activities import snapshot_subscripfrom posthog.temporal.subscriptions.types import (CreateDeliveryRecordInputs,CreateExportAssetsInputs,- CreateExportAssetsResult,DeliverSubscriptionInputs,DeliverSubscriptionResult,DeliveryStatus,@@ -50,79 +48,35 @@ from posthog.temporal.subscriptions.types import (# Rolling-deploy deprecation bundle (TODO slug: subscriptions-patched-cleanup)# ----------------------------------------------------------------------------# The items below exist ONLY to keep pre-rollout workflows replayable on new-# workers during a rolling deploy. They must be removed together, in two-# follow-up PRs, once the subscriptions task queue has drained past the oldest-# in-flight pre-patch workflow (workflow execution_timeout is 2h; wait ≥24h-# after deploy to be safe).+# Step 1 of the two-step `patched()` -> `deprecate_patch()` -> deletion dance.+# `workflow.deprecate_patch()` records a "deprecated" marker at the same+# command-sequence position the original `workflow.patched()` guard occupied,+# so workflows whose history already carries the `patched` marker replay+# cleanly. The if-gate and legacy-replay helper are gone because pre-rollout+# workflows (no marker in history) have drained by deploy time of this PR.#-# Grep for `subscriptions-patched-cleanup` to find every site. The removal-# sequence matters — deleting `patched()` directly breaks replay of any-# workflow whose history already recorded the marker:-# 1. First cleanup PR: replace `workflow.patched(...)` with-# `workflow.deprecate_patch(...)` (same runtime behavior; records a-# "deprecated" marker instead).-# 2. Second cleanup PR (after another full drain): delete-# `_reissue_phase_2_5_update_for_replay`, `_PATCH_ID_CONTENT_SNAPSHOT_DIRECT_WRITE`,-# `CreateExportAssetsResult.insight_snapshots`, and-# `UpdateDeliveryRecordInputs.content_snapshot`.+# Deploy-ordering precondition: `ProcessSubscriptionWorkflow.execution_timeout`+# is 2h, so in theory any pre-rollout workflow completes 2h after #55943 deploys.+# In practice, wait ≥24h after #55943's prod deploy before merging this PR —+# the same buffer the predecessor comment prescribed. The same rule applies+# from this PR's deploy to the step-2 cleanup below.+#+# The binding condition is "no workflow whose history was recorded pre-#55943+# is still replayable" — continue-as-new chains and long signaled workflows+# can outlive execution_timeout. Verify before merging each step by running:+# Temporal UI → WorkflowType="process-subscription" ExecutionStatus=Running+# StartTime <= <preceding-PR-prod-deploy-timestamp>+# and confirming zero results.+#+# Grep `subscriptions-patched-cleanup` to find every site. Step 2 (after+# another ≥24h drain past this deploy) deletes: the `deprecate_patch()` call,+# `_PATCH_ID_CONTENT_SNAPSHOT_DIRECT_WRITE`,+# `CreateExportAssetsResult.insight_snapshots`,+# `UpdateDeliveryRecordInputs.content_snapshot`, and the shallow-merge branch+# in `update_delivery_record` that the deprecated field fed._PATCH_ID_CONTENT_SNAPSHOT_DIRECT_WRITE = "subscriptions-content-snapshot-direct-write"-async def _reissue_phase_2_5_update_for_replay(- *,- delivery_id: uuid.UUID,- prepare_result: CreateExportAssetsResult,- delivery_exported_asset_ids: list[int],- subscription_id: int,-) -> None:- """DO NOT MODIFY — must match the pre-rollout command shape exactly.-- Re-issues the old Phase 2.5 `update_delivery_record` command so pre-rollout- workflows replay deterministically on new workers. Any change to the- command's activity name, input type, or issued-or-not decision breaks- replay for every in-flight pre-patch workflow and leaves them stuck.-- Correctness argument: the reconstructed content_snapshot only includes- `insights` when the activity actually returned them (pre-patch history).- When the new activity ran (insight_snapshots=None), it already persisted- the snapshot to Postgres directly, so we omit that key to avoid the- shallow-merge in `update_delivery_record` overwriting the in-activity- write. `total_insight_count` is always included and always computed the- same way on both code paths, so overwriting it is benign.-- Part of the `subscriptions-patched-cleanup` deprecation bundle — see the- top-of-file comment for the two-step removal sequence.- """- legacy_content_snapshot: dict[str, typing.Any] = {- "total_insight_count": prepare_result.total_insight_count,- }- if prepare_result.insight_snapshots is not None:- legacy_content_snapshot["insights"] = prepare_result.insight_snapshots-- try:- await temporalio.workflow.execute_activity(- update_delivery_record,- UpdateDeliveryRecordInputs(- delivery_id=delivery_id,- status=DeliveryStatus.STARTING,- exported_asset_ids=delivery_exported_asset_ids or None,- content_snapshot=legacy_content_snapshot,- ),- start_to_close_timeout=dt.timedelta(minutes=1),- retry_policy=temporalio.common.RetryPolicy(- initial_interval=dt.timedelta(seconds=5),- maximum_interval=dt.timedelta(seconds=30),- maximum_attempts=3,- ),- )- except Exception:- temporalio.workflow.logger.warning(- "process_subscription.content_snapshot_persist_failed",- extra={"subscription_id": subscription_id},- )--def _build_outcome_assets(asset_ids: list[int],export_results: list[ExportAssetResult | BaseException],@@ -366,27 +320,18 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):f"{len(non_user_errors)} export(s) failed: {', '.join(distinct_classes)}",)- # Rolling-deploy compat: re-issue the old Phase 2.5 command for- # in-flight pre-patch workflows so their replay stays deterministic.- # Post-patch workflows skip this entirely — the content_snapshot is- # already in Postgres via create_export_assets writing directly.- # `patched()` returns False on replay of a pre-rollout workflow's- # history (no marker recorded) and True on any workflow that first- # ran on new code. Inverted from the canonical pattern: we only- # execute the legacy replay on the False branch.- if not temporalio.workflow.patched(_PATCH_ID_CONTENT_SNAPSHOT_DIRECT_WRITE):- if delivery_id is not None:- await _reissue_phase_2_5_update_for_replay(- delivery_id=delivery_id,- prepare_result=prepare_result,- delivery_exported_asset_ids=delivery_exported_asset_ids,- subscription_id=inputs.subscription_id,- )+ # Phase 2.5 (legacy) — deprecated. The pre-rollout `update_delivery_record`+ # command at this position has drained; `deprecate_patch()` records a+ # "deprecated" marker so any straggler replay from the original deploy+ # reaches this point without tripping non-determinism. Next cleanup PR+ # removes the call once the "deprecated"-marker histories have drained+ # (verify via the Temporal UI query in the top-of-file comment block).+ temporalio.workflow.deprecate_patch(_PATCH_ID_CONTENT_SNAPSHOT_DIRECT_WRITE)# Generate LLM change summary (best-effort, skip if not enabled).- # Reads content_snapshot back from Postgres — it was persisted- # inline by create_export_assets above, or by the legacy-replay- # helper on pre-patch workflows.+ # Reads content_snapshot back from Postgres — persisted inline by+ # create_export_assets above (via delivery_id, or via the+ # workflow_id fallback lookup when replaying pre-rollout workflows).if delivery_id is not None:try:snapshot_result = await temporalio.workflow.execute_activity(diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 5fa860f8eb8b..b583592f4e8c 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -1,6 +1,4 @@-import jsonimport uuid-import dataclassesfrom collections.abc import Callable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime@@ -44,7 +42,6 @@ from posthog.temporal.subscriptions.activities import (from posthog.temporal.subscriptions.types import (CreateDeliveryRecordInputs,CreateExportAssetsInputs,- CreateExportAssetsResult,DeliverSubscriptionInputs,DeliveryStatus,FetchDueSubscriptionsActivityInputs,@@ -1013,65 +1010,34 @@ async def test_update_delivery_record_patches_status_and_results_without_touchinassert row.content_snapshot == initial_content_snapshotassert row.finished_at is not None--@freeze_time("2022-02-02T08:55:00.000Z")-async def test_update_delivery_record_merges_content_snapshot_for_legacy_replay(team, user):- # Rolling-deploy compat path: when a pre-patch workflow replays Phase 2.5- # on a new worker, it re-issues update_delivery_record with a populated- # content_snapshot. The activity must shallow-merge so that earlier keys- # (e.g. dashboard metadata written by create_delivery_record, or insights- # already written to Postgres by the new create_export_assets activity)- # are preserved, not overwritten, when the replayed payload only covers a- # subset of keys.- insight = await sync_to_async(Insight.objects.create)(team=team, short_id="lgcy01", name="Legacy replay")- subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)-- env = ActivityEnvironment()- delivery_id = await env.run(- create_delivery_record,- CreateDeliveryRecordInputs(- subscription_id=subscription.id,- team_id=team.id,- trigger_type=SubscriptionTriggerType.MANUAL,- temporal_workflow_id="wf-lgcy",- idempotency_key="idem-lgcy",- scheduled_at=None,- ),- )-- # Simulate "create_export_assets already wrote insights to DB" — this is- # the state on a pre-patch workflow retry where the new activity persisted- # the snapshot before the workflow reaches the legacy Phase 2.5 replay.+ # Rolling-deploy compat: the shallow-merge branch in update_delivery_record+ # is still live for any pre-rollout workflow whose replay re-issues the old+ # Phase 2.5 update_delivery_record command with a populated content_snapshot.+ # Pin the merge semantics here (partial input preserves pre-existing keys,+ # overwrites overlapping keys) until the content_snapshot field is removed+ # in the subscriptions-patched-cleanup step-2 PR.await sync_to_async(SubscriptionDelivery.objects.filter(pk=delivery_id).update,)(content_snapshot={"id": 1, "short_id": "abc", "insights": [{"id": 99, "name": "inline-write"}]})- # Legacy replay with insights set should overwrite the insights key but- # preserve id/short_id set by create_delivery_record.await env.run(update_delivery_record,UpdateDeliveryRecordInputs(delivery_id=delivery_id,status=DeliveryStatus.STARTING,- content_snapshot={- "total_insight_count": 1,- "insights": [{"id": 99, "name": "replayed-insights"}],- },+ content_snapshot={"total_insight_count": 1, "insights": [{"id": 99, "name": "replayed"}]},),)- row = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery_id)- # Top-level merge preserved id/short_id from the pre-existing content_snapshot.- assert row.content_snapshot["id"] == 1- assert row.content_snapshot["short_id"] == "abc"- # Replay's keys took precedence for the keys it included.- assert row.content_snapshot["total_insight_count"] == 1- assert row.content_snapshot["insights"] == [{"id": 99, "name": "replayed-insights"}]-- # Legacy replay without the `insights` key (new activity returned- # insight_snapshots=None) must NOT wipe the insights already persisted by- # the new activity.+ merged = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery_id)+ assert merged.content_snapshot["id"] == 1 # preserved+ assert merged.content_snapshot["short_id"] == "abc" # preserved+ assert merged.content_snapshot["total_insight_count"] == 1 # added+ assert merged.content_snapshot["insights"] == [{"id": 99, "name": "replayed"}] # overwritten++ # Second replay whose payload omits `insights` must NOT wipe the key — a+ # plain-assignment regression would clobber it, which is the failure mode+ # the DO-NOT-change comment warns against.await env.run(update_delivery_record,UpdateDeliveryRecordInputs(@@ -1080,12 +1046,9 @@ async def test_update_delivery_record_merges_content_snapshot_for_legacy_replay(content_snapshot={"total_insight_count": 2}, # no insights key),)-- row = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery_id)- # insights from the previous replay are preserved.- assert row.content_snapshot["insights"] == [{"id": 99, "name": "replayed-insights"}]- # total_insight_count was updated.- assert row.content_snapshot["total_insight_count"] == 2+ merged2 = await sync_to_async(SubscriptionDelivery.objects.get)(pk=delivery_id)+ assert merged2.content_snapshot["insights"] == [{"id": 99, "name": "replayed"}] # preserved+ assert merged2.content_snapshot["total_insight_count"] == 2 # updated@freeze_time("2022-02-02T08:55:00.000Z")@@ -1769,50 +1732,6 @@ async def test_partial_export_failure_delivers_successful_assets(assert props["asset_errors"] == []-def test_create_export_assets_result_fields_stable_reminder():- # Reminder-style guard: fails if a field is added to CreateExportAssetsResult- # without the author noticing. Temporal activity payloads are capped at- # ~2 MiB (TMPRL1103), so any new field must be size-bounded by construction- # — primitives, IDs, short strings, or small lists of primitives. Multi-MB- # data must be persisted from inside the activity (e.g. SubscriptionDelivery- # .content_snapshot via Postgres), not returned.- #- # Only the field name set is checked here — the test can't catch field- # *type* bloat (e.g. someone changing `target_type: str` to- # `target_type: dict[str, Any]`). That risk is caught at review time by the- # AGENTS.md rule on activity payload size.- small_metadata_fields = {- "exported_asset_ids",- "total_insight_count",- "team_id",- "distinct_id",- "target_type",- }- # Kept on the dataclass for rolling-deploy replay compatibility. New code- # does not populate them. Remove from this set when the fields are removed- # from types.py (after the subscriptions task queue has drained).- deprecated_fields = {"insight_snapshots"}- expected_fields = small_metadata_fields | deprecated_fields- actual_fields = {f.name for f in dataclasses.fields(CreateExportAssetsResult)}- assert actual_fields == expected_fields, (- f"CreateExportAssetsResult fields changed: added={actual_fields - expected_fields}, "- f"removed={expected_fields - actual_fields}. If adding a field, confirm it is "- f"size-bounded — Temporal activity payloads are capped at ~2 MiB (TMPRL1103). "- f"Persist multi-MB data from within the activity rather than returning it."- )-- # Byte-ceiling sanity check: an empty result instance with default values- # stays well under any plausible payload concern. Catches accidental large- # defaults on new fields (e.g. a mutable default factory that pulls data).- empty = CreateExportAssetsResult(exported_asset_ids=[], total_insight_count=0)-- encoded_size = len(json.dumps(dataclasses.asdict(empty), default=str).encode("utf-8"))- assert encoded_size < 1024, (- f"Empty CreateExportAssetsResult serialized to {encoded_size} bytes — larger than expected. "- f"New fields should not carry non-trivial default values."- )--@patch("posthog.temporal.exports.activities.exporter")@patch("posthog.slo.events.posthoganalytics")@patch("ee.tasks.subscriptions.get_metric_meter")