: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
feat(billing): sync Organization.is_active into billing's deactivated flag (#117974)
minekansu4b7a652d8349
diff --git a/ee/api/billing.py b/ee/api/billing.pyindex 0791656fe491..7eca6e4391df 100644--- a/ee/api/billing.py+++ b/ee/api/billing.py@@ -358,7 +358,6 @@ class BillingOverviewResponseSerializer(serializers.Serializer):billing_plan = serializers.CharField(required=False, allow_blank=True, allow_null=True)subscription_level = serializers.CharField(required=False, allow_blank=True, allow_null=True)has_active_subscription = serializers.BooleanField(required=False)- deactivated = serializers.BooleanField(required=False)is_annual_plan_customer = serializers.BooleanField(required=False)free_trial_until = serializers.CharField(required=False, allow_blank=True, allow_null=True)current_total_amount_usd = serializers.CharField(required=False, allow_blank=True, allow_null=True)diff --git a/ee/api/organization_billing.py b/ee/api/organization_billing.pyindex b9c2d18d41b5..184afa369442 100644--- a/ee/api/organization_billing.py+++ b/ee/api/organization_billing.py@@ -157,7 +157,6 @@ class BillingSubscriptionSerializer(serializers.Serializer):subscription_level = serializers.CharField(allow_null=True)billing_plan = serializers.CharField(allow_null=True)billing_provider = serializers.ChoiceField(choices=["stripe", "vercel"], allow_null=True)- deactivated = serializers.BooleanField()is_annual_plan_customer = serializers.BooleanField()billing_period = BillingPeriodSerializer(allow_null=True)trial = TrialSerializer(allow_null=True)@@ -854,7 +853,6 @@ class OrganizationBillingViewSet(BillingReadViewSet):"subscription_level": data.get("subscription_level"),"billing_plan": data.get("billing_plan"),"billing_provider": ORGANIZATION_BILLING_PROVIDER.get(data.get("billing_provider") or "", None),- "deactivated": data.get("deactivated", False),"is_annual_plan_customer": data.get("is_annual_plan_customer", False),"billing_period": _billing_period(data.get("billing_period")),"trial": (diff --git a/ee/api/test/test_billing.py b/ee/api/test/test_billing.pyindex 86c20d922d00..182b00d9f03a 100644--- a/ee/api/test/test_billing.py+++ b/ee/api/test/test_billing.py@@ -101,7 +101,6 @@ def create_billing_response(**kwargs) -> dict[str, Any]:def create_missing_billing_customer(**kwargs) -> CustomerInfo:data: dict[str, Any] = {"customer_id": "cus_123",- "deactivated": False,"custom_limits_usd": {},"has_active_subscription": False,"current_total_amount_usd": "0.00",@@ -132,7 +131,6 @@ def create_billing_customer(**kwargs) -> CustomerInfo:"current_total_amount_usd_after_discount": "100.00","discount_percent": None,"discount_amount_usd": None,- "deactivated": False,"products": [{"name": "Product OS",@@ -429,7 +427,6 @@ class TestBillingAPI(APILicensedTest):"current_total_amount_usd_after_discount": "100.00","discount_percent": None,"discount_amount_usd": None,- "deactivated": False,"products": [{"name": "Product OS",@@ -629,7 +626,6 @@ class TestBillingAPI(APILicensedTest):"current_total_amount_usd_after_discount": "0.00","discount_percent": None,"discount_amount_usd": None,- "deactivated": False,"stripe_portal_url": "http://localhost:8010/api/billing/portal","billing_managed_by_partner": None,}diff --git a/ee/api/test/test_organization_billing.py b/ee/api/test/test_organization_billing.pyindex b43f919b2c18..cf2f1d1374ce 100644--- a/ee/api/test/test_organization_billing.py+++ b/ee/api/test/test_organization_billing.py@@ -36,7 +36,6 @@ SUBSCRIPTION: dict[str, Any] = {"subscription_level": "paid","billing_plan": "boost","billing_provider": "posthog",- "deactivated": False,"is_annual_plan_customer": False,"trial": {"id": 7, "type": "standard", "status": "active", "target": "paid", "expires_at": PERIOD_END},"discount_percent": 20,diff --git a/ee/api/tests/test_conversation.py b/ee/api/tests/test_conversation.pyindex 5050724adb09..8ab1d715bcbf 100644--- a/ee/api/tests/test_conversation.py+++ b/ee/api/tests/test_conversation.py@@ -69,7 +69,6 @@ class TestConversation(APIBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="paid",has_active_subscription=True,- is_deactivated=False,billing_period=MaxBillingContextBillingPeriod(current_period_start=str(datetime.date(2023, 1, 1)),current_period_end=str(datetime.date(2023, 1, 31)),diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.pyindex 7a835675b586..8e71c0fb4971 100644--- a/ee/billing/billing_manager.py+++ b/ee/billing/billing_manager.py@@ -233,6 +233,28 @@ def build_billing_token(return encoded_jwt+DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION = "deactivated_organizations"+++def build_billing_system_token(license: License, service_action: str) -> str:+ """JWT for billing's /api/internal/* endpoints: license-signed, org-less, action-scoped.++ Billing's internal endpoints reject tokens that carry an organization_id claim, so unlike+ build_billing_token this deliberately omits the organization.+ """+ license_id = license.key.split("::")[0]+ license_secret = license.key.split("::")[1]++ payload = {+ "exp": datetime.now(tz=UTC) + timedelta(minutes=15),+ "id": license_id,+ "aud": "posthog:license-key",+ "service_action": service_action,+ }++ return jwt.encode(payload, license_secret, algorithm="HS256")++def _compute_webhook_signature(secret: str, timestamp: int, body: bytes) -> str:"""HMAC-SHA256 over "<timestamp>.<body>", hex-encoded."""mac = hmac.new(secret.encode(), digestmod=hashlib.sha256)@@ -1014,6 +1036,41 @@ class BillingManager:return res.json()+ def _system_auth_headers(self, service_action: str) -> dict[str, str]:+ if not self.license: # mypy+ raise Exception("No license found")+ return {"Authorization": f"Bearer {build_billing_system_token(self.license, service_action)}"}++ def set_organizations_deactivated(self, organization_ids: list[str], deactivated: bool) -> dict[str, Any]:+ """Set or remove billing's forecast-exclusion flag for these organizations.++ Billing returns 200 for every handled outcome. The default valid_codes would swallow+ 404 (endpoint not deployed) and 401 (auth failure) as success, so the caller would+ record a sync that never happened, hence the explicit (200,).+ """+ res = http_session.post(+ f"{BILLING_SERVICE_URL}/api/internal/deactivated-organizations",+ headers=self._system_auth_headers(DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION),+ json={"organization_ids": organization_ids, "deactivated": deactivated},+ timeout=30,+ )++ handle_billing_service_error(res, valid_codes=(200,))++ return res.json()++ def get_deactivated_organizations(self) -> list[str]:+ """Organization ids billing currently excludes from the revenue forecast."""+ res = http_session.get(+ f"{BILLING_SERVICE_URL}/api/internal/deactivated-organizations",+ headers=self._system_auth_headers(DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION),+ timeout=30,+ )++ handle_billing_service_error(res, valid_codes=(200,))++ return res.json()["deactivated_organization_ids"]+def activate_trial(self, organization: Organization, data: dict[str, Any]):res = http_session.post(f"{BILLING_SERVICE_URL}/api/trials/activate",diff --git a/ee/billing/billing_types.py b/ee/billing/billing_types.pyindex fff6ab76b939..d862f6e7c462 100644--- a/ee/billing/billing_types.py+++ b/ee/billing/billing_types.py@@ -184,7 +184,6 @@ class ProductFeature(TypedDict):class CustomerInfo(TypedDict):customer_id: Optional[str]- deactivated: boolhas_active_subscription: boolbilling_period: BillingPeriodavailable_product_features: list[ProductFeature]diff --git a/ee/billing/test/test_organization_deactivation_sync.py b/ee/billing/test/test_organization_deactivation_sync.pynew file mode 100644index 000000000000..0feb09d7d037--- /dev/null+++ b/ee/billing/test/test_organization_deactivation_sync.py@@ -0,0 +1,233 @@+import asyncio+import datetime+from typing import cast++from posthog.test.base import BaseTest+from unittest.mock import AsyncMock, MagicMock, patch++import jwt+from temporalio.common import WorkflowIDConflictPolicy++from posthog.models.organization import Organization, _start_billing_active_sync_workflow+from posthog.temporal.billing_active_sync.sync_organization_active_state import (+ RESYNC_SIGNAL,+ reconcile_organization_active_state,+ sync_organization_active_state,+)++from ee.billing.billing_manager import (+ DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION,+ BillingManager,+ build_billing_system_token,+)+from ee.models.license import License, LicenseManager+++def _create_license() -> License:+ return super(LicenseManager, cast(LicenseManager, License.objects)).create(+ key="key123::secret123",+ plan="enterprise",+ valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),+ )+++class TestBuildBillingSystemToken(BaseTest):+ def test_token_is_org_less_and_action_scoped(self):+ license = _create_license()++ token = build_billing_system_token(license, DEACTIVATED_ORGANIZATIONS_SERVICE_ACTION)++ payload = jwt.decode(token, "secret123", algorithms=["HS256"], audience="posthog:license-key")+ assert payload["id"] == "key123"+ assert payload["service_action"] == "deactivated_organizations"+ assert "organization_id" not in payload+ assert "organization_name" not in payload+++class TestDeactivatedOrganizationsClient(BaseTest):+ def setUp(self):+ super().setUp()+ self.license = _create_license()++ @patch(+ "ee.billing.billing_manager.http_session.post",+ return_value=MagicMock(+ status_code=200, json=MagicMock(return_value={"changed": 1, "already_set": 0, "not_found": []})+ ),+ )+ def test_set_organizations_deactivated_posts_the_batch(self, post_mock):+ result = BillingManager(self.license).set_organizations_deactivated(["org-1"], deactivated=True)++ assert result == {"changed": 1, "already_set": 0, "not_found": []}+ (url,) = post_mock.call_args.args+ assert url == "https://billing.posthog.com/api/internal/deactivated-organizations"+ assert post_mock.call_args.kwargs["json"] == {"organization_ids": ["org-1"], "deactivated": True}+ token = post_mock.call_args.kwargs["headers"]["Authorization"].removeprefix("Bearer ")+ payload = jwt.decode(token, "secret123", algorithms=["HS256"], audience="posthog:license-key")+ assert payload["service_action"] == "deactivated_organizations"+ assert "organization_id" not in payload++ @patch(+ "ee.billing.billing_manager.http_session.get",+ return_value=MagicMock(+ status_code=200, json=MagicMock(return_value={"deactivated_organization_ids": ["org-9"]})+ ),+ )+ def test_get_deactivated_organizations_returns_the_ids(self, get_mock):+ result = BillingManager(self.license).get_deactivated_organizations()++ assert result == ["org-9"]+ (url,) = get_mock.call_args.args+ assert url == "https://billing.posthog.com/api/internal/deactivated-organizations"++ @patch(+ "ee.billing.billing_manager.http_session.post",+ return_value=MagicMock(status_code=404, json=MagicMock(return_value={"detail": "not found"})),+ )+ def test_set_organizations_deactivated_raises_on_404(self, post_mock):+ with self.assertRaises(Exception):+ BillingManager(self.license).set_organizations_deactivated(["org-1"], deactivated=True)+++class TestSyncActiveStateReceiver(BaseTest):+ def setUp(self):+ super().setUp()+ is_cloud_patcher = patch("posthog.models.organization.is_cloud", return_value=True)+ self.is_cloud_mock = is_cloud_patcher.start()+ self.addCleanup(is_cloud_patcher.stop)++ @patch("posthog.models.organization._start_billing_active_sync_workflow")+ def test_dispatches_on_is_active_flip(self, dispatch_mock):+ with self.captureOnCommitCallbacks(execute=True):+ self.organization.is_active = False+ self.organization.save(update_fields=["is_active"])++ dispatch_mock.assert_called_once_with(str(self.organization.pk))++ @patch("posthog.models.organization._start_billing_active_sync_workflow")+ def test_does_not_dispatch_on_unrelated_save(self, dispatch_mock):+ with self.captureOnCommitCallbacks(execute=True):+ self.organization.name = "renamed"+ self.organization.save(update_fields=["name"])++ dispatch_mock.assert_not_called()++ @patch("posthog.models.organization._start_billing_active_sync_workflow")+ def test_does_not_dispatch_on_create(self, dispatch_mock):+ with self.captureOnCommitCallbacks(execute=True):+ Organization.objects.create(name="fresh org")++ dispatch_mock.assert_not_called()++ @patch("posthog.models.organization._start_billing_active_sync_workflow")+ def test_does_not_dispatch_outside_cloud(self, dispatch_mock):+ self.is_cloud_mock.return_value = False++ with self.captureOnCommitCallbacks(execute=True):+ self.organization.is_active = False+ self.organization.save(update_fields=["is_active"])++ dispatch_mock.assert_not_called()+++class TestStartBillingActiveSyncWorkflow(BaseTest):+ @patch("posthog.temporal.common.client.async_connect")+ def test_signals_a_running_sync_instead_of_replacing_it(self, connect_mock):+ client = MagicMock()+ client.start_workflow = AsyncMock()+ connect_mock.side_effect = AsyncMock(return_value=client)++ _start_billing_active_sync_workflow(str(self.organization.pk))++ kwargs = client.start_workflow.call_args.kwargs+ assert kwargs["id"] == f"billing-org-active-sync-{self.organization.pk}"+ assert kwargs["id_conflict_policy"] == WorkflowIDConflictPolicy.USE_EXISTING+ assert kwargs["start_signal"] == RESYNC_SIGNAL+ assert "id_reuse_policy" not in kwargs++ @patch("posthog.models.organization.BILLING_ACTIVE_SYNC_DISPATCH_TIMEOUT_SECONDS", 0.01)+ @patch("posthog.models.organization.logger")+ @patch("posthog.temporal.common.client.async_connect")+ def test_gives_up_when_temporal_does_not_answer(self, connect_mock, logger_mock):+ async def _hang():+ await asyncio.sleep(60)++ connect_mock.side_effect = _hang++ _start_billing_active_sync_workflow(str(self.organization.pk))++ logger_mock.warning.assert_called_once()+ assert logger_mock.warning.call_args.args == ("billing_active_state_sync_dispatch_failed",)+++class TestSyncTasks(BaseTest):+ def setUp(self):+ super().setUp()+ self.license = _create_license()++ def _run_with_cloud(self, func, *args):+ with (+ patch("posthog.cloud_utils.is_cloud", return_value=True),+ patch("posthog.cloud_utils.get_cached_instance_license", return_value=self.license),+ ):+ func(*args)++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ def test_sync_task_pushes_the_inverse_of_is_active(self, set_mock):+ self.organization.is_active = False+ self.organization.save(update_fields=["is_active"])++ self._run_with_cloud(sync_organization_active_state, str(self.organization.pk))++ set_mock.assert_called_once_with([str(self.organization.pk)], deactivated=True)++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ def test_sync_task_treats_null_is_active_as_active(self, set_mock):+ self.organization.is_active = None+ self.organization.save(update_fields=["is_active"])++ self._run_with_cloud(sync_organization_active_state, str(self.organization.pk))++ set_mock.assert_called_once_with([str(self.organization.pk)], deactivated=False)++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ def test_sync_task_does_nothing_outside_cloud(self, set_mock):+ with patch("posthog.cloud_utils.is_cloud", return_value=False):+ sync_organization_active_state(str(self.organization.pk))++ set_mock.assert_not_called()++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ @patch("ee.billing.billing_manager.BillingManager.get_deactivated_organizations")+ def test_reconciliation_pushes_deltas_in_both_directions(self, get_mock, set_mock):+ inactive_org = Organization.objects.create(name="blocked org", is_active=False)+ stale_org = Organization.objects.create(name="unblocked org", is_active=True)+ # billing still flags the unblocked org, misses the blocked one, and lists an id+ # this instance does not know (not ours to flip back).+ get_mock.return_value = [str(stale_org.pk), "01900000-0000-0000-0000-000000000000"]++ self._run_with_cloud(reconcile_organization_active_state)++ set_mock.assert_any_call([str(inactive_org.pk)], deactivated=True)+ set_mock.assert_any_call([str(stale_org.pk)], deactivated=False)+ assert set_mock.call_count == 2++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ @patch("ee.billing.billing_manager.BillingManager.get_deactivated_organizations")+ def test_reconciliation_reactivates_null_is_active_orgs(self, get_mock, set_mock):+ null_org = Organization.objects.create(name="null org", is_active=None)+ get_mock.return_value = [str(null_org.pk)]++ self._run_with_cloud(reconcile_organization_active_state)++ set_mock.assert_called_once_with([str(null_org.pk)], deactivated=False)++ @patch("ee.billing.billing_manager.BillingManager.set_organizations_deactivated")+ @patch("ee.billing.billing_manager.BillingManager.get_deactivated_organizations")+ def test_reconciliation_is_quiet_when_aligned(self, get_mock, set_mock):+ inactive_org = Organization.objects.create(name="blocked org", is_active=False)+ get_mock.return_value = [str(inactive_org.pk)]++ self._run_with_cloud(reconcile_organization_active_state)++ set_mock.assert_not_called()diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.pyindex 5e7e393b0972..3debc5ff0f6a 100644--- a/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/test/test_usage.py@@ -235,7 +235,6 @@ class TestUsage(BaseTest):},"billing_plan": "paid","has_active_subscription": True,- "is_deactivated": False,"products": [],"settings": {"autocapture_on": True, "active_destinations": 0},"subscription_level": "paid",diff --git a/ee/hogai/chat_agent/test/test_chat_agent.py b/ee/hogai/chat_agent/test/test_chat_agent.pyindex c21d6aa597d7..88b368127616 100644--- a/ee/hogai/chat_agent/test/test_chat_agent.py+++ b/ee/hogai/chat_agent/test/test_chat_agent.py@@ -1467,7 +1467,6 @@ class TestChatAgent(ClickhouseTestMixin, BaseAssistantTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="startup",has_active_subscription=True,- is_deactivated=False,products=[MaxProductInfo(name="Product Analytics",diff --git a/ee/hogai/tools/read_billing_tool/prompts.py b/ee/hogai/tools/read_billing_tool/prompts.pyindex 672b5ca43c44..3845808cc10a 100644--- a/ee/hogai/tools/read_billing_tool/prompts.py+++ b/ee/hogai/tools/read_billing_tool/prompts.py@@ -21,10 +21,6 @@ The user's current project is {{current_team_name}} (ID: {{current_team_id}}).{{#startup_program_label_previous}}- Previous startup program: {{startup_program_label_previous}}{{/startup_program_label_previous}}-{{#is_deactivated}}-- Status: Account is deactivated-{{/is_deactivated}}-{{#billing_period}}## Billing Period- Period: {{current_period_start}} to {{current_period_end}} ({{interval}}ly billing)diff --git a/ee/hogai/tools/read_billing_tool/test/test_nodes.py b/ee/hogai/tools/read_billing_tool/test/test_nodes.pyindex b45d7391ad25..2cb94695c8bb 100644--- a/ee/hogai/tools/read_billing_tool/test/test_nodes.py+++ b/ee/hogai/tools/read_billing_tool/test/test_nodes.py@@ -51,7 +51,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="paid",has_active_subscription=True,- is_deactivated=False,settings=MaxBillingContextSettings(autocapture_on=True, active_destinations=2),products=[],)@@ -67,7 +66,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="paid",has_active_subscription=True,- is_deactivated=False,billing_period=MaxBillingContextBillingPeriod(current_period_start=str(datetime.date(2023, 1, 1)),current_period_end=str(datetime.date(2023, 1, 31)),@@ -167,7 +165,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="startup",has_active_subscription=True,- is_deactivated=False,startup_program_label="YC W21",billing_period=MaxBillingContextBillingPeriod(current_period_start="2023-01-01",@@ -285,7 +282,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.FREE,billing_plan=None,has_active_subscription=False,- is_deactivated=False,products=[],settings=MaxBillingContextSettings(autocapture_on=False, active_destinations=0),trial=MaxBillingContextTrial(is_active=True, expires_at="2023-02-01", target="teams"),@@ -360,7 +356,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.CUSTOM,billing_plan="enterprise",has_active_subscription=True,- is_deactivated=True, # Deactivated accountstartup_program_label=None,startup_program_label_previous="YC W20", # Previous program but no currentproducts=[@@ -382,9 +377,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):with patch.object(self.tool, "_get_top_events_by_usage", return_value=[]):formatted_string = await self.tool._format_billing_context(billing_context)- # Check deactivated status- self.assertIn("Status: Account is deactivated", formatted_string)-# Check previous startup programself.assertIn("Previous startup program: YC W20", formatted_string)@@ -404,7 +396,6 @@ class TestBillingNode(ClickhouseTestMixin, NonAtomicBaseTest):subscription_level=MaxBillingContextSubscriptionLevel.PAID,billing_plan="scale",has_active_subscription=True,- is_deactivated=False,startup_program_label="Techstars 2023",startup_program_label_previous=None,billing_period=MaxBillingContextBillingPeriod(diff --git a/ee/hogai/tools/read_billing_tool/tool.py b/ee/hogai/tools/read_billing_tool/tool.pyindex b4ff1ed440d0..31ab6198a1a8 100644--- a/ee/hogai/tools/read_billing_tool/tool.py+++ b/ee/hogai/tools/read_billing_tool/tool.py@@ -48,7 +48,6 @@ class ReadBillingTool(MaxSubtool):),"billing_plan": billing_context.billing_plan,"has_active_subscription": billing_context.has_active_subscription,- "is_deactivated": billing_context.is_deactivated,"organization_teams_count": len(self._get_teams_map().keys()),"current_team_name": self._team.name,"current_team_id": self._team.id,diff --git a/frontend/src/layout/today/todayRailSeverity.test.ts b/frontend/src/layout/today/todayRailSeverity.test.tsindex 186f712168db..c1d8dde1e277 100644--- a/frontend/src/layout/today/todayRailSeverity.test.ts+++ b/frontend/src/layout/today/todayRailSeverity.test.ts@@ -6,7 +6,6 @@ describe('todayRailSeverity', () => {test.each<[string, BillingAlertConfig | null, TodayRailSeverity]>([['no alert', null, 'none'],['usage limit reached', { kind: 'usage_limit', status: 'error', title: '' }, 'critical'],- ['organization suspended', { kind: 'deactivated', status: 'error', title: '' }, 'critical'],['usage limit approaching', { kind: 'usage_limit', status: 'info', title: '' }, 'warning'],['trial ending', { kind: 'trial', status: 'info', title: '' }, 'none'],])('rates a billing alert for %s', (_name, alert, expected) => {diff --git a/frontend/src/lib/components/Superpowers/Superpowers.tsx b/frontend/src/lib/components/Superpowers/Superpowers.tsxindex 9612557ed441..1a5014ca957c 100644--- a/frontend/src/lib/components/Superpowers/Superpowers.tsx+++ b/frontend/src/lib/components/Superpowers/Superpowers.tsx@@ -47,7 +47,6 @@ const BILLING_ALERT_OPTIONS: { value: FakeBillingAlert; label: string }[] = [{ value: 'usage_limit_reached', label: 'Usage limit reached' },{ value: 'usage_limit_approaching', label: 'Usage limit approaching' },{ value: 'trial', label: 'Trial ending' },- { value: 'suspended', label: 'Organization suspended' },]function Section({diff --git a/frontend/src/lib/components/Superpowers/buildFakeBillingAlert.ts b/frontend/src/lib/components/Superpowers/buildFakeBillingAlert.tsindex 6e105537d27b..6811a22e646d 100644--- a/frontend/src/lib/components/Superpowers/buildFakeBillingAlert.ts+++ b/frontend/src/lib/components/Superpowers/buildFakeBillingAlert.ts@@ -29,14 +29,6 @@ export function buildFakeBillingAlert(fake: FakeBillingAlert): BillingAlertConfititle: "Your free trial for the Teams plan ends in 3 days. Your service will continue without interruption, and you'll be charged for the Teams plan.",message: 'Questions? Reach out to sales at [email protected].',}- case 'suspended':- return {- kind: 'deactivated',- status: 'error',- title: 'Your organization has been temporarily suspended.',- message: 'Please contact support to reactivate it.',- contactSupport: true,- }case 'none':return null}diff --git a/frontend/src/lib/components/Superpowers/superpowersLogic.ts b/frontend/src/lib/components/Superpowers/superpowersLogic.tsindex 69a06f3d0ad3..a8fe363f1ced 100644--- a/frontend/src/lib/components/Superpowers/superpowersLogic.ts+++ b/frontend/src/lib/components/Superpowers/superpowersLogic.ts@@ -11,7 +11,7 @@ import { userLogic } from 'scenes/userLogic'import type { PreflightStatus, UserType } from '../../../types'export type FakeStatusOverride = 'none' | 'operational' | 'degraded_performance' | 'partial_outage' | 'major_outage'-export type FakeBillingAlert = 'none' | 'usage_limit_reached' | 'usage_limit_approaching' | 'trial' | 'suspended'+export type FakeBillingAlert = 'none' | 'usage_limit_reached' | 'usage_limit_approaching' | 'trial'// The PostHog Team cohort in PostHog's own project excludes people with this person property set to true.export const EXCLUDED_FROM_POSTHOG_TEAM_COHORT_PROPERTY = 'excluded_from_posthog_team_cohort'diff --git a/frontend/src/mocks/fixtures/_billing.tsx b/frontend/src/mocks/fixtures/_billing.tsxindex b1b5106dc5e4..c6f113016147 100644--- a/frontend/src/mocks/fixtures/_billing.tsx+++ b/frontend/src/mocks/fixtures/_billing.tsx@@ -6,7 +6,6 @@ import { defaultPlatformAddons } from './_billing_platform_addons'export const billingJson: BillingType = {customer_id: 'cus_Pg7PIL8MsKi6bx',- deactivated: false,has_active_subscription: true,billing_period: {current_period_start: dayjs('2024-03-07T22:54:32Z'),diff --git a/frontend/src/mocks/fixtures/_billing_unsubscribed.tsx b/frontend/src/mocks/fixtures/_billing_unsubscribed.tsxindex 94659653fa84..fd5416e726ae 100644--- a/frontend/src/mocks/fixtures/_billing_unsubscribed.tsx+++ b/frontend/src/mocks/fixtures/_billing_unsubscribed.tsx@@ -7,7 +7,6 @@ export const billingUnsubscribedJson: BillingType = {plan: LicensePlan.Dev},customer_id: "cus_OfAfHKf4QiD0rs",- deactivated: false,has_active_subscription: false,billing_period: {current_period_start: dayjs("2023-11-17T23:19:00.444Z"),diff --git a/frontend/src/mocks/fixtures/_billing_with_100_percent_discount.json b/frontend/src/mocks/fixtures/_billing_with_100_percent_discount.jsonindex 9edf71995f75..a63dd629da43 100644--- a/frontend/src/mocks/fixtures/_billing_with_100_percent_discount.json+++ b/frontend/src/mocks/fixtures/_billing_with_100_percent_discount.json@@ -3,7 +3,6 @@"plan": "cloud"},"customer_id": "cus_234",- "deactivated": false,"has_active_subscription": true,"billing_period": {"current_period_start": "2023-04-13T04:41:02Z",diff --git a/frontend/src/mocks/fixtures/_billing_with_billing_limits.json b/frontend/src/mocks/fixtures/_billing_with_billing_limits.jsonindex 06a6832a50b7..e010561eea79 100644--- a/frontend/src/mocks/fixtures/_billing_with_billing_limits.json+++ b/frontend/src/mocks/fixtures/_billing_with_billing_limits.json@@ -3,7 +3,6 @@"plan": "dev"},"customer_id": "cus_Q2Ei7TeJ3Y0uuU",- "deactivated": false,"has_active_subscription": true,"billing_period": {"current_period_start": "2024-05-08T18:56:04Z",diff --git a/frontend/src/mocks/fixtures/_billing_with_credits.json b/frontend/src/mocks/fixtures/_billing_with_credits.jsonindex 7b46006dc167..e3197fabf522 100644--- a/frontend/src/mocks/fixtures/_billing_with_credits.json+++ b/frontend/src/mocks/fixtures/_billing_with_credits.json@@ -3,7 +3,6 @@"plan": "cloud"},"customer_id": "cus_234",- "deactivated": false,"has_active_subscription": true,"billing_period": {"current_period_start": "2023-04-13T04:41:02Z",diff --git a/frontend/src/mocks/fixtures/_billing_with_discount.json b/frontend/src/mocks/fixtures/_billing_with_discount.jsonindex ecd2020d1312..0df98eff39d7 100644--- a/frontend/src/mocks/fixtures/_billing_with_discount.json+++ b/frontend/src/mocks/fixtures/_billing_with_discount.json@@ -3,7 +3,6 @@"plan": "cloud"},"customer_id": "cus_234",- "deactivated": false,"has_active_subscription": true,"billing_period": {"current_period_start": "2023-04-13T04:41:02Z",diff --git a/frontend/src/mocks/fixtures/_billing_with_flat_fee.json b/frontend/src/mocks/fixtures/_billing_with_flat_fee.jsonindex 5566b3c217db..8f0b58d1a660 100644--- a/frontend/src/mocks/fixtures/_billing_with_flat_fee.json+++ b/frontend/src/mocks/fixtures/_billing_with_flat_fee.json@@ -3,7 +3,6 @@"plan": "cloud"},"customer_id": "cus_1234",- "deactivated": false,"has_active_subscription": true,"billing_period": {"current_period_start": "2023-10-13T09:54:24Z",diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex f30706e56d5c..4c70ace4a388 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -37705,9 +37705,6 @@"has_active_subscription": {"type": "boolean"},- "is_deactivated": {- "type": "boolean"- },"products": {"items": {"$ref": "#/definitions/MaxProductInfo"diff --git a/frontend/src/scenes/billing/billingLogic.tsx b/frontend/src/scenes/billing/billingLogic.tsxindex c10a4e7766b2..1a40247908e5 100644--- a/frontend/src/scenes/billing/billingLogic.tsx+++ b/frontend/src/scenes/billing/billingLogic.tsx@@ -67,7 +67,7 @@ const getFirstProductFromProductsParam = (productsParam: unknown): ProductKey |}export interface BillingAlertConfig {- kind?: 'trial' | 'deactivated' | 'usage_limit'+ kind?: 'trial' | 'usage_limit'status: 'info' | 'warning' | 'error'title: stringmessage?: string@@ -1694,17 +1694,6 @@ export const billingLogic = kea<billingLogicType>([return}- if (values.billing.deactivated) {- actions.setBillingAlert({- kind: 'deactivated',- status: 'error',- title: 'Your organization has been temporarily suspended.',- message: 'Please contact support to reactivate it.',- contactSupport: true,- })- return- }-const billingPeriodEnd = values.billing.billing_period?.current_period_end?.format('YYYY-MM-DD')const productsAtOrOverLimit =@@ -1835,7 +1824,6 @@ export const billingLogic = kea<billingLogicType>([const payload: { [key: string]: any } = {has_billing_plan: !!values.billing.has_active_subscription,free_trial_until: values.billing.free_trial_until?.toISOString(),- customer_deactivated: values.billing.deactivated,current_total_amount_usd: values.billing.current_total_amount_usd,}if (values.billing.products) {diff --git a/frontend/src/scenes/max/maxBillingContextLogic.test.ts b/frontend/src/scenes/max/maxBillingContextLogic.test.tsindex 90f279204698..4921f3fa5bb6 100644--- a/frontend/src/scenes/max/maxBillingContextLogic.test.ts+++ b/frontend/src/scenes/max/maxBillingContextLogic.test.ts@@ -16,7 +16,6 @@ const mockBilling: BillingType = {subscription_level: 'paid',has_active_subscription: true,billing_plan: BillingPlan.Paid,- deactivated: false,current_total_amount_usd: '100.00',projected_total_amount_usd: '150.00',projected_total_amount_usd_after_discount: '135.00',@@ -317,7 +316,6 @@ describe('maxBillingContextLogic', () => {has_active_subscription: true,subscription_level: 'paid',billing_plan: 'paid',- is_deactivated: false,total_current_amount_usd: '100.00',projected_total_amount_usd: '150.00',projected_total_amount_usd_after_discount: '135.00',diff --git a/frontend/src/scenes/max/maxBillingContextLogic.tsx b/frontend/src/scenes/max/maxBillingContextLogic.tsxindex b924556b1e99..e6c48df01b78 100644--- a/frontend/src/scenes/max/maxBillingContextLogic.tsx+++ b/frontend/src/scenes/max/maxBillingContextLogic.tsx@@ -85,7 +85,6 @@ export interface MaxBillingContext {has_active_subscription: booleansubscription_level: MaxBillingContextSubscriptionLevelbilling_plan: string | null- is_deactivated?: boolean// Products informationproducts: MaxProductInfo[]@@ -213,7 +212,6 @@ export const billingToMaxContext = ((billing.subscription_level as MaxBillingContextSubscriptionLevel) ||MaxBillingContextSubscriptionLevel.FREE,billing_plan: billing.billing_plan || null,- is_deactivated: billing.deactivated,products: maxProducts,total_current_amount_usd: billing.current_total_amount_usd,projected_total_amount_usd: billing.projected_total_amount_usd,diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 7ff47ef082a5..76729a4bee9b 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -2473,7 +2473,6 @@ export interface BillingType {free_trial_until?: Dayjsstripe_portal_url?: stringexternal_billing_provider_invoices_url?: string- deactivated?: booleancurrent_total_amount_usd?: stringcurrent_total_amount_usd_after_discount?: stringprojected_total_amount_usd?: stringdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 2904f30043dd..3ff9928703ab 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -42,6 +42,10 @@ from posthog.temporal.backfill_materialized_property import (ACTIVITIES as BACKFILL_MATERIALIZED_PROPERTY_ACTIVITIES,BackfillMaterializedPropertiesBatchWorkflow,)+from posthog.temporal.billing_active_sync import (+ ACTIVITIES as BILLING_ACTIVE_SYNC_ACTIVITIES,+ WORKFLOWS as BILLING_ACTIVE_SYNC_WORKFLOWS,+)from posthog.temporal.cleanup_property_definitions import (ACTIVITIES as CLEANUP_PROPDEFS_ACTIVITIES,WORKFLOWS as CLEANUP_PROPDEFS_WORKFLOWS,@@ -512,11 +516,16 @@ _task_queue_specs = [),(settings.BILLING_TASK_QUEUE,- QUOTA_LIMITING_WORKFLOWS + SALESFORCE_ENRICHMENT_WORKFLOWS + USAGE_REPORTS_WORKFLOWS + BILLING_ALERTS_WORKFLOWS,+ QUOTA_LIMITING_WORKFLOWS+ + SALESFORCE_ENRICHMENT_WORKFLOWS+ + USAGE_REPORTS_WORKFLOWS+ + BILLING_ALERTS_WORKFLOWS+ + BILLING_ACTIVE_SYNC_WORKFLOWS,QUOTA_LIMITING_ACTIVITIES+ SALESFORCE_ENRICHMENT_ACTIVITIES+ USAGE_REPORTS_ACTIVITIES- + BILLING_ALERTS_ACTIVITIES,+ + BILLING_ALERTS_ACTIVITIES+ + BILLING_ACTIVE_SYNC_ACTIVITIES,),(settings.VIDEO_EXPORT_TASK_QUEUE,diff --git a/posthog/models/organization.py b/posthog/models/organization.pyindex 053d6e44e1bb..014689b96114 100644--- a/posthog/models/organization.py+++ b/posthog/models/organization.py@@ -739,6 +739,53 @@ def invalidate_llm_gateway_quota_cache_on_active_state_change(sender, instance:transaction.on_commit(_project_gateway_quota)+@receiver(post_save, sender=Organization)+def sync_active_state_to_billing_on_change(sender, instance: Organization, created: bool, **kwargs):+ if created or not instance._is_active_changed or not is_cloud():+ return++ organization_id = str(instance.pk)+ transaction.on_commit(lambda: _start_billing_active_sync_workflow(organization_id))+++BILLING_ACTIVE_SYNC_DISPATCH_TIMEOUT_SECONDS = 5+++def _start_billing_active_sync_workflow(organization_id: str) -> None:+ # Imports deferred to keep the Temporal stack off the model import path.+ import asyncio++ from temporalio.common import WorkflowIDConflictPolicy++ from posthog.temporal.billing_active_sync.sync_organization_active_state import (+ RESYNC_SIGNAL,+ SyncOrganizationActiveStateInputs,+ SyncOrganizationActiveStateWorkflow,+ )+ from posthog.temporal.common.client import async_connect++ async def _connect_and_start() -> None:+ client = await asyncio.wait_for(async_connect(), timeout=BILLING_ACTIVE_SYNC_DISPATCH_TIMEOUT_SECONDS)+ await asyncio.wait_for(+ client.start_workflow(+ SyncOrganizationActiveStateWorkflow.run,+ SyncOrganizationActiveStateInputs(organization_id=organization_id),+ id=f"billing-org-active-sync-{organization_id}",+ task_queue=settings.BILLING_TASK_QUEUE,+ # A running sync gets the signal and syncs again, so two POSTs for one org never race.+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ start_signal=RESYNC_SIGNAL,+ ),+ timeout=BILLING_ACTIVE_SYNC_DISPATCH_TIMEOUT_SECONDS,+ )++ try:+ asyncio.run(_connect_and_start())+ except Exception:+ # The nightly reconciliation realigns billing; never fail the org save.+ logger.warning("billing_active_state_sync_dispatch_failed", organization_id=organization_id, exc_info=True)++class OrganizationMembership(ModelActivityMixin, UUIDTModel):class Level(models.IntegerChoices):"""Keep in sync with TeamMembership.Level (only difference being projects not having an Owner)."""diff --git a/posthog/schema.py b/posthog/schema.pyindex f0b4860fdd45..19f22cdb8f6e 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -20521,7 +20521,6 @@ class MaxBillingContext(BaseModel):billing_period: MaxBillingContextBillingPeriod | None = Nonebilling_plan: str | None = Nonehas_active_subscription: bool- is_deactivated: bool | None = Noneproducts: list[MaxProductInfo]projected_total_amount_usd: str | None = Noneprojected_total_amount_usd_after_discount: str | None = Nonediff --git a/posthog/temporal/billing_active_sync/__init__.py b/posthog/temporal/billing_active_sync/__init__.pynew file mode 100644index 000000000000..cba60aaa59d8--- /dev/null+++ b/posthog/temporal/billing_active_sync/__init__.py@@ -0,0 +1,16 @@+from posthog.temporal.billing_active_sync.sync_organization_active_state import (+ ReconcileOrganizationActiveStateWorkflow,+ SyncOrganizationActiveStateWorkflow,+ reconcile_organization_active_state_activity,+ sync_organization_active_state_activity,+)++WORKFLOWS = [+ SyncOrganizationActiveStateWorkflow,+ ReconcileOrganizationActiveStateWorkflow,+]++ACTIVITIES = [+ sync_organization_active_state_activity,+ reconcile_organization_active_state_activity,+]diff --git a/posthog/temporal/billing_active_sync/sync_organization_active_state.py b/posthog/temporal/billing_active_sync/sync_organization_active_state.pynew file mode 100644index 000000000000..67ea7f94d30a--- /dev/null+++ b/posthog/temporal/billing_active_sync/sync_organization_active_state.py@@ -0,0 +1,172 @@+import json+from datetime import timedelta++import structlog+from temporalio import activity, common, workflow++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception+from posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.common.heartbeat import Heartbeater++logger = structlog.get_logger()+++@frozen+class SyncOrganizationActiveStateInputs:+ organization_id: str+++@frozen+class ReconcileOrganizationActiveStateInputs:+ pass+++def sync_organization_active_state(organization_id: str) -> None:+ """Mirror Organization.is_active into billing's deactivated flag (forecast exclusion).++ Reads the organization inside this function so every retry attempt sees the latest+ is_active value.+ """+ from posthog.cloud_utils import get_cached_instance_license, is_cloud+ from posthog.models import Organization++ from ee.billing.billing_manager import BillingManager++ if not is_cloud():+ return+ license = get_cached_instance_license()+ if license is None:+ return++ organization = Organization.objects.get(id=organization_id)+ # is_active is nullable; the rest of the app treats only an explicit False as deactivated.+ BillingManager(license, None).set_organizations_deactivated(+ [str(organization.id)], deactivated=organization.is_active is False+ )+++def reconcile_organization_active_state() -> None:+ """Nightly sweep: realign billing's deactivated flags with Organization.is_active.++ The post_save signal is the real-time path; this catches missed flips (worker loss,+ writes that skip signals). Organization.is_active is authoritative in both directions,+ so a flag set only in billing for an org that is active here is removed.+ """+ from posthog.cloud_utils import get_cached_instance_license, is_cloud+ from posthog.models import Organization++ from ee.billing.billing_manager import BillingManager++ if not is_cloud():+ return+ license = get_cached_instance_license()+ if license is None:+ return++ manager = BillingManager(license, None)+ billing_deactivated = set(manager.get_deactivated_organizations())+ # Nullable is_active: only an explicit False is deactivated, so null lands on the reactivation side.+ inactive = {str(pk) for pk in Organization.objects.filter(is_active=False).values_list("id", flat=True)}++ to_deactivate = sorted(inactive - billing_deactivated)+ # An id this instance does not know (e.g. a deleted org) is not ours to flip back.+ to_reactivate = sorted(+ str(pk)+ for pk in Organization.objects.filter(id__in=billing_deactivated)+ .exclude(is_active=False)+ .values_list("id", flat=True)+ )+ # Billing caps a batch at 1000 organization ids.+ batch_size = 500+ for batch_start in range(0, len(to_deactivate), batch_size):+ manager.set_organizations_deactivated(to_deactivate[batch_start : batch_start + batch_size], deactivated=True)+ for batch_start in range(0, len(to_reactivate), batch_size):+ manager.set_organizations_deactivated(to_reactivate[batch_start : batch_start + batch_size], deactivated=False)++[email protected](name="sync-organization-active-state")+async def sync_organization_active_state_activity(inputs: SyncOrganizationActiveStateInputs) -> None:+ async with Heartbeater():+ try:+ await database_sync_to_async_pool(sync_organization_active_state)(inputs.organization_id)+ except Exception as e:+ capture_exception(e)+ # Raise exception without large context to avoid "Failure exceeds size limit"+ raise Exception(f"Organization active state sync failed: {type(e).__name__}: {str(e)[:200]}")++[email protected](name="reconcile-organization-active-state")+async def reconcile_organization_active_state_activity(_inputs: ReconcileOrganizationActiveStateInputs) -> None:+ async with Heartbeater():+ try:+ await database_sync_to_async_pool(reconcile_organization_active_state)()+ except Exception as e:+ capture_exception(e)+ # Raise exception without large context to avoid "Failure exceeds size limit"+ raise Exception(f"Organization active state reconciliation failed: {type(e).__name__}: {str(e)[:200]}")+++RESYNC_SIGNAL = "resync"++[email protected](name="sync-organization-active-state-to-billing")+class SyncOrganizationActiveStateWorkflow(PostHogWorkflow):+ """One run per organization; a flip during a run signals it to sync again, so no stale POST lands last."""++ def __init__(self) -> None:+ self._resync_requested = False++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SyncOrganizationActiveStateInputs:+ """Parse inputs from the management command CLI."""+ loaded = json.loads(inputs[0])+ return SyncOrganizationActiveStateInputs(**loaded)++ @workflow.signal(name=RESYNC_SIGNAL)+ def resync(self) -> None:+ self._resync_requested = True++ @workflow.run+ async def run(self, inputs: SyncOrganizationActiveStateInputs) -> None:+ while True:+ self._resync_requested = False+ await workflow.execute_activity(+ sync_organization_active_state_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=common.RetryPolicy(+ initial_interval=timedelta(seconds=10),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(minutes=5),+ maximum_attempts=6,+ ),+ heartbeat_timeout=timedelta(minutes=1),+ )+ if not self._resync_requested:+ return++[email protected](name="reconcile-organization-active-state-to-billing")+class ReconcileOrganizationActiveStateWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> ReconcileOrganizationActiveStateInputs:+ """Parse inputs from the management command CLI."""+ loaded = json.loads(inputs[0])+ return ReconcileOrganizationActiveStateInputs(**loaded)++ @workflow.run+ async def run(self, inputs: ReconcileOrganizationActiveStateInputs) -> None:+ await workflow.execute_activity(+ reconcile_organization_active_state_activity,+ inputs,+ start_to_close_timeout=timedelta(minutes=15),+ retry_policy=common.RetryPolicy(+ initial_interval=timedelta(minutes=1),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(minutes=10),+ maximum_attempts=4,+ ),+ heartbeat_timeout=timedelta(minutes=2),+ )diff --git a/posthog/temporal/billing_active_sync/tests/__init__.py b/posthog/temporal/billing_active_sync/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/temporal/billing_active_sync/tests/test_sync_organization_active_state.py b/posthog/temporal/billing_active_sync/tests/test_sync_organization_active_state.pynew file mode 100644index 000000000000..cfb46263020d--- /dev/null+++ b/posthog/temporal/billing_active_sync/tests/test_sync_organization_active_state.py@@ -0,0 +1,59 @@+import uuid++import pytest++from temporalio import activity+from temporalio.client import Client+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.temporal.billing_active_sync.sync_organization_active_state import (+ RESYNC_SIGNAL,+ SyncOrganizationActiveStateInputs,+ SyncOrganizationActiveStateWorkflow,+)+++async def _run_sync_workflow(signals_during_first_sync: int) -> int:+ calls: list[str] = []+ workflow_id = str(uuid.uuid4())+ client: Client | None = None++ @activity.defn(name="sync-organization-active-state")+ async def stub_sync(inputs: SyncOrganizationActiveStateInputs) -> None:+ calls.append(inputs.organization_id)+ if len(calls) == 1:+ assert client is not None+ handle = client.get_workflow_handle(workflow_id)+ for _ in range(signals_during_first_sync):+ await handle.signal(RESYNC_SIGNAL)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ client = env.client+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SyncOrganizationActiveStateWorkflow],+ activities=[stub_sync],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ SyncOrganizationActiveStateWorkflow.run,+ SyncOrganizationActiveStateInputs(organization_id="org-1"),+ id=workflow_id,+ task_queue=task_queue,+ start_signal=RESYNC_SIGNAL,+ )+ await handle.result()+ return len(calls)+++class TestSyncOrganizationActiveStateWorkflow:+ @pytest.mark.asyncio+ async def test_syncs_once_without_a_flip_during_the_run(self) -> None:+ assert await _run_sync_workflow(signals_during_first_sync=0) == 1++ @pytest.mark.asyncio+ async def test_flips_during_a_run_cause_exactly_one_more_sync(self) -> None:+ assert await _run_sync_workflow(signals_during_first_sync=3) == 2diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex bfdca3bf59ce..0da7b6588581 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -826,6 +826,51 @@ async def create_finalize_usage_reports_schedule(client: Client):)+async def create_reconcile_organization_active_state_schedule(client: Client):+ """Nightly realignment of billing's deactivated flags with Organization.is_active, 04:45 UTC.++ The Organization post_save signal is the real-time path; this sweep catches missed+ flips (dispatch failures, writes that skip signals). Same slot as the Celery schedule+ it replaces.+ """+ from posthog.temporal.billing_active_sync.sync_organization_active_state import (+ ReconcileOrganizationActiveStateInputs,+ )++ reconcile_schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ "reconcile-organization-active-state-to-billing",+ asdict(ReconcileOrganizationActiveStateInputs()),+ id="reconcile-organization-active-state-schedule",+ task_queue=settings.BILLING_TASK_QUEUE,+ retry_policy=common.RetryPolicy(+ maximum_attempts=3,+ initial_interval=timedelta(minutes=5),+ ),+ ),+ spec=ScheduleSpec(+ calendars=[+ ScheduleCalendarSpec(+ comment="Daily at 04:45 UTC",+ hour=[ScheduleRange(start=4, end=4)],+ minute=[ScheduleRange(start=45, end=45)],+ )+ ]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, "reconcile-organization-active-state-schedule"):+ await a_update_schedule(client, "reconcile-organization-active-state-schedule", reconcile_schedule)+ else:+ await a_create_schedule(+ client,+ "reconcile-organization-active-state-schedule",+ reconcile_schedule,+ trigger_immediately=False,+ )++async def create_count_all_playlists_schedule(client: Client):"""Create or update the schedule for the playlist counting workflow.@@ -994,6 +1039,7 @@ if settings.CLOUD_DEPLOYMENT:schedules.append(create_replay_vision_gemini_cleanup_sweep_schedule)schedules.append(create_run_usage_reports_schedule)schedules.append(create_finalize_usage_reports_schedule)+ schedules.append(create_reconcile_organization_active_state_schedule)if should_register_checkpoint_compaction_schedule():schedules.append(create_checkpoint_compaction_schedule)# The sweep re-fetches each region's own orgs from Harmonic, and only US and EU carry the key.diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txtindex 1b942bb09921..e40c097b22f6 100644--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt@@ -143,6 +143,7 @@ post_save:posthog.models.file_system.signal_handlers.access_control_createdpost_save:posthog.models.global_rate_limit_threshold_config.update_redis_thresholds_on_savepost_save:posthog.models.organization.cache_organization_session_agepost_save:posthog.models.organization.invalidate_llm_gateway_quota_cache_on_active_state_change+post_save:posthog.models.organization.sync_active_state_to_billing_on_changepost_save:posthog.models.organization.sync_billing_on_membership_savepost_save:posthog.models.product_intent.product_intent._invalidate_product_intents_on_savepost_save:posthog.models.remote_config.error_tracking_suppression_rule_saveddiff --git a/products/billing/frontend/generated/api.schemas.ts b/products/billing/frontend/generated/api.schemas.tsindex 1201c4de3b5d..e794dd1b5749 100644--- a/products/billing/frontend/generated/api.schemas.ts+++ b/products/billing/frontend/generated/api.schemas.ts@@ -22,7 +22,6 @@ export interface BillingOverviewResponseApi {/** @nullable */subscription_level?: string | nullhas_active_subscription?: boolean- deactivated?: booleanis_annual_plan_customer?: boolean/** @nullable */free_trial_until?: string | null@@ -1156,7 +1155,6 @@ export interface BillingSubscriptionApi {/** @nullable */billing_plan: string | nullbilling_provider: BillingProviderEnumApi | null- deactivated: booleanis_annual_plan_customer: booleanbilling_period: BillingPeriodApi | nulltrial: TrialApi | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex ea31c948fa42..0ee542a721ce 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -18233,7 +18233,6 @@ export namespace Schemas {/** @nullable */subscription_level?: string | null;has_active_subscription?: boolean;- deactivated?: boolean;is_annual_plan_customer?: boolean;/** @nullable */free_trial_until?: string | null;@@ -18493,7 +18492,6 @@ export namespace Schemas {/** @nullable */billing_plan: string | null;billing_provider: BillingProviderEnum | null;- deactivated: boolean;is_annual_plan_customer: boolean;billing_period: BillingPeriod | null;trial: Trial | null;