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.

chore(subscriptions): delete rolling-deploy scaffolding after patched->deprecate_patch drain (#56004)

Vasco de Krijger9e5b2a5107dc
diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
index aed233c5a547..681bc1d783e3 100644
--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
@@ -1398,6 +1398,44 @@
LIMIT 21
'''
# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.39
+ '''
+ SELECT "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_organization"
+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid
+ LIMIT 21
+ '''
+# ---
# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.4
'''
SELECT "posthog_organization"."id",
diff --git a/posthog/temporal/subscriptions/activities.py b/posthog/temporal/subscriptions/activities.py
index 93521e57323c..3d19f5353784 100644
--- a/posthog/temporal/subscriptions/activities.py
+++ b/posthog/temporal/subscriptions/activities.py
@@ -57,61 +57,6 @@ LOGGER = get_logger(__name__)
NO_ASSETS_REASON = "No assets to deliver — likely a transient export pipeline failure; will retry on next schedule"
-async def _resolve_target_delivery_id(inputs: CreateExportAssetsInputs) -> uuid.UUID | None:
- """Find the SubscriptionDelivery row that create_export_assets should write to.
-
- Priority order:
- 1. `inputs.delivery_id` set by the steady-state workflow — use it directly.
- 2. Look up by the current activity's workflow_id (handles pre-rollout
- workflow retries that replay the old input shape without delivery_id).
- 3. None — standalone callers (tests, management commands) proceed without
- persisting the snapshot.
- """
- if inputs.delivery_id is not None:
- return inputs.delivery_id
-
- try:
- workflow_id = temporalio.activity.info().workflow_id
- except RuntimeError:
- # Not running inside a Temporal activity (e.g. unit test calling directly)
- return None
-
- @database_sync_to_async(thread_sensitive=False)
- def _lookup() -> tuple[uuid.UUID | None, int]:
- qs = SubscriptionDelivery.objects.filter(
- temporal_workflow_id=workflow_id,
- subscription_id=inputs.subscription_id,
- finished_at__isnull=True,
- ).order_by("-created_at")
- total = qs.count()
- row = qs.values_list("id", flat=True).first()
- return row, total
-
- row, total = await _lookup()
- if total > 1:
- # Multiple unfinished delivery rows for the same workflow_id is a
- # surprise invariant violation — surface it rather than silently picking
- # the newest. Could indicate a failed prior run or a workflow_id reuse.
- await LOGGER.awarning(
- "create_export_assets.workflow_id_lookup_ambiguous",
- subscription_id=inputs.subscription_id,
- workflow_id=workflow_id,
- match_count=total,
- picked=str(row) if row else None,
- )
- if row is None:
- # Inside an activity context and the fallback lookup found nothing —
- # this path should never fire in steady state (create_delivery_record
- # always runs first). Canary for a regression back to the old
- # shuttle-through-Temporal flow.
- await LOGGER.awarning(
- "create_export_assets.delivery_row_not_found",
- subscription_id=inputs.subscription_id,
- workflow_id=workflow_id,
- )
- return row
-
-
async def _persist_content_snapshot(
*,
delivery_id: uuid.UUID,
@@ -304,12 +249,9 @@ async def create_export_assets(inputs: CreateExportAssetsInputs) -> CreateExport
# Persist insight snapshots directly on SubscriptionDelivery.content_snapshot
# instead of returning them across the Temporal activity boundary — per-insight
# query_results can reach multi-MB and will trip Temporal's ~2 MiB payload cap.
- #
- # Resolve the target row. In the steady state the workflow passes delivery_id
- # directly. For pre-rollout workflow retries replaying the old input shape
- # (no delivery_id) and standalone callers, fall back to locating the row via
- # the activity's workflow_id so we don't silently drop the snapshot.
- target_delivery_id = await _resolve_target_delivery_id(inputs)
+ # Standalone callers (tests, management commands) that don't pass delivery_id
+ # skip the persist — they don't have a row to write to.
+ target_delivery_id = inputs.delivery_id
if target_delivery_id is not None:
snapshot_bytes = await _persist_content_snapshot(
delivery_id=target_delivery_id,
@@ -629,17 +571,6 @@ async def update_delivery_record(inputs: UpdateDeliveryRecordInputs) -> None:
if inputs.exported_asset_ids is not None:
delivery.exported_asset_ids = inputs.exported_asset_ids
update_fields.append("exported_asset_ids")
- if inputs.content_snapshot is not None:
- # 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:
delivery.recipient_results = inputs.recipient_results
update_fields.append("recipient_results")
diff --git a/posthog/temporal/subscriptions/types.py b/posthog/temporal/subscriptions/types.py
index dea4cfcff0a5..d4a7c37e912a 100644
--- a/posthog/temporal/subscriptions/types.py
+++ b/posthog/temporal/subscriptions/types.py
@@ -58,9 +58,8 @@ class CreateExportAssetsInputs:
previous_value: typing.Optional[str] = None
# When set, the activity persists the per-insight snapshot directly onto
# SubscriptionDelivery.content_snapshot. Keeps multi-MB query_results off
- # the Temporal payload wire (~2 MiB gRPC cap). When unset (standalone
- # callers or pre-rollout workflow retries replaying old input shape), the
- # activity falls back to looking up the delivery row by workflow_id.
+ # the Temporal payload wire (~2 MiB gRPC cap). Unset for standalone callers
+ # (tests, management commands) that have no delivery row to write to.
delivery_id: typing.Optional[uuid.UUID] = None
@@ -78,12 +77,6 @@ class CreateExportAssetsResult:
team_id: int = 0
distinct_id: str = ""
target_type: str = ""
- # Deprecated (TODO slug: subscriptions-patched-cleanup) — kept only so
- # that in-flight Temporal workflows (whose history contains an old-format
- # result) still deserialize on new workers during a rolling deploy. New
- # code does not populate this field. Remove in the second cleanup PR per
- # the sequence in workflows.py.
- insight_snapshots: typing.Optional[list[dict[str, typing.Any]]] = None
@dataclasses.dataclass
@@ -166,12 +159,9 @@ class CreateDeliveryRecordInputs:
class UpdateDeliveryRecordInputs:
"""Patch a SubscriptionDelivery row. None on optional collections means leave the column unchanged.
- New code writes per-insight query results directly to Postgres from
+ Per-insight query results are written to Postgres directly from
`create_export_assets` rather than shipping them back through this input
- (they can easily exceed Temporal's ~2 MiB payload cap). `content_snapshot`
- remains here only so that in-flight workflows from before the rollout can
- still replay successfully — their history carries a populated
- content_snapshot, and dropping the field would break deserialization.
+ (they can easily exceed Temporal's ~2 MiB payload cap).
"""
delivery_id: uuid.UUID
@@ -181,10 +171,6 @@ class UpdateDeliveryRecordInputs:
error: typing.Optional[dict[str, typing.Any]] = None
change_summary: typing.Optional[str] = None
finished: bool = False
- # Deprecated (TODO slug: subscriptions-patched-cleanup) — see docstring
- # above and cleanup sequence at top of workflows.py. Remove in the second
- # cleanup PR after task queue drain.
- content_snapshot: typing.Optional[dict[str, typing.Any]] = None
@dataclasses.dataclass
diff --git a/posthog/temporal/subscriptions/workflows.py b/posthog/temporal/subscriptions/workflows.py
index e654ca17e616..5a15a949f6da 100644
--- a/posthog/temporal/subscriptions/workflows.py
+++ b/posthog/temporal/subscriptions/workflows.py
@@ -46,36 +46,6 @@ from posthog.temporal.subscriptions.types import (
UpdateDeliveryRecordInputs,
)
-# Rolling-deploy deprecation bundle (TODO slug: subscriptions-patched-cleanup)
-# ---------------------------------------------------------------------------
-# 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.
-#
-# 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"
-
def _build_outcome_assets(
asset_ids: list[int],
@@ -255,12 +225,6 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
# onto SubscriptionDelivery.content_snapshot (written from within the
# activity to avoid shipping multi-MB query_results across Temporal's
# ~2 MiB payload boundary).
- #
- # Adding the new `delivery_id` input field is a safe, non-breaking
- # change per Temporal's schema evolution guidance — activity inputs
- # are not part of the workflow command state machine, so this does
- # not need a workflow.patched() gate (unlike the Phase 2.5 removal
- # below, which is a command-sequence change).
prepare_result = await temporalio.workflow.execute_activity(
create_export_assets,
CreateExportAssetsInputs(
@@ -320,18 +284,9 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):
f"{len(non_user_errors)} export(s) failed: {', '.join(distinct_classes)}",
)
- # 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 — persisted inline by
- # create_export_assets above (via delivery_id, or via the
- # workflow_id fallback lookup when replaying pre-rollout workflows).
+ # create_export_assets above via delivery_id.
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.py
index 6704d4fed85c..401695a0721c 100644
--- a/posthog/temporal/tests/test_subscriptions_workflows.py
+++ b/posthog/temporal/tests/test_subscriptions_workflows.py
@@ -981,12 +981,9 @@ async def test_create_delivery_record_persists_row_and_idempotency_key_dedupes(t
@freeze_time("2022-02-02T08:55:00.000Z")
@pytest.mark.asyncio
async def test_update_delivery_record_patches_status_and_results_without_touching_content(team, user):
- # When the new workflow calls update_delivery_record without content_snapshot
- # — which is the production path, since create_export_assets owns the
- # snapshot write — the delivery row's existing content_snapshot is preserved.
- # The field still exists on the dataclass for rolling-deploy replay compat
- # (old in-flight workflows may populate it), but it's no longer part of the
- # steady-state call path.
+ # update_delivery_record is the observability finalizer; create_export_assets
+ # owns the content_snapshot write. This pins that update_delivery_record does
+ # not touch the snapshot column — it only patches status/asset_ids/recipient_results.
insight = await sync_to_async(Insight.objects.create)(team=team, short_id="upd01", name="Update delivery")
subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)
@@ -1026,46 +1023,6 @@ async def test_update_delivery_record_patches_status_and_results_without_touchin
assert row.content_snapshot == initial_content_snapshot
assert row.finished_at is not None
- # 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"}]})
-
- 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"}]},
- ),
- )
-
- 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(
- delivery_id=delivery_id,
- status=DeliveryStatus.STARTING,
- content_snapshot={"total_insight_count": 2}, # no insights key
- ),
- )
- 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")
@pytest.mark.asyncio