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.

feat(growth): add a job that creates custom product push campaigns (#90597)

Rafael Audibert71cc1a21d103
diff --git a/posthog/dags/locations/growth.py b/posthog/dags/locations/growth.py
index 5567752d08fc..9748f9c0c647 100644
--- a/posthog/dags/locations/growth.py
+++ b/posthog/dags/locations/growth.py
@@ -2,6 +2,7 @@ import dagster
from products.growth.dags import (
ai_enrichment,
+ custom_product_push_campaigns,
github_sdk_versions,
identity_matching,
oauth,
@@ -22,6 +23,8 @@ jobs = [
user_product_list.sync_cross_sell_products_monthly_job,
team_production_event_activation.detect_first_team_production_event_job,
product_push_campaigns.product_push_campaigns_job,
+ # Manual-run only: growth names the organizations, product, and window per run.
+ custom_product_push_campaigns.custom_product_push_campaigns_job,
]
schedules = [
oauth.oauth_clear_expired_oauth_tokens_schedule,
diff --git a/products/growth/backend/product_push/service.py b/products/growth/backend/product_push/service.py
index 03314988b4ac..692212f73b7e 100644
--- a/products/growth/backend/product_push/service.py
+++ b/products/growth/backend/product_push/service.py
@@ -8,13 +8,14 @@ intent metric.
"""
from dataclasses import dataclass
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from django.db import IntegrityError, transaction
-from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.db.models import Exists, Max, OuterRef, Q, QuerySet
import structlog
+from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models.organization import Organization
@@ -28,6 +29,7 @@ from products.growth.backend.product_push.cadence import (
campaign_ends_at,
is_cooldown_over,
is_grace_period_over,
+ is_retry_eligible,
)
from products.growth.backend.product_push.selection import Selection, select_next_product
@@ -37,6 +39,12 @@ logger = structlog.get_logger(__name__)
# cadence of `calculate_product_activation`'s debounce.
ACTIVATION_RECHECK_STALENESS = timedelta(days=1)
+# What a custom product push campaign does when the organization is already running one.
+ON_ACTIVE_SKIP = "skip"
+ON_ACTIVE_QUEUE = "queue"
+ON_ACTIVE_OVERRIDE = "override"
+ON_ACTIVE_POLICIES = (ON_ACTIVE_SKIP, ON_ACTIVE_QUEUE, ON_ACTIVE_OVERRIDE)
+
@dataclass(frozen=True)
class AdoptionResult:
@@ -51,12 +59,28 @@ class CloseBatchResult:
skipped: int = 0
-@dataclass(kw_only=True)
+@frozen(frozen=False) # counters accumulate while the batch is processed
+class CustomProductPushBatchResult:
+ orgs_processed: int = 0
+ created: int = 0
+ queued_behind_active: int = 0
+ overrode_active: int = 0
+ blocked_by_active: int = 0
+ window_unreachable: int = 0
+ already_pending: int = 0
+ already_adopted: int = 0
+ in_retry_cooldown: int = 0
+ conflicts: int = 0
+ would_create: int = 0 # dry-run only
+
+
+@frozen(frozen=False) # counters accumulate while the batch is processed
class StartBatchResult:
orgs_processed: int = 0
started: int = 0
no_candidate: int = 0
not_eligible: int = 0
+ expired: int = 0
conflicts: int = 0
would_start: int = 0 # dry-run only
@@ -214,6 +238,18 @@ def start_campaigns_for_org_batch(
result.not_eligible += 1
continue
+ # Last resort for a campaign whose window ran out before it could start.
+ # Creation refuses the cases it can predict, but not what happens afterwards:
+ # the org can pick up an automatic campaign, another pin can jump the queue,
+ # or this sweep can be paused for a stretch. Retire the campaign rather than
+ # show a push whose window has passed.
+ scheduled = selection.scheduled_campaign
+ if scheduled is not None and scheduled.ends_at is not None and now >= scheduled.ends_at:
+ if not dry_run:
+ cancel_campaigns([str(scheduled.id)], now)
+ result.expired += 1
+ continue
+
if dry_run:
result.would_start += 1
logger.info(
@@ -243,6 +279,155 @@ def start_campaigns_for_org_batch(
return result
+def create_custom_product_push_campaigns_for_org_batch(
+ organization_ids: list[str],
+ product_key: str,
+ now: datetime,
+ *,
+ starts_on: date,
+ ends_at: datetime,
+ on_active_campaign: str,
+ reason_text: str | None = None,
+ skip_recently_pushed: bool = True,
+ dry_run: bool = False,
+) -> CustomProductPushBatchResult:
+ """Create a custom product push campaign pushing one product to each org in the batch.
+
+ The campaign lands as SCHEDULED with its own window: the daily sweep starts it
+ on or after `starts_on` and closes it at `ends_at`, instead of applying the
+ default campaign duration. Because the campaign is dated it also overrides the
+ signup grace period and the between-campaigns cooldown.
+
+ `on_active_campaign` decides what happens to an org that is already running a
+ campaign — the caller must pick one, since none of the three is a safe default:
+ `skip` writes nothing, `queue` starts the custom product push campaign once the running one
+ closes, and `override` cancels the running one so the custom product push campaign starts on
+ the next sweep.
+
+ Re-running with the same org list is a no-op: an org that already holds a
+ scheduled or active campaign for the product is counted and left alone.
+ """
+ if on_active_campaign not in ON_ACTIVE_POLICIES:
+ raise ValueError(f"on_active_campaign must be one of {ON_ACTIVE_POLICIES}, got {on_active_campaign!r}")
+
+ result = CustomProductPushBatchResult()
+ created_rows: list[tuple[ProductPushCampaign, str]] = []
+
+ organizations = Organization.objects.filter(id__in=organization_ids).only("id", "created_at")
+
+ for organization in organizations:
+ result.orgs_processed += 1
+
+ history = list(
+ ProductPushCampaign.objects.filter(organization=organization, product_key=product_key).values_list(
+ "status", "ended_at"
+ )
+ )
+ if any(
+ status in (ProductPushCampaign.Status.SCHEDULED, ProductPushCampaign.Status.ACTIVE) for status, _ in history
+ ):
+ result.already_pending += 1
+ continue
+ if any(status == ProductPushCampaign.Status.ADOPTED for status, _ in history):
+ result.already_adopted += 1
+ continue
+ if skip_recently_pushed and any(
+ ended_at is not None and not is_retry_eligible(ended_at, now) for _, ended_at in history
+ ):
+ result.in_retry_cooldown += 1
+ continue
+
+ active = (
+ ProductPushCampaign.objects.filter(organization=organization, status=ProductPushCampaign.Status.ACTIVE)
+ .only("id", "ends_at")
+ .first()
+ )
+ if active is not None and on_active_campaign == ON_ACTIVE_SKIP:
+ result.blocked_by_active += 1
+ logger.info(
+ "custom_product_push_blocked_by_active",
+ organization_id=str(organization.id),
+ product_key=product_key,
+ active_campaign_id=str(active.id),
+ )
+ continue
+
+ # A queued campaign only starts once the running one closes, so a running
+ # campaign planned to outlast the requested window leaves it no time to run.
+ # Refuse the org instead of writing a campaign that expires unseen — the
+ # operator can widen the window or override the running campaign.
+ if (
+ active is not None
+ and on_active_campaign == ON_ACTIVE_QUEUE
+ and (active.ends_at is None or active.ends_at >= ends_at)
+ ):
+ result.window_unreachable += 1
+ logger.info(
+ "custom_product_push_window_unreachable",
+ organization_id=str(organization.id),
+ product_key=product_key,
+ active_campaign_id=str(active.id),
+ active_ends_at=str(active.ends_at),
+ ends_at=str(ends_at),
+ )
+ continue
+
+ if dry_run:
+ result.would_create += 1
+ logger.info(
+ "custom_product_push_would_create",
+ organization_id=str(organization.id),
+ product_key=product_key,
+ starts_on=str(starts_on),
+ ends_at=str(ends_at),
+ on_active_campaign=on_active_campaign if active is not None else None,
+ )
+ continue
+
+ campaign = _create_custom_product_push_campaign(
+ organization,
+ product_key,
+ starts_on=starts_on,
+ ends_at=ends_at,
+ reason_text=reason_text,
+ )
+ if campaign is None:
+ result.conflicts += 1
+ continue
+
+ if active is not None:
+ # Cancelling skips a locked row, so an override can come back empty. The
+ # custom push is then simply queued behind the running campaign, and the
+ # run has to say so rather than report an override that did not happen.
+ overrode = on_active_campaign == ON_ACTIVE_OVERRIDE and cancel_campaigns([str(active.id)], now) == 1
+ if overrode:
+ result.overrode_active += 1
+ else:
+ result.queued_behind_active += 1
+ if on_active_campaign == ON_ACTIVE_OVERRIDE:
+ logger.warning(
+ "custom_product_push_override_skipped",
+ organization_id=str(organization.id),
+ product_key=product_key,
+ active_campaign_id=str(active.id),
+ )
+
+ result.created += 1
+ created_rows.append((campaign, "scheduled"))
+ logger.info(
+ "custom_product_push_created",
+ campaign_id=str(campaign.id),
+ organization_id=str(organization.id),
+ product_key=product_key,
+ starts_on=str(starts_on),
+ ends_at=str(ends_at),
+ on_active_campaign=on_active_campaign if active is not None else None,
+ )
+
+ _capture_campaign_events(created_rows)
+ return result
+
+
def cancel_campaigns(campaign_ids: list[str], now: datetime) -> int:
"""Cancel SCHEDULED or ACTIVE campaigns (admin action). Returns the count cancelled."""
cancelled: list[tuple[ProductPushCampaign, str]] = []
@@ -301,7 +486,10 @@ def _start_campaign(organization: Organization, selection: Selection, now: datet
return None
campaign.status = ProductPushCampaign.Status.ACTIVE
campaign.started_at = now
- campaign.ends_at = ends_at
+ # A custom product push campaign carries the window its operator asked for; only
+ # fall back to the default duration when it has none.
+ if campaign.ends_at is None:
+ campaign.ends_at = ends_at
campaign.save(update_fields=["status", "started_at", "ends_at", "updated_at"])
return campaign
return ProductPushCampaign.objects.create(
@@ -318,6 +506,39 @@ def _start_campaign(organization: Organization, selection: Selection, now: datet
return None
+def _create_custom_product_push_campaign(
+ organization: Organization,
+ product_key: str,
+ *,
+ starts_on: date,
+ ends_at: datetime,
+ reason_text: str | None,
+) -> ProductPushCampaign | None:
+ """Queue a custom product push campaign behind whatever the org already has scheduled."""
+ try:
+ with transaction.atomic():
+ last_position = (
+ ProductPushCampaign.objects.filter(
+ organization=organization, status=ProductPushCampaign.Status.SCHEDULED
+ ).aggregate(last=Max("position"))["last"]
+ or 0
+ )
+ return ProductPushCampaign.objects.create(
+ organization=organization,
+ product_key=product_key,
+ status=ProductPushCampaign.Status.SCHEDULED,
+ source=ProductPushCampaign.Source.TAM,
+ position=last_position + 1,
+ scheduled_for=starts_on,
+ ends_at=ends_at,
+ reason_text=reason_text,
+ )
+ except IntegrityError:
+ # A concurrent run queued the same product for this org — the partial unique
+ # constraint keeps the org on one pending push instead of two.
+ return None
+
+
def _capture_campaign_events(campaign_events: list[tuple[ProductPushCampaign, str]]) -> None:
"""Emit one analytics event per transition, after the transactions committed.
diff --git a/products/growth/dags/custom_product_push_campaigns.py b/products/growth/dags/custom_product_push_campaigns.py
new file mode 100644
index 000000000000..fce229157196
--- /dev/null
+++ b/products/growth/dags/custom_product_push_campaigns.py
@@ -0,0 +1,278 @@
+"""Dagster job that creates custom product push campaigns for a list of organizations.
+
+Growth names the organizations, the product, and the window the push should run
+for. The job creates one SCHEDULED, TAM-sourced `ProductPushCampaign` per
+organization, and the daily `product_push_campaigns_job` starts it on or after
+`starts_on` and closes it at `ends_on` — so a custom push joins the normal campaign
+lifecycle instead of bypassing it.
+
+Two things the operator has to decide per run, because no default is safe:
+
+- `on_active_campaign` — an organization can already be running a campaign, and
+ only one runs at a time. `skip` writes nothing for it, `queue` starts the custom
+ push once the running one closes, `override` cancels the running one. A queued
+ push is refused when the running campaign is planned to outlast the window,
+ since it would expire before getting to run.
+- `starts_on` / `ends_on` — the campaign window. Dating the campaign also overrides
+ the signup grace period and the between-campaigns cooldown.
+
+Re-running with the same organization list creates nothing new: an organization
+that already holds a scheduled or active campaign for the product is counted and
+skipped.
+"""
+
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, time
+
+from django.conf import settings
+from django.db import connections
+
+import dagster
+import pydantic
+
+from posthog.clickhouse.query_tagging import get_query_tags
+from posthog.dags.common import JobOwners, dagster_tags
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+from posthog.models.organization import Organization
+from posthog.schema_enums import ProductKey
+
+from products.growth.backend.product_push.selection import (
+ BLESSED_PRODUCT_ORDER,
+ FALLBACK_PRODUCT_ORDER,
+ PUSH_PRODUCT_PATHS,
+)
+from products.growth.backend.product_push.service import (
+ ON_ACTIVE_POLICIES,
+ CustomProductPushBatchResult,
+ create_custom_product_push_campaigns_for_org_batch,
+)
+
+CUSTOM_PUSH_BATCH_SIZE = 500
+
+_BATCH_OP_RETRY_POLICY = dagster.RetryPolicy(
+ max_retries=3,
+ delay=30,
+ backoff=dagster.Backoff.EXPONENTIAL,
+ jitter=dagster.Jitter.FULL,
+)
+
+
+@frozen
+class CustomProductPushBatchSpec:
+ organization_ids: list[str]
+ product_key: str
+ starts_on: date
+ ends_at: datetime
+ on_active_campaign: str
+ reason_text: str | None
+ skip_recently_pushed: bool
+ dry_run: bool
+
+
+class CustomProductPushCampaignConfig(dagster.Config):
+ """Config for the custom product push campaign job."""
+
+ organization_ids: list[str] = pydantic.Field(
+ description="Organization ids (UUIDs) to create the campaign for.",
+ min_length=1,
+ )
+ product_key: str = pydantic.Field(
+ description="ProductKey value of the product to push, e.g. 'session_replay'.",
+ )
+ starts_on: str = pydantic.Field(
+ description="First day the campaign may start (YYYY-MM-DD). The daily sweep starts it on or after "
+ "this date, and a dated campaign overrides the signup grace period and the between-campaigns cooldown.",
+ )
+ ends_on: str = pydantic.Field(
+ description="Last day the campaign runs (YYYY-MM-DD), inclusive. A campaign that never got to start "
+ "by then is cancelled instead of shown late.",
+ )
+ on_active_campaign: str = pydantic.Field(
+ description="What to do with an organization that is already running a campaign: "
+ "'skip' writes nothing for it, 'queue' starts this campaign once the running one closes, "
+ "'override' cancels the running one so this campaign starts on the next sweep.",
+ )
+ reason_text: str | None = pydantic.Field(
+ default=None,
+ description="Custom promo copy shown on the card. Empty uses the product's default copy.",
+ )
+ skip_recently_pushed: bool = pydantic.Field(
+ default=True,
+ description="Skip organizations that were pushed this same product in the last 90 days. "
+ "Turn off only when the repeat push is deliberate.",
+ )
+ batch_size: int = pydantic.Field(default=CUSTOM_PUSH_BATCH_SIZE, gt=0)
+ max_campaigns: int | None = pydantic.Field(
+ default=None,
+ description="Cap on how many campaigns this run may create (herd control for large lists).",
+ gt=0,
+ )
+ dry_run: bool = pydantic.Field(
+ default=False,
+ description="Log what would be created without writing campaigns or emitting events.",
+ )
+
+
+def _parse_window(config: CustomProductPushCampaignConfig) -> tuple[date, datetime]:
+ try:
+ starts_on = date.fromisoformat(config.starts_on)
+ ends_on = date.fromisoformat(config.ends_on)
+ except ValueError:
+ raise dagster.Failure(
+ f"starts_on and ends_on must be YYYY-MM-DD dates, got {config.starts_on!r} and {config.ends_on!r}"
+ )
+ if ends_on < starts_on:
+ raise dagster.Failure(f"ends_on ({ends_on}) is before starts_on ({starts_on})")
+ # ends_on is inclusive, so the campaign runs to the end of that day.
+ return starts_on, datetime.combine(ends_on, time.max, tzinfo=UTC)
+
+
[email protected](out=dagster.DynamicOut(CustomProductPushBatchSpec))
+def get_custom_product_push_batches_op(
+ context: dagster.OpExecutionContext, config: CustomProductPushCampaignConfig
+) -> Iterator[dagster.DynamicOutput[CustomProductPushBatchSpec]]:
+ """Validate the config and fan out the organization list as batches."""
+ try:
+ product_key = ProductKey(config.product_key)
+ except ValueError:
+ raise dagster.Failure(f"product_key must be a valid ProductKey value, got {config.product_key!r}")
+
+ if config.on_active_campaign not in ON_ACTIVE_POLICIES:
+ raise dagster.Failure(
+ f"on_active_campaign must be one of {', '.join(ON_ACTIVE_POLICIES)}, got {config.on_active_campaign!r}"
+ )
+
+ starts_on, ends_at = _parse_window(config)
+ now = datetime.now(tz=UTC)
+ if ends_at <= now:
+ raise dagster.Failure(f"ends_on ({config.ends_on}) is already past — the campaign would never run")
+
+ if product_key not in PUSH_PRODUCT_PATHS:
+ context.log.warning(
+ f"{product_key.value} has no curated catalog path — the card falls back to intent inference, "
+ "which resolves to the wrong product for several keys. Add it to PUSH_PRODUCT_PATHS first."
+ )
+ if product_key not in BLESSED_PRODUCT_ORDER and product_key not in FALLBACK_PRODUCT_ORDER:
+ context.log.warning(
+ f"{product_key.value} is outside the automatic push lists, so it may be feature-flag gated or "
+ "unreleased. The card is hidden for users without the flag, and this run will still report "
+ "the campaigns as created."
+ )
+
+ requested_ids = list(dict.fromkeys(config.organization_ids))
+ organization_ids = [
+ str(organization_id)
+ for organization_id in Organization.objects.filter(id__in=requested_ids).values_list("id", flat=True)
+ ]
+ missing = len(requested_ids) - len(organization_ids)
+ if missing:
+ context.log.warning(f"{missing} of {len(requested_ids)} organization ids do not exist and are ignored")
+ if config.max_campaigns is not None and len(organization_ids) > config.max_campaigns:
+ context.log.info(f"Capping at max_campaigns={config.max_campaigns} of {len(organization_ids)} organizations")
+ organization_ids = organization_ids[: config.max_campaigns]
+
+ context.log.info(
+ f"Creating {product_key.value} campaigns for {len(organization_ids)} organizations, running "
+ f"{starts_on} to {config.ends_on} (on_active_campaign={config.on_active_campaign}, dry_run={config.dry_run})"
+ )
+
+ def spec(ids: list[str]) -> CustomProductPushBatchSpec:
+ return CustomProductPushBatchSpec(
+ organization_ids=ids,
+ product_key=product_key.value,
+ starts_on=starts_on,
+ ends_at=ends_at,
+ on_active_campaign=config.on_active_campaign,
+ reason_text=config.reason_text or None,
+ skip_recently_pushed=config.skip_recently_pushed,
+ dry_run=config.dry_run,
+ )
+
+ # Always yield one batch so the summary op runs even when nothing matched.
+ if not organization_ids:
+ yield dagster.DynamicOutput(spec([]), mapping_key="batch_0")
+ return
+ for index in range(0, len(organization_ids), config.batch_size):
+ yield dagster.DynamicOutput(
+ spec(organization_ids[index : index + config.batch_size]),
+ mapping_key=f"batch_{index // config.batch_size}",
+ )
+
+
[email protected](retry_policy=_BATCH_OP_RETRY_POLICY)
+def create_custom_product_push_batch_op(
+ context: dagster.OpExecutionContext, spec: CustomProductPushBatchSpec
+) -> CustomProductPushBatchResult:
+ """Create campaigns for the organizations in this batch. Retry-safe: an org that
+ already holds a pending campaign for the product is skipped, and the partial
+ unique constraint turns a concurrent double-write into a counted conflict."""
+ get_query_tags().with_dagster(dagster_tags(context))
+ try:
+ result = create_custom_product_push_campaigns_for_org_batch(
+ spec.organization_ids,
+ spec.product_key,
+ now=datetime.now(tz=UTC),
+ starts_on=spec.starts_on,
+ ends_at=spec.ends_at,
+ on_active_campaign=spec.on_active_campaign,
+ reason_text=spec.reason_text,
+ skip_recently_pushed=spec.skip_recently_pushed,
+ dry_run=spec.dry_run,
+ )
+ context.log.info(
+ f"Batch of {result.orgs_processed} orgs: {result.created} created "
+ f"({result.queued_behind_active} queued behind a running campaign, "
+ f"{result.overrode_active} overrode one), {result.would_create} would create, "
+ f"{result.blocked_by_active} blocked by a running campaign, "
+ f"{result.window_unreachable} without room in the window, {result.already_pending} already pending, "
+ f"{result.already_adopted} already adopted, {result.in_retry_cooldown} pushed this product recently, "
+ f"{result.conflicts} conflicts"
+ )
+ return result
+ except Exception as e:
+ context.log.exception(f"Failed to create campaigns for batch of {len(spec.organization_ids)} orgs")
+ capture_exception(e, {"team": "team-growth", "org_count": len(spec.organization_ids)})
+ raise
+ finally:
+ if not settings.TEST:
+ connections.close_all()
+
+
+def summarize_custom_product_push_run_op(
+ context: dagster.OpExecutionContext, results: list[CustomProductPushBatchResult]
+) -> None:
+ """Roll up per-batch counts into a single run-level summary."""
+ created = sum(r.created for r in results)
+ would_create = sum(r.would_create for r in results)
+
+ context.log.info(f"Run complete: {created} campaigns created, {would_create} would be created")
+ context.add_output_metadata(
+ {
+ "orgs_processed": dagster.MetadataValue.int(sum(r.orgs_processed for r in results)),
+ "campaigns_created": dagster.MetadataValue.int(created),
+ "campaigns_would_create": dagster.MetadataValue.int(would_create),
+ "queued_behind_active": dagster.MetadataValue.int(sum(r.queued_behind_active for r in results)),
+ "overrode_active": dagster.MetadataValue.int(sum(r.overrode_active for r in results)),
+ "skipped_blocked_by_active": dagster.MetadataValue.int(sum(r.blocked_by_active for r in results)),
+ "skipped_window_unreachable": dagster.MetadataValue.int(sum(r.window_unreachable for r in results)),
+ "skipped_already_pending": dagster.MetadataValue.int(sum(r.already_pending for r in results)),
+ "skipped_already_adopted": dagster.MetadataValue.int(sum(r.already_adopted for r in results)),
+ "skipped_pushed_recently": dagster.MetadataValue.int(sum(r.in_retry_cooldown for r in results)),
+ "conflicts": dagster.MetadataValue.int(sum(r.conflicts for r in results)),
+ }
+ )
+
+
+ description=(
+ "Create a custom product push campaign for a list of organizations, running for a given window. "
+ "Campaigns land as scheduled and are started and closed by the daily product push job."
+ ),
+ executor_def=dagster.multiprocess_executor.configured({"max_concurrent": 5}),
+ tags={"owner": JobOwners.TEAM_GROWTH.value},
+)
+def custom_product_push_campaigns_job() -> None:
+ results = get_custom_product_push_batches_op().map(create_custom_product_push_batch_op).collect()
+ summarize_custom_product_push_run_op(results)
diff --git a/products/growth/dags/product_push_campaigns.py b/products/growth/dags/product_push_campaigns.py
index 7f757231be4c..9e59d603627c 100644
--- a/products/growth/dags/product_push_campaigns.py
+++ b/products/growth/dags/product_push_campaigns.py
@@ -196,7 +196,7 @@ def start_campaign_batch_op(context: dagster.OpExecutionContext, spec: StartBatc
context.log.info(
f"Batch of {result.orgs_processed} orgs: {result.started} started, {result.would_start} would start, "
f"{result.no_candidate} without candidate, {result.not_eligible} not eligible, "
- f"{result.conflicts} conflicts"
+ f"{result.expired} expired before starting, {result.conflicts} conflicts"
)
return result
except Exception as e:
@@ -233,6 +233,7 @@ def summarize_product_push_run_op(
"campaigns_would_start": dagster.MetadataValue.int(would_start),
"starts_not_eligible": dagster.MetadataValue.int(sum(r.not_eligible for r in start_results)),
"starts_no_candidate": dagster.MetadataValue.int(sum(r.no_candidate for r in start_results)),
+ "starts_expired": dagster.MetadataValue.int(sum(r.expired for r in start_results)),
"start_conflicts": dagster.MetadataValue.int(sum(r.conflicts for r in start_results)),
}
)
diff --git a/products/growth/dags/tests/test_custom_product_push_campaigns.py b/products/growth/dags/tests/test_custom_product_push_campaigns.py
new file mode 100644
index 000000000000..cd1e3d91c2f1
--- /dev/null
+++ b/products/growth/dags/tests/test_custom_product_push_campaigns.py
@@ -0,0 +1,197 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+import dagster
+from parameterized import parameterized
+
+from posthog.models.organization import Organization
+
+from products.growth.backend.models import ProductPushCampaign
+from products.growth.dags.custom_product_push_campaigns import custom_product_push_campaigns_job
+from products.growth.dags.product_push_campaigns import product_push_campaigns_job
+
+
+@contextmanager
+def _mock_capture() -> Iterator[MagicMock]:
+ capture_fn = MagicMock()
+ with patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_csm:
+ mock_csm.return_value.__enter__.return_value = capture_fn
+ mock_csm.return_value.__exit__.return_value = False
+ yield capture_fn
+
+
+class TestCustomProductPushCampaignsJob(BaseTest):
+ def _run_job(self, raise_on_error: bool = True, **config: Any) -> dagster.ExecuteInProcessResult:
+ today = timezone.now().date()
+ run_config = {
+ "ops": {
+ "get_custom_product_push_batches_op": {
+ "config": {
+ "organization_ids": [str(self.organization.id)],
+ "product_key": "session_replay",
+ "starts_on": today.isoformat(),
+ "ends_on": (today + timedelta(days=20)).isoformat(),
+ "on_active_campaign": "queue",
+ **config,
+ }
+ }
+ }
+ }
+ with _mock_capture():
+ return custom_product_push_campaigns_job.execute_in_process(
+ run_config=run_config, raise_on_error=raise_on_error
+ )
+
+ def _start_active_campaign(self, organization: Organization, product_key: str) -> ProductPushCampaign:
+ return ProductPushCampaign.objects.create(
+ organization=organization,
+ product_key=product_key,
+ status=ProductPushCampaign.Status.ACTIVE,
+ started_at=timezone.now(),
+ ends_at=timezone.now() + timedelta(days=14),
+ )
+
+ def test_creates_a_scheduled_tam_campaign_with_the_requested_window(self) -> None:
+ other = Organization.objects.create(name="other")
+ today = timezone.now().date()
+
+ result = self._run_job(
+ organization_ids=[str(self.organization.id), str(other.id)],
+ starts_on=(today + timedelta(days=2)).isoformat(),
+ ends_on=(today + timedelta(days=9)).isoformat(),
+ reason_text="Try replay",
+ )
+
+ assert result.success
+ campaigns = ProductPushCampaign.objects.all()
+ assert campaigns.count() == 2
+ for campaign in campaigns:
+ assert campaign.status == ProductPushCampaign.Status.SCHEDULED
+ assert campaign.source == ProductPushCampaign.Source.TAM
+ assert campaign.product_key == "session_replay"
+ assert campaign.reason_text == "Try replay"
+ assert campaign.scheduled_for == today + timedelta(days=2)
+ assert campaign.ends_at is not None
+ assert campaign.ends_at.date() == today + timedelta(days=9)
+
+ def test_rerunning_the_same_list_does_not_double_create(self) -> None:
+ assert self._run_job().success
+ assert self._run_job().success
+
+ assert ProductPushCampaign.objects.filter(organization=self.organization).count() == 1
+
+ @parameterized.expand(
+ [
+ ("skip", 20, ProductPushCampaign.Status.ACTIVE, False),
+ ("queue", 20, ProductPushCampaign.Status.ACTIVE, True),
+ ("override", 20, ProductPushCampaign.Status.CANCELLED, True),
+ # The running campaign outlasts this window, so a queued push would
+ # expire before getting to run — nothing is written for the org.
+ ("queue", 5, ProductPushCampaign.Status.ACTIVE, False),
+ ]
+ )
+ def test_policy_decides_what_happens_to_a_running_campaign(
+ self, policy: str, window_days: int, running_status: str, creates_campaign: bool
+ ) -> None:
+ running = self._start_active_campaign(self.organization, "product_analytics")
+
+ assert self._run_job(
+ on_active_campaign=policy,
+ ends_on=(timezone.now().date() + timedelta(days=window_days)).isoformat(),
+ ).success
+
+ running.refresh_from_db()
+ assert running.status == running_status
+ created = ProductPushCampaign.objects.filter(product_key="session_replay").first()
+ assert (created is not None) == creates_campaign
+ if created is not None:
+ assert created.status == ProductPushCampaign.Status.SCHEDULED
+ assert created.position == 1
+
+ def test_the_daily_job_starts_the_campaign_and_keeps_its_window(self) -> None:
+ today = timezone.now().date()
+ assert self._run_job(ends_on=(today + timedelta(days=3)).isoformat()).success
+
+ with _mock_capture():
+ assert product_push_campaigns_job.execute_in_process().success
+
+ campaign = ProductPushCampaign.objects.get(product_key="session_replay")
+ assert campaign.status == ProductPushCampaign.Status.ACTIVE
+ assert campaign.ends_at is not None
+ # The requested window survives, rather than the default 14-day duration.
+ assert campaign.ends_at.date() == today + timedelta(days=3)
+
+ def test_a_campaign_whose_window_passed_is_cancelled_instead_of_started(self) -> None:
+ assert self._run_job().success
+ campaign = ProductPushCampaign.objects.get(product_key="session_replay")
+ ProductPushCampaign.objects.filter(id=campaign.id).update(ends_at=timezone.now() - timedelta(days=1))
+
+ with _mock_capture():
+ assert product_push_campaigns_job.execute_in_process().success
+
+ campaign.refresh_from_db()
+ assert campaign.status == ProductPushCampaign.Status.CANCELLED
+
+ def test_skips_organizations_that_adopted_or_recently_skipped_the_product(self) -> None:
+ adopted_org = Organization.objects.create(name="adopted")
+ ProductPushCampaign.objects.create(
+ organization=adopted_org,
+ product_key="session_replay",
+ status=ProductPushCampaign.Status.ADOPTED,
+ ended_at=timezone.now() - timedelta(days=1),
+ )
+ skipped_org = Organization.objects.create(name="skipped")
+ ProductPushCampaign.objects.create(
+ organization=skipped_org,
+ product_key="session_replay",
+ status=ProductPushCampaign.Status.SKIPPED,
+ ended_at=timezone.now() - timedelta(days=1),
+ )
+
+ assert self._run_job(organization_ids=[str(adopted_org.id), str(skipped_org.id)]).success
+
+ assert not ProductPushCampaign.objects.filter(status=ProductPushCampaign.Status.SCHEDULED).exists()
+
+ assert self._run_job(organization_ids=[str(skipped_org.id)], skip_recently_pushed=False).success
+
+ assert ProductPushCampaign.objects.filter(
+ organization=skipped_org, status=ProductPushCampaign.Status.SCHEDULED
+ ).exists()
+
+ def test_dry_run_and_max_campaigns_limit_what_is_written(self) -> None:
+ assert self._run_job(dry_run=True).success
+ assert not ProductPushCampaign.objects.exists()
+
+ other = Organization.objects.create(name="other")
+ assert self._run_job(organization_ids=[str(self.organization.id), str(other.id)], max_campaigns=1).success
+ assert ProductPushCampaign.objects.count() == 1
+
+ @parameterized.expand(
+ [
+ ("unknown product", {"product_key": "not_a_product"}, None, None),
+ ("unknown policy", {"on_active_campaign": "cancel_everything"}, None, None),
+ ("window already past", {}, None, -1),
+ ("end before start", {}, 5, 0),
+ ]
+ )
+ def test_invalid_config_fails_the_run(
+ self, _name: str, overrides: dict[str, Any], starts_in_days: int | None, ends_in_days: int | None
+ ) -> None:
+ today = timezone.now().date()
+ config = dict(overrides)
+ if starts_in_days is not None:
+ config["starts_on"] = (today + timedelta(days=starts_in_days)).isoformat()
+ if ends_in_days is not None:
+ config["ends_on"] = (today + timedelta(days=ends_in_days)).isoformat()
+
+ result = self._run_job(raise_on_error=False, **config)
+
+ assert not result.success
+ assert not ProductPushCampaign.objects.exists()