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(growth): drop organization join from product push close batch (#129824)

Rafael Audibert5a10539779a0
diff --git a/products/growth/backend/product_push/service.py b/products/growth/backend/product_push/service.py
index a0d04987fb07..134186c5121f 100644
--- a/products/growth/backend/product_push/service.py
+++ b/products/growth/backend/product_push/service.py
@@ -162,9 +162,7 @@ def evaluate_and_close_campaign_batch(campaign_ids: list[str], now: datetime) ->
result = CloseBatchResult()
closed: list[tuple[ProductPushCampaign, str]] = []
- campaigns = ProductPushCampaign.objects.filter(
- id__in=campaign_ids, status=ProductPushCampaign.Status.ACTIVE
- ).select_related("organization")
+ campaigns = ProductPushCampaign.objects.filter(id__in=campaign_ids, status=ProductPushCampaign.Status.ACTIVE)
for campaign in campaigns:
if campaign.started_at is None:
@@ -440,12 +438,10 @@ def cancel_campaigns(campaign_ids: list[str], now: datetime) -> int:
cancelled: list[tuple[ProductPushCampaign, str]] = []
with transaction.atomic():
campaigns = list(
- ProductPushCampaign.objects.select_for_update(skip_locked=True)
- .filter(
+ ProductPushCampaign.objects.select_for_update(skip_locked=True).filter(
id__in=campaign_ids,
status__in=[ProductPushCampaign.Status.SCHEDULED, ProductPushCampaign.Status.ACTIVE],
)
- .select_related("organization")
)
for campaign in campaigns:
campaign.status = ProductPushCampaign.Status.CANCELLED
@@ -556,6 +552,29 @@ def _capture_campaign_events(campaign_events: list[tuple[ProductPushCampaign, st
if not campaign_events:
return
+ # groups() reads only the org's pk and customer_id, so fetch those two columns for the orgs not
+ # already attached, rather than joining full organization rows into every batch query.
+ missing_org_ids = {
+ campaign.organization_id
+ for campaign, _ in campaign_events
+ if not ProductPushCampaign.organization.is_cached(campaign)
+ }
+ if missing_org_ids:
+ # The transitions already committed, so a failed lookup must not fail the caller; a campaign
+ # left without its org falls back to the per-row guard below.
+ try:
+ organizations_by_id = {
+ organization.id: organization
+ for organization in Organization.objects.filter(id__in=missing_org_ids).only("id", "customer_id")
+ }
+ except Exception as e:
+ capture_exception(e, {"team": "team-growth"})
+ logger.exception("product_push_campaign_org_lookup_failed", organization_count=len(missing_org_ids))
+ organizations_by_id = {}
+ for campaign, _ in campaign_events:
+ if campaign.organization_id in organizations_by_id:
+ campaign.organization = organizations_by_id[campaign.organization_id]
+
with ph_scoped_capture() as capture:
for campaign, transition in campaign_events:
try:
diff --git a/products/growth/backend/tests/test_product_push_service.py b/products/growth/backend/tests/test_product_push_service.py
index a2c7ba087c8e..9ef14edb99f4 100644
--- a/products/growth/backend/tests/test_product_push_service.py
+++ b/products/growth/backend/tests/test_product_push_service.py
@@ -3,6 +3,8 @@ from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from django.db import DatabaseError, connection
+from django.test.utils import CaptureQueriesContext
from django.utils import timezone
from posthog.models.organization import Organization
@@ -168,9 +170,13 @@ class TestProductPushService(BaseTest):
assert campaign.status == ProductPushCampaign.Status.ACTIVE
def test_expired_campaign_without_adoption_closes_as_skipped(self) -> None:
+ Organization.objects.filter(id=self.organization.id).update(customer_id="cus_test_123")
campaign = self._active_campaign("product_analytics", started_days_ago=CAMPAIGN_DURATION_DAYS + 1)
- with patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_scoped:
+ with (
+ patch("products.growth.backend.product_push.service.ph_scoped_capture") as mock_scoped,
+ CaptureQueriesContext(connection) as queries,
+ ):
mock_capture = MagicMock()
mock_scoped.return_value.__enter__.return_value = mock_capture
result = evaluate_and_close_campaign_batch([str(campaign.id)], self.now)
@@ -180,6 +186,10 @@ class TestProductPushService(BaseTest):
assert campaign.status == ProductPushCampaign.Status.SKIPPED
assert campaign.ended_at == self.now
assert mock_capture.call_args.kwargs["event"] == "product push campaign skipped"
+ groups = mock_capture.call_args.kwargs["groups"]
+ assert groups["organization"] == str(self.organization.id)
+ assert groups["customer"] == "cus_test_123"
+ assert not [q["sql"] for q in queries.captured_queries if 'JOIN "posthog_organization"' in q["sql"]]
def test_intent_created_during_campaign_adopts_product_without_activation_criterion(self) -> None:
campaign = self._active_campaign("web_analytics")
@@ -282,3 +292,14 @@ class TestProductPushService(BaseTest):
assert active.ended_at == self.now
assert scheduled.status == ProductPushCampaign.Status.CANCELLED
assert adopted.status == ProductPushCampaign.Status.ADOPTED
+
+ def test_cancel_succeeds_when_event_org_lookup_fails(self) -> None:
+ active = self._active_campaign("product_analytics")
+
+ with patch("products.growth.backend.product_push.service.Organization.objects.filter") as mock_filter:
+ mock_filter.side_effect = DatabaseError("connection lost")
+ cancelled_count = cancel_campaigns([str(active.id)], self.now)
+
+ assert cancelled_count == 1
+ active.refresh_from_db()
+ assert active.status == ProductPushCampaign.Status.CANCELLED