: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(aio): add manual trigger for ai observability usage report (#73088)
Carlos Marchal38f215871f2a
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex 7123a711a37e..b9e0b48b7c7d 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -488,6 +488,11 @@ class OrganizationAdmin(admin.ModelAdmin):path("send-usage-report/", self.admin_site.admin_view(self.send_usage_report_view), name="send-usage-report"),+ path(+ "send-ai-observability-usage-report/",+ self.admin_site.admin_view(self.send_ai_observability_usage_report_view),+ name="send-ai-observability-usage-report",+ ),path("<path:organization_id>/limit-product/",self.admin_site.admin_view(self.limit_product_view),@@ -550,6 +555,23 @@ class OrganizationAdmin(admin.ModelAdmin):return render(request, "admin/posthog/organization/send_usage_report.html", {"form": form})+ def send_ai_observability_usage_report_view(self, request):+ # Staff-only on purpose (no group gate like the sibling): nothing customer-facing, and+ # duplicate emissions are ignorable at query time (read one event per org per day).+ if request.method == "POST":+ form = UsageReportForm(request.POST)+ if form.is_valid():+ report_date = form.cleaned_data["report_date"]+ call_command(+ "send_ai_observability_usage_report", f"--date={report_date.strftime('%Y-%m-%d')}", "--async"+ )+ messages.success(request, f"AI observability usage report for date {report_date} was queued.")+ return redirect(reverse("admin:posthog_organization_changelist"))+ else:+ form = UsageReportForm()++ return render(request, "admin/posthog/organization/send_ai_observability_usage_report.html", {"form": form})+def changelist_view(self, request, extra_context=None):extra_context = extra_context or {}extra_context["show_usage_report_button"] = Truediff --git a/posthog/admin/test_send_ai_observability_usage_report_admin.py b/posthog/admin/test_send_ai_observability_usage_report_admin.pynew file mode 100644index 000000000000..cdf94c7132ad--- /dev/null+++ b/posthog/admin/test_send_ai_observability_usage_report_admin.py@@ -0,0 +1,72 @@+from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.contrib.admin.sites import AdminSite+from django.contrib.messages.storage.fallback import FallbackStorage+from django.test import RequestFactory+from django.urls import reverse++from posthog.admin.admins.organization_admin import OrganizationAdmin+from posthog.models import Organization+++def _attach_messages(request) -> None:+ request.session = {}+ request._messages = FallbackStorage(request)+++def _fake_reverse(name, args=None, kwargs=None):+ return f"/{name}/"+++class TestSendAIObservabilityUsageReportAdmin(BaseTest):+ def setUp(self):+ super().setUp()+ self.user.is_staff = True+ self.user.save()+ self.factory = RequestFactory()+ self.admin = OrganizationAdmin(Organization, AdminSite())+ reverse(+ "admin:index"+ ) # warm posthog.urls import outside freeze_time: the first reverse() lazily imports pydantic v1, which breaks under a frozen datetime.date++ def _post(self, report_date: str):+ http_request = self.factory.post(+ "/admin/posthog/organization/send-ai-observability-usage-report/", {"report_date": report_date}+ )+ http_request.user = self.user+ _attach_messages(http_request)+ with (+ patch("posthog.admin.admins.organization_admin.reverse", side_effect=_fake_reverse),+ patch("posthog.admin.admins.organization_admin.call_command") as mock_call_command,+ ):+ response = self.admin.send_ai_observability_usage_report_view(http_request)+ return response, mock_call_command++ @freeze_time("2026-07-22T12:00:00Z")+ def test_valid_post_dispatches_async_command_for_date(self):+ response, mock_call_command = self._post("2026-07-15")++ self.assertEqual(response.status_code, 302)+ mock_call_command.assert_called_once_with("send_ai_observability_usage_report", "--date=2026-07-15", "--async")++ @freeze_time("2026-07-22T12:00:00Z")+ def test_far_future_date_is_rejected_and_not_dispatched(self):+ response, mock_call_command = self._post("2026-07-30")++ self.assertEqual(response.status_code, 200)+ mock_call_command.assert_not_called()++ def test_get_renders_form_without_dispatching(self):+ http_request = self.factory.get("/admin/posthog/organization/send-ai-observability-usage-report/")+ http_request.user = self.user+ _attach_messages(http_request)+ with (+ patch("posthog.admin.admins.organization_admin.reverse", side_effect=_fake_reverse),+ patch("posthog.admin.admins.organization_admin.call_command") as mock_call_command,+ ):+ response = self.admin.send_ai_observability_usage_report_view(http_request)++ self.assertEqual(response.status_code, 200)+ mock_call_command.assert_not_called()diff --git a/posthog/management/commands/send_ai_observability_usage_report.py b/posthog/management/commands/send_ai_observability_usage_report.pynew file mode 100644index 000000000000..96f0d3217662--- /dev/null+++ b/posthog/management/commands/send_ai_observability_usage_report.py@@ -0,0 +1,51 @@+from typing import Any++from django.core.management.base import BaseCommand, CommandParser+from django.utils import timezone++from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports+++class Command(BaseCommand):+ help = "Send the AI observability usage report for a given day"++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--dry-run", action="store_true", help="Print information instead of sending it")+ parser.add_argument("--date", type=str, help="The date to be run in format YYYY-MM-DD")+ parser.add_argument("--async", action="store_true", help="Run the task asynchronously")+ parser.add_argument(+ "--org-ids",+ type=str,+ help="Comma-separated list of organization UUIDs to process (e.g., 'uuid1,uuid2,uuid3')",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ dry_run = options["dry_run"]+ date = options["date"] or timezone.now().date().isoformat()+ run_async = options["async"]+ org_ids_str = options.get("org_ids")++ organization_ids = (+ ([oid.strip() for oid in org_ids_str.split(",") if oid.strip()] or None) if org_ids_str else None+ )++ if run_async:+ send_ai_observability_usage_reports.delay(+ dry_run=dry_run,+ at=date,+ organization_ids=organization_ids,+ )+ print("Queued!") # noqa: T201+ else:+ send_ai_observability_usage_reports(+ dry_run=dry_run,+ at=date,+ organization_ids=organization_ids,+ )++ if dry_run:+ print("Dry run so not sent.") # noqa: T201+ elif organization_ids:+ print(f"Done! Processed {len(organization_ids)} organization(s).") # noqa: T201+ else:+ print("Done!") # noqa: T201diff --git a/posthog/management/commands/test/test_send_ai_observability_usage_report.py b/posthog/management/commands/test/test_send_ai_observability_usage_report.pynew file mode 100644index 000000000000..95499ce2c2d5--- /dev/null+++ b/posthog/management/commands/test/test_send_ai_observability_usage_report.py@@ -0,0 +1,56 @@+from freezegun import freeze_time+from unittest.mock import patch++from django.core.management import call_command++TASK_PATH = "posthog.management.commands.send_ai_observability_usage_report.send_ai_observability_usage_reports"+++@freeze_time("2026-07-22T12:00:00Z")+def test_send_ai_observability_usage_report_defaults_to_current_date() -> None:+ with patch(TASK_PATH) as mock_send_reports:+ call_command("send_ai_observability_usage_report")++ mock_send_reports.assert_called_once_with(+ dry_run=False,+ at="2026-07-22",+ organization_ids=None,+ )+++@freeze_time("2026-07-22T12:00:00Z")+def test_send_ai_observability_usage_report_preserves_passed_date() -> None:+ with patch(TASK_PATH) as mock_send_reports:+ call_command("send_ai_observability_usage_report", "--date=2026-07-15")++ mock_send_reports.assert_called_once_with(+ dry_run=False,+ at="2026-07-15",+ organization_ids=None,+ )+++@freeze_time("2026-07-22T12:00:00Z")+def test_send_ai_observability_usage_report_dry_run_runs_sync_with_dry_run_flag() -> None:+ with patch(TASK_PATH) as mock_send_reports:+ call_command("send_ai_observability_usage_report", "--dry-run")++ mock_send_reports.assert_called_once_with(+ dry_run=True,+ at="2026-07-22",+ organization_ids=None,+ )+ mock_send_reports.delay.assert_not_called()+++@freeze_time("2026-07-22T12:00:00Z")+def test_send_ai_observability_usage_report_async_dispatches_delay_with_parsed_org_ids() -> None:+ with patch(TASK_PATH) as mock_send_reports:+ call_command("send_ai_observability_usage_report", "--async", "--org-ids=org-a, org-b,")++ mock_send_reports.delay.assert_called_once_with(+ dry_run=False,+ at="2026-07-22",+ organization_ids=["org-a", "org-b"],+ )+ mock_send_reports.assert_not_called()diff --git a/posthog/templates/admin/posthog/organization/change_list.html b/posthog/templates/admin/posthog/organization/change_list.htmlindex fe356f7d7bb9..1ea7859b9727 100644--- a/posthog/templates/admin/posthog/organization/change_list.html+++ b/posthog/templates/admin/posthog/organization/change_list.html@@ -6,6 +6,9 @@<li><a href="{% url 'admin:send-usage-report' %}">Send Usage Report</a></li>+ <li>+ <a href="{% url 'admin:send-ai-observability-usage-report' %}">Send AI observability usage report</a>+ </li>{% endif %}{{ block.super }}{% endblock %}diff --git a/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html b/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.htmlnew file mode 100644index 000000000000..1c31d879d470--- /dev/null+++ b/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html@@ -0,0 +1,26 @@+{% extends "admin/base_site.html" %}+{% load i18n admin_urls %}++{% block content %}+<div id="content-main">+ <form method="post">+ <p>The date is the day the report would have run; it reports AI observability usage for the <b>previous</b> day.+ <br/>If the dashboards are missing a day X, enter the day after (X+1). The report covering day X is generated and stamped on X+1.</p>+ <p><b>Warning: there is no idempotency yet.</b> Submitting for a date that already emitted reports (fully or partially) creates duplicate events that double-count in every downstream insight, with no way to clean them up.+ <br/>Check the daily <code>llm analytics usage</code> event volume in the internal usage-tracking project for that date before submitting.</p>+ <p>US and EU each report their own organizations. To backfill both, run this in each region's admin separately.</p>+ {% csrf_token %}+ <fieldset class="module aligned">+ {% for field in form %}+ <div class="form-row">+ {{ field.errors }}+ {{ field.label_tag }} {{ field }}+ </div>+ {% endfor %}+ </fieldset>+ <div class="submit-row">+ <input type="submit" value="Send AI observability usage report" class="default" name="_send_report">+ </div>+ </form>+</div>+{% endblock %}