: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
fix(billing): remove legacy license endpoints and usage task (#102898)
Pawel Cebulaa7a6170b83c0
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.mdindex 008c5a781389..3d946c2074fd 100644--- a/docs/published/handbook/engineering/developing-locally.md+++ b/docs/published/handbook/engineering/developing-locally.md@@ -557,6 +557,8 @@ The AI assistant uses the MCP tools to query phrocs directly and provide you witIf you're a PostHog employee, you can get access to paid features on your local instance to make development easier. [Learn how to do so in our internal billing guide](https://github.com/PostHog/billing?tab=readme-ov-file#licensing-your-local-instance).+Instance licenses are configured through `PATCH /api/billing/license/`. The legacy `/api/license/` activation and deactivation endpoints are no longer available.+## Extra: Resetting your local databaseIf you need to start fresh with a clean database (for example, if your local data is corrupted or you want to test the initial setup), follow these steps:diff --git a/ee/api/license.py b/ee/api/license.pydeleted file mode 100644index 661120cd96d7..000000000000--- a/ee/api/license.py+++ /dev/null@@ -1,95 +0,0 @@-from django.db.models import QuerySet-from django.utils.timezone import now--import requests-import posthoganalytics-from rest_framework import mixins, request, serializers, viewsets-from rest_framework.permissions import IsAuthenticated-from rest_framework.response import Response--from posthog.cloud_utils import is_cloud-from posthog.event_usage import groups-from posthog.models.organization import Organization-from posthog.models.team import Team-from posthog.permissions import IsStaffUser, TimeSensitiveActionPermission--from ee.models.license import License, LicenseError---class LicenseSerializer(serializers.ModelSerializer):- class Meta:- model = License- fields = [- "id",- "plan",- "key",- "valid_until",- "created_at",- ]- read_only_fields = ["plan", "valid_until"]- extra_kwargs = {"key": {"write_only": True}}-- def validate(self, data):- validation = requests.post(- "https://license.posthog.com/licenses/activate", data={"key": data["key"]}, timeout=10- )- resp = validation.json()- user = self.context["request"].user- if not validation.ok:- posthoganalytics.capture(- "license key activation failure",- distinct_id=user.distinct_id,- properties={"error": validation.content},- groups=groups(user.current_organization, user.current_team),- )- raise LicenseError(resp["code"], resp["detail"])-- posthoganalytics.capture(- "license key activation success",- distinct_id=user.distinct_id,- properties={},- groups=groups(user.current_organization, user.current_team),- )- data["valid_until"] = resp["valid_until"]- data["plan"] = resp["plan"]- return data---class LicenseViewSet(- mixins.ListModelMixin,- mixins.RetrieveModelMixin,- mixins.CreateModelMixin,- viewsets.GenericViewSet,-):- queryset = License.objects.all()- serializer_class = LicenseSerializer- permission_classes = [IsAuthenticated, IsStaffUser, TimeSensitiveActionPermission]-- def get_queryset(self) -> QuerySet:- if is_cloud():- return License.objects.none()-- return super().get_queryset()-- def destroy(self, request: request.Request, *args, **kwargs) -> Response:- license = self.get_object()- validation = requests.post(- "https://license.posthog.com/licenses/deactivate", data={"key": license.key}, timeout=10- )- validation.raise_for_status()-- has_another_valid_license = License.objects.filter(valid_until__gte=now()).exclude(pk=license.pk).exists()- if not has_another_valid_license:- teams = Team.objects.exclude(is_demo=True).order_by("pk")[1:]- for team in teams:- team.delete()-- # delete any organization where we've deleted all teams- # there is no way in the interface to create multiple organizations so we won't bother informing people that this is happening- for organization in Organization.objects.all():- if organization.teams.count() == 0:- organization.delete()-- license.delete()-- return Response({"ok": True})diff --git a/ee/api/test/test_license.py b/ee/api/test/test_license.pydeleted file mode 100644index 550e9b373807..000000000000--- a/ee/api/test/test_license.py+++ /dev/null@@ -1,269 +0,0 @@-import datetime-from zoneinfo import ZoneInfo--import pytest-import time_machine-from unittest.mock import Mock, patch--from django.utils import timezone-from django.utils.timezone import now--from dateutil.relativedelta import relativedelta-from parameterized import parameterized-from rest_framework import status--from posthog.models.organization import Organization-from posthog.models.team import Team--from ee.api.test.base import APILicensedTest-from ee.models.license import License---class TestLicenseAPI(APILicensedTest):- def setUp(self):- super().setUp()- self.user.is_staff = True- self.user.save()-- @pytest.mark.skip_on_multitenancy- def test_can_list_and_retrieve_licenses(self):- response = self.client.get("/api/license")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- response_data = response.json()- self.assertEqual(response_data["count"], 1)- self.assertEqual(response_data["results"][0]["plan"], "enterprise")- self.assertNotIn("key", response_data["results"][0])- self.assertEqual(- response_data["results"][0]["valid_until"],- datetime.datetime(2038, 1, 19, 3, 14, 7, tzinfo=ZoneInfo("UTC")).isoformat().replace("+00:00", "Z"),- )-- retrieve_response = self.client.get(f"/api/license/{response_data['results'][0]['id']}")- self.assertEqual(retrieve_response.status_code, status.HTTP_200_OK)- self.assertEqual(retrieve_response.json(), response_data["results"][0])-- @parameterized.expand(["list", "retrieve", "create"])- @patch("ee.api.license.requests.post")- @pytest.mark.skip_on_multitenancy- def test_license_key_is_write_only(self, method, patch_post):- mock = Mock()- mock.json.return_value = {- "plan": "enterprise",- "valid_until": (timezone.now() + datetime.timedelta(days=10)).isoformat().replace("+00:00", "Z"),- }- patch_post.return_value = mock-- if method == "list":- response_data = self.client.get("/api/license").json()["results"][0]- elif method == "retrieve":- response_data = self.client.get(f"/api/license/{self.license.pk}").json()- else:- response_data = self.client.post("/api/license", {"key": "test_key"}).json()-- self.assertNotIn("key", response_data)-- @patch("ee.api.license.requests.post")- @pytest.mark.skip_on_multitenancy- def test_can_create_license(self, patch_post):- valid_until = timezone.now() + datetime.timedelta(days=10)- mock = Mock()- mock.json.return_value = {- "plan": "enterprise",- "valid_until": valid_until.isoformat().replace("+00:00", "Z"),- }- patch_post.return_value = mock- count = License.objects.count()-- response = self.client.post("/api/license", {"key": "newer_license_1"})- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- response_data = response.json()- self.assertEqual(response_data["plan"], "enterprise")- self.assertNotIn("key", response_data)-- self.assertEqual(License.objects.count(), count + 1)- license = License.objects.get(id=response_data["id"])- self.assertEqual(license.key, "newer_license_1")- self.assertEqual(license.valid_until, valid_until)-- @patch("ee.api.license.requests.post")- @pytest.mark.skip_on_multitenancy- def test_friendly_error_when_license_key_is_invalid(self, patch_post):- mock = Mock()- mock.ok = False- mock.json.return_value = {- "type": "validation_error",- "code": "invalid_key",- "detail": "Provided key is invalid.",- "attr": "key",- }- patch_post.return_value = mock- count = License.objects.count()-- response = self.client.post("/api/license", {"key": "invalid_key"})- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(- response.json(),- {- "type": "license_error",- "code": "invalid_key",- "detail": "Provided key is invalid.",- "attr": None,- },- )-- self.assertEqual(License.objects.count(), count)-- @pytest.mark.skip_on_multitenancy- def test_highest_activated_license_is_used_after_upgrade(self):- with time_machine.travel("2022-06-01T12:00:00.000Z", tick=False):- License.objects.create(- key="old",- plan="scale",- valid_until=datetime.datetime.now() + datetime.timedelta(days=30),- )- with time_machine.travel("2022-06-03T12:00:00.000Z", tick=False):- License.objects.create(- key="new",- plan="enterprise",- valid_until=datetime.datetime.now() + datetime.timedelta(days=30),- )-- with time_machine.travel("2022-06-03T13:00:00.000Z", tick=False):- first_valid = License.objects.first_valid()-- self.assertIsInstance(first_valid, License)- self.assertEqual(first_valid.plan, "enterprise") # type: ignore-- @pytest.mark.skip_on_multitenancy- def test_highest_activated_license_is_used_after_renewal_to_lower(self):- with time_machine.travel("2022-06-01T12:00:00.000Z", tick=False):- License.objects.create(- key="new",- plan="enterprise",- valid_until=datetime.datetime.now() + datetime.timedelta(days=30),- )- with time_machine.travel("2022-06-27T12:00:00.000Z", tick=False):- License.objects.create(- key="old",- plan="scale",- valid_until=datetime.datetime.now() + datetime.timedelta(days=30),- )-- with time_machine.travel("2022-06-27T13:00:00.000Z", tick=False):- first_valid = License.objects.first_valid()-- self.assertIsInstance(first_valid, License)- self.assertEqual(first_valid.plan, "enterprise") # type: ignore-- @pytest.mark.skip_on_multitenancy- @patch("ee.api.license.requests.post")- def test_can_cancel_license(self, patch_post):- to_be_deleted = Team.objects.create(organization=self.organization)- not_to_be_deleted = Team.objects.create(organization=self.organization, is_demo=True) # don't delete- other_org = Organization.objects.create()- from_another_organisation = Team.objects.create(organization=other_org)-- self.assertEqual(Team.objects.count(), 4)- self.assertEqual(- sorted([team.id for team in Team.objects.all()]),- sorted(- [- self.team.pk,- to_be_deleted.pk,- not_to_be_deleted.pk,- from_another_organisation.pk,- ]- ),- )-- mock = Mock()- mock.json.return_value = {"ok": True}- patch_post.return_value = mock- response = self.client.delete(f"/api/license/{self.license.pk}/")- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)- self.assertEqual(Team.objects.count(), 2) # deleted two teams- self.assertEqual(- sorted([team.id for team in Team.objects.all()]),- sorted([self.team.pk, not_to_be_deleted.pk]),- )- self.assertEqual(Organization.objects.count(), 1)-- @parameterized.expand(["list", "retrieve", "create", "destroy"])- @pytest.mark.skip_on_multitenancy- @patch("ee.api.license.requests.post")- def test_non_staff_user_cannot_access_license_endpoints(self, action, patch_post):- self.user.is_staff = False- self.user.save()-- Team.objects.create(organization=self.organization)- Team.objects.create(organization=self.organization, is_demo=True)- other_org = Organization.objects.create()- Team.objects.create(organization=other_org)-- teams_before = set(Team.objects.values_list("pk", flat=True))- orgs_before = set(Organization.objects.values_list("pk", flat=True))- license_pk = self.license.pk-- mock = Mock()- mock.json.return_value = {"ok": True}- patch_post.return_value = mock-- if action == "list":- response = self.client.get("/api/license")- elif action == "retrieve":- response = self.client.get(f"/api/license/{license_pk}")- elif action == "create":- response = self.client.post("/api/license", {"key": "test_key"})- else:- response = self.client.delete(f"/api/license/{license_pk}/")-- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)- patch_post.assert_not_called()- self.assertTrue(License.objects.filter(pk=license_pk).exists())- self.assertEqual(set(Team.objects.values_list("pk", flat=True)), teams_before)- self.assertEqual(set(Organization.objects.values_list("pk", flat=True)), orgs_before)-- @pytest.mark.skip_on_multitenancy- @patch("ee.api.license.requests.post")- def test_staff_user_cannot_delete_license_in_cloud_mode(self, patch_post):- Team.objects.create(organization=self.organization)- Team.objects.create(organization=self.organization, is_demo=True)- other_org = Organization.objects.create()- Team.objects.create(organization=other_org)-- teams_before = set(Team.objects.values_list("pk", flat=True))- orgs_before = set(Organization.objects.values_list("pk", flat=True))- license_pk = self.license.pk-- mock = Mock()- mock.json.return_value = {"ok": True}- patch_post.return_value = mock-- with self.is_cloud(True):- response = self.client.delete(f"/api/license/{license_pk}/")-- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)- patch_post.assert_not_called()- self.assertTrue(License.objects.filter(pk=license_pk).exists())- self.assertEqual(set(Team.objects.values_list("pk", flat=True)), teams_before)- self.assertEqual(set(Organization.objects.values_list("pk", flat=True)), orgs_before)-- @pytest.mark.skip_on_multitenancy- @patch("ee.api.license.requests.post")- def test_can_cancel_license_with_another_valid_license(self, patch_post):- # In this case we won't delete projects as there's another valid license- License.objects.create(valid_until=now() + relativedelta(years=1), plan="enterprise")- Team.objects.create(organization=self.organization)- Team.objects.create(organization=self.organization, is_demo=True) # don't delete- other_org = Organization.objects.create()- Team.objects.create(organization=other_org)-- mock = Mock()- mock.json.return_value = {"ok": True}- patch_post.return_value = mock- response = self.client.delete(f"/api/license/{self.license.pk}/")- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)- self.assertEqual(Team.objects.count(), 4)- self.assertEqual(Team.objects.all().order_by("pk")[0].pk, self.team.pk)- self.assertEqual(Organization.objects.count(), 2)diff --git a/ee/api/test/test_organization.py b/ee/api/test/test_organization.pyindex 5ab5bfcb139c..2d38d2285188 100644--- a/ee/api/test/test_organization.py+++ b/ee/api/test/test_organization.py@@ -286,8 +286,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):self.assertFalse(self.organization.is_feature_available("feature-doesnt-exist"))License.PLANS = current_plans- @patch("ee.api.license.requests.post")- def test_feature_available_self_hosted_license_expired(self, patch_post):+ def test_feature_available_self_hosted_license_expired(self):current_plans = License.PLANSLicense.PLANS = {"enterprise": ["whatever"]} # type: ignorediff --git a/ee/models/license.py b/ee/models/license.pyindex 26ca91ee26f8..6bbd041e17f7 100644--- a/ee/models/license.py+++ b/ee/models/license.py@@ -7,27 +7,10 @@ from django.db.models.signals import post_savefrom django.dispatch.dispatcher import receiverfrom django.utils import timezone-from rest_framework import exceptions, status-from posthog.constants import AvailableFeaturefrom posthog.models.utils import sane_repr-class LicenseError(exceptions.APIException):- """- Exception raised for licensing errors.- """-- default_type = "license_error"- default_code = "license_error"- status_code = status.HTTP_400_BAD_REQUEST- default_detail = "There was a problem with your current license."-- def __init__(self, code, detail):- self.code = code- self.detail = exceptions._get_error_details(detail, code)--class LicenseManager(models.Manager["License"]):def first_valid(self) -> Optional["License"]:"""Return the highest valid license or cloud licenses if any"""diff --git a/ee/models/test/test_license.py b/ee/models/test/test_license.pynew file mode 100644index 000000000000..fd0767fa29f3--- /dev/null+++ b/ee/models/test/test_license.py@@ -0,0 +1,31 @@+from datetime import timedelta++import time_machine++from django.test import TestCase+from django.utils import timezone++from parameterized import parameterized++from ee.models.license import License+++class TestLicenseManager(TestCase):+ @parameterized.expand(+ [+ ("scale_then_enterprise", [License.SCALE_PLAN, License.ENTERPRISE_PLAN]),+ ("enterprise_then_scale", [License.ENTERPRISE_PLAN, License.SCALE_PLAN]),+ ]+ )+ @time_machine.travel("2022-06-03T12:00:00Z", tick=False)+ def test_first_valid_returns_highest_plan_regardless_of_creation_order(self, _name, creation_order):+ licenses = {}+ for index, plan in enumerate(creation_order):+ with time_machine.travel(timezone.now() + timedelta(days=index), tick=False):+ licenses[plan] = License.objects.create(+ key=f"{plan}-license",+ plan=plan,+ valid_until=timezone.now() + timedelta(days=30),+ )++ self.assertEqual(License.objects.first_valid(), licenses[License.ENTERPRISE_PLAN])diff --git a/ee/tasks/send_license_usage.py b/ee/tasks/send_license_usage.pydeleted file mode 100644index 01bd66ea0fcc..000000000000--- a/ee/tasks/send_license_usage.py+++ /dev/null@@ -1,105 +0,0 @@-from django.utils import timezone-from django.utils.timezone import now--import requests-import posthoganalytics-from dateutil.relativedelta import relativedelta--from posthog.clickhouse.client import sync_execute-from posthog.models import User-from posthog.settings import SITE_URL--from ee.models.license import License---def send_license_usage():- license = License.objects.first_valid()- user = User.objects.filter(is_active=True).first()-- if not license:- return-- # New type of license key for billing- if license.is_v2_license:- return-- try:- date_from = (timezone.now() - relativedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)- date_to = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)-- events_count = sync_execute(- "select count(1) from events where timestamp >= %(date_from)s and timestamp < %(date_to)s and not startsWith(event, '$$')",- {"date_from": date_from, "date_to": date_to},- )[0][0]- response = requests.post(- "https://license.posthog.com/licenses/usage",- data={- "date": date_from.strftime("%Y-%m-%d"),- "key": license.key,- "events_count": events_count,- },- )-- if response.status_code == 404 and response.json().get("code") == "not_found":- license.valid_until = now() - relativedelta(hours=1)- license.save()-- if response.status_code == 400 and response.json().get("code") == "already_sent":- return-- if response.json().get("valid_until"):- license.valid_until = response.json()["valid_until"]- license.save()-- if not response.ok:- posthoganalytics.capture(- "send license usage data error",- distinct_id=user.distinct_id, # type: ignore- properties={- "error": response.content,- "status_code": response.status_code,- "date": date_from.strftime("%Y-%m-%d"),- "events_count": events_count,- "organization_name": user.current_organization.name, # type: ignore- },- groups={- "organization": str(user.current_organization.id), # type: ignore- "instance": SITE_URL,- },- )- response.raise_for_status()- return- else:- posthoganalytics.capture(- "send license usage data",- distinct_id=user.distinct_id, # type: ignore- properties={- "date": date_from.strftime("%Y-%m-%d"),- "events_count": events_count,- "license_keys": [license.key for license in License.objects.all()],- "organization_name": user.current_organization.name, # type: ignore- },- groups={- "organization": str(user.current_organization.id), # type: ignore- "instance": SITE_URL,- },- )- except Exception as err:- try:- posthoganalytics.capture(- "send license usage data error",- distinct_id=user.distinct_id, # type: ignore- properties={- "error": str(err),- "date": date_from.strftime("%Y-%m-%d"),- "organization_name": user.current_organization.name, # type: ignore- },- groups={- "organization": str(user.current_organization.id), # type: ignore- "instance": SITE_URL,- },- )- raise err- except:- # If the posthoganalytics call errors, just throw the original error rather than that error- raise errdiff --git a/ee/tasks/test/test_send_license_usage.py b/ee/tasks/test/test_send_license_usage.pydeleted file mode 100644index b3cc41eb218d..000000000000--- a/ee/tasks/test/test_send_license_usage.py+++ /dev/null@@ -1,316 +0,0 @@-import time_machine-from posthog.test.base import APIBaseTest, ClickhouseDestroyTablesMixin, _create_event, flush_persons_and_events-from unittest.mock import ANY, Mock, patch--from posthog.models.team import Team--from ee.api.test.base import LicensedTestMixin-from ee.models.license import License-from ee.tasks.send_license_usage import send_license_usage---class SendLicenseUsageTest(LicensedTestMixin, ClickhouseDestroyTablesMixin, APIBaseTest):- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("posthoganalytics.capture")- @patch("ee.tasks.send_license_usage.requests.post")- def test_send_license_usage(self, mock_post, mock_capture):- self.license.key = "legacy-key"- self.license.save()- team2 = Team.objects.create(organization=self.organization)- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-08T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T12:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$$internal_metrics_shouldnt_be_billed",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$pageview",- team=team2,- distinct_id=1,- timestamp="2021-10-09T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-10T14:01:01Z",- )- flush_persons_and_events()-- mockresponse = Mock()- mock_post.return_value = mockresponse- mockresponse.json = lambda: {"ok": True, "valid_until": "2021-11-10T23:01:00Z"}-- send_license_usage()- mock_post.assert_called_once_with(- "https://license.posthog.com/licenses/usage",- data={"date": "2021-10-09", "key": self.license.key, "events_count": 3},- )- mock_capture.assert_called_once_with(- "send license usage data",- distinct_id=self.user.distinct_id,- properties={- "date": "2021-10-09",- "events_count": 3,- "license_keys": [self.license.key],- "organization_name": "Test",- },- groups={"instance": ANY, "organization": str(self.organization.id)},- )- self.assertEqual(License.objects.get().valid_until.isoformat(), "2021-11-10T23:01:00+00:00")-- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("posthoganalytics.capture")- @patch("ee.tasks.send_license_usage.sync_execute", side_effect=Exception())- def test_send_license_error(self, mock_post, mock_capture):- self.license.key = "legacy-key"- self.license.save()-- team2 = Team.objects.create(organization=self.organization)- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-08T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T12:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$$internal_metrics_shouldnt_be_billed",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$pageview",- team=team2,- distinct_id=1,- timestamp="2021-10-09T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-10T14:01:01Z",- )- flush_persons_and_events()- with self.assertRaises(Exception):- send_license_usage()- mock_capture.assert_called_once_with(- "send license usage data error",- distinct_id=self.user.distinct_id,- properties={- "error": "",- "date": "2021-10-09",- "organization_name": "Test",- },- groups={"instance": ANY, "organization": str(self.organization.id)},- )-- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("posthoganalytics.capture")- @patch("ee.tasks.send_license_usage.requests.post")- def test_send_license_usage_already_sent(self, mock_post, mock_capture):- self.license.key = "legacy-key"- self.license.save()-- team2 = Team.objects.create(organization=self.organization)- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-08T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T12:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$$internal_metrics_shouldnt_be_billed",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$pageview",- team=team2,- distinct_id=1,- timestamp="2021-10-09T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-10T14:01:01Z",- )- mockresponse = Mock()- mock_post.return_value = mockresponse- mockresponse.ok = False- mockresponse.status_code = 400- mockresponse.json = lambda: {- "code": "already_sent",- "error": "Usage data for this period has already been sent.",- }- flush_persons_and_events()- send_license_usage()- mock_capture.assert_not_called()-- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("posthoganalytics.capture")- @patch("ee.tasks.send_license_usage.requests.post")- def test_send_license_not_found(self, mock_post, mock_capture):- self.license.key = "legacy-key"- self.license.save()-- team2 = Team.objects.create(organization=self.organization)- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-08T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T12:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$$internal_metrics_shouldnt_be_billed",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$pageview",- team=team2,- distinct_id=1,- timestamp="2021-10-09T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-10T14:01:01Z",- )- flush_persons_and_events()- flush_persons_and_events()-- mockresponse = Mock()- mock_post.return_value = mockresponse- mockresponse.status_code = 404- mockresponse.ok = False- mockresponse.json = lambda: {"code": "not_found"}- mockresponse.content = ""-- send_license_usage()-- mock_capture.assert_called_once_with(- "send license usage data error",- distinct_id=self.user.distinct_id,- properties={- "error": "",- "date": "2021-10-09",- "organization_name": "Test",- "status_code": 404,- "events_count": 3,- },- groups={"instance": ANY, "organization": str(self.organization.id)},- )- self.assertEqual(License.objects.get().valid_until.isoformat(), "2021-10-10T22:01:00+00:00")-- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("posthoganalytics.capture")- @patch("ee.tasks.send_license_usage.requests.post")- def test_send_license_not_triggered_for_v2_licenses(self, mock_post, mock_capture):- self.license.key = "billing-service::v2-key"- self.license.save()-- send_license_usage()-- assert mock_capture.call_count == 0---class SendLicenseUsageNoLicenseTest(APIBaseTest):- @time_machine.travel("2021-10-10T23:01:00Z", tick=False)- @patch("ee.tasks.send_license_usage.requests.post")- def test_no_license(self, mock_post):- # Same test, we just don't include the LicensedTestMixin so no license- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-08T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T12:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T13:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-09T14:01:01Z",- )- _create_event(- event="$pageview",- team=self.team,- distinct_id=1,- timestamp="2021-10-10T14:01:01Z",- )-- flush_persons_and_events()-- send_license_usage()-- self.assertEqual(mock_post.call_count, 0)diff --git a/ee/urls.py b/ee/urls.pyindex 34852a0a5647..f18b6fb3caf6 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -23,7 +23,7 @@ from ee.api.vercel import vercel_connect, vercel_sso, vercel_webhooksfrom ee.middleware import admin_oauth2_callbackfrom ee.support_sidebar_max.views import MaxChatViewSet-from .api import authentication, billing, conversation, core_memory, license, subscription+from .api import authentication, billing, conversation, core_memory, subscriptionfrom .api.rbac import rolefrom .api.scim import views as scim_views@@ -38,7 +38,6 @@ def extend_api_router() -> None:from ee.api import hands_free, max_toolsroot_router.register(r"billing", billing.BillingViewset, "billing")- root_router.register(r"license", license.LicenseViewSet)root_router.register(r"integrations", integration.PublicIntegrationViewSet)organization_roles_router = organizations_router.register(r"roles",diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 053a8f6d3ed4..ad73e6b85574 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -46,7 +46,6 @@ from posthog.tasks.tasks import (clickhouse_mutation_count,clickhouse_part_count,clickhouse_row_count,- clickhouse_send_license_usage,delete_expired_delegation_invites,delete_expired_exported_assets,fail_stuck_video_exports,@@ -922,17 +921,6 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:)if settings.EE_AVAILABLE:- sender.add_periodic_task(- # The minute differs between installations so that they do not all call- # license.posthog.com in the same minute past midnight.- crontab(hour="0", minute=instance_spread_minute("send license usage", 40)),- clickhouse_send_license_usage.s(),- )- sender.add_periodic_task(- crontab(hour="4", minute=instance_spread_minute("send license usage retry", 40)),- clickhouse_send_license_usage.s(),- ) # again a few hours later just to make sure-materialize_columns_crontab = get_crontab(settings.MATERIALIZE_COLUMNS_SCHEDULE_CRON)if materialize_columns_crontab:diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 86c73029bb71..1ac68c577f88 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -1104,17 +1104,6 @@ def send_org_usage_reports() -> None:send_all_org_usage_reports.delay()-@shared_task(ignore_result=True, retries=3)-def clickhouse_send_license_usage() -> None:- try:- if not is_cloud():- from ee.tasks.send_license_usage import send_license_usage-- send_license_usage()- except ImportError:- pass--@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)def background_delete_model_task(model_name: str, team_id: int, batch_size: int = 10000, records_to_delete: int | None = Nonediff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 2dcf4c114656..1e3b45e2aa4a 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -122,7 +122,6 @@'posthog.tasks.tasks.clickhouse_mutation_count','posthog.tasks.tasks.clickhouse_part_count','posthog.tasks.tasks.clickhouse_row_count',- 'posthog.tasks.tasks.clickhouse_send_license_usage','posthog.tasks.tasks.delete_expired_delegation_invites','posthog.tasks.tasks.delete_expired_exported_assets','posthog.tasks.tasks.demo_reset_master_team',