Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(aio): guard duplicate usage report emission (#81138)

Carlos Marchalf22c2fb4b612
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 22cc55db18ec..0630b9443e82 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -5,6 +5,7 @@ from django.apps import apps
from django.conf import settings
from django.contrib import admin, messages
from django.core.management import call_command
+from django.core.management.base import CommandError
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.urls import path, reverse
@@ -23,6 +24,7 @@ from posthog.admin.inlines.team_inline import TeamInline
from posthog.admin.paginators.no_count_paginator import NoCountPaginator
from posthog.models.organization import Organization
from posthog.person_db_router import PERSONS_DB_MODELS
+from posthog.tasks.ai_observability_usage_report import internal_reporting_team_id
# Registry of default-db models to count for bulk-delete report.
# Format: (app_label.ModelName, filter_field, display_name)
@@ -570,21 +572,31 @@ 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).
+ # Staff-only on purpose, unlike the sibling billing view: nothing here is customer-facing, and
+ # the task now skips organizations that already have a report for the period.
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.")
+ try:
+ call_command(
+ "send_ai_observability_usage_report", f"--date={report_date.strftime('%Y-%m-%d')}", "--async"
+ )
+ except CommandError as e:
+ # Surfacing this matters: a swallowed refusal would report success for a run that
+ # never started, so the operator would stop looking for the missing reports.
+ messages.error(request, str(e))
+ else:
+ 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})
+ return render(
+ request,
+ "admin/posthog/organization/send_ai_observability_usage_report.html",
+ {"form": form, "can_skip_existing_reports": internal_reporting_team_id() is not None},
+ )
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
diff --git a/posthog/admin/test_send_ai_observability_usage_report_admin.py b/posthog/admin/test_send_ai_observability_usage_report_admin.py
index cdf94c7132ad..1257ce3ef0d4 100644
--- a/posthog/admin/test_send_ai_observability_usage_report_admin.py
+++ b/posthog/admin/test_send_ai_observability_usage_report_admin.py
@@ -2,8 +2,10 @@ from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.contrib import messages
from django.contrib.admin.sites import AdminSite
from django.contrib.messages.storage.fallback import FallbackStorage
+from django.core.management.base import CommandError
from django.test import RequestFactory
from django.urls import reverse
@@ -31,7 +33,7 @@ class TestSendAIObservabilityUsageReportAdmin(BaseTest):
"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):
+ def _post(self, report_date: str, call_command_side_effect=None):
http_request = self.factory.post(
"/admin/posthog/organization/send-ai-observability-usage-report/", {"report_date": report_date}
)
@@ -39,25 +41,38 @@ class TestSendAIObservabilityUsageReportAdmin(BaseTest):
_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,
+ patch(
+ "posthog.admin.admins.organization_admin.call_command", side_effect=call_command_side_effect
+ ) as mock_call_command,
):
response = self.admin.send_ai_observability_usage_report_view(http_request)
- return response, mock_call_command
+ return response, mock_call_command, http_request
@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")
+ response, mock_call_command, http_request = 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")
+ self.assertEqual([m.level for m in http_request._messages], [messages.SUCCESS])
@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")
+ response, mock_call_command, _ = self._post("2026-07-30")
self.assertEqual(response.status_code, 200)
mock_call_command.assert_not_called()
+ @freeze_time("2026-07-22T12:00:00Z")
+ def test_refused_dispatch_is_reported_as_an_error_not_a_success(self):
+ response, _, http_request = self._post(
+ "2026-07-15", call_command_side_effect=CommandError("A usage report run for 2026-07-15 was already sent.")
+ )
+
+ self.assertEqual(response.status_code, 302)
+ stored = [(m.level, str(m)) for m in http_request._messages]
+ self.assertEqual(stored, [(messages.ERROR, "A usage report run for 2026-07-15 was already sent.")])
+
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
diff --git a/posthog/management/commands/send_ai_observability_usage_report.py b/posthog/management/commands/send_ai_observability_usage_report.py
index 96f0d3217662..f11fe1e7dbbe 100644
--- a/posthog/management/commands/send_ai_observability_usage_report.py
+++ b/posthog/management/commands/send_ai_observability_usage_report.py
@@ -1,9 +1,19 @@
from typing import Any
-from django.core.management.base import BaseCommand, CommandParser
+from django.core.cache import cache
+from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.utils import timezone
-from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports
+import structlog
+from dateutil import parser
+
+from posthog.tasks.ai_observability_usage_report import (
+ USAGE_REPORT_DISPATCH_LOCK_TIMEOUT_SECONDS,
+ send_ai_observability_usage_reports,
+ usage_report_dispatch_lock_key,
+)
+
+logger = structlog.get_logger(__name__)
class Command(BaseCommand):
@@ -21,7 +31,7 @@ class Command(BaseCommand):
def handle(self, *args: Any, **options: Any) -> None:
dry_run = options["dry_run"]
- date = options["date"] or timezone.now().date().isoformat()
+ date = self._normalized_date(options["date"])
run_async = options["async"]
org_ids_str = options.get("org_ids")
@@ -29,23 +39,85 @@ class Command(BaseCommand):
([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,
- )
+ # The task's already-reported lookup cannot see an emission that has not been ingested yet,
+ # so it does not stop two dispatches made seconds apart. Claiming the date here does, because
+ # the claim is atomic. A dry run emits nothing, so it must not claim and lock out a real run.
+ if not dry_run:
+ self._claim_dispatch(date)
- 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
+ # Both branches release the claim when the call raises. The task emits nothing before it can
+ # raise: it fails in the feature-flag check, the already-reported lookup, or the gathering, all
+ # of which precede the emission loop, and the loop itself swallows and logs per-organization
+ # failures rather than propagating them. Holding the claim after such a failure would lock the
+ # date out while nothing had been emitted, and there is no way to clear it by hand.
+ #
+ # `Exception` rather than `BaseException` on purpose. Ctrl+C raises `KeyboardInterrupt`, which
+ # a synchronous run can take part way through the emission loop, once some organizations
+ # already have reports. Releasing the claim there would admit a second run that cannot yet see
+ # those emissions, so an interrupt deliberately keeps the date claimed until the claim expires.
+ try:
+ if run_async:
+ send_ai_observability_usage_reports.delay(
+ dry_run=dry_run,
+ at=date,
+ organization_ids=organization_ids,
+ )
+ print("Queued!") # noqa: T201
else:
- print("Done!") # noqa: T201
+ 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: T201
+ except Exception:
+ if not dry_run:
+ self._release_dispatch(date)
+ raise
+
+ def _normalized_date(self, date: str | None) -> str:
+ """The report date as `YYYY-MM-DD`, defaulting to today.
+
+ The task resolves this with `dateutil`, which reads `2026-08-01`, `2026-8-1` and `08/01/2026`
+ as the same day, while the claim key is a literal string. Without normalizing first, those
+ spellings take different claims for one date and both runs emit. Normalizing here also turns
+ an unparseable date into an immediate error rather than one raised later inside a worker.
+ """
+ if not date:
+ return timezone.now().date().isoformat()
+
+ try:
+ return parser.parse(date).date().isoformat()
+ except (ValueError, OverflowError) as e:
+ raise CommandError(f"Could not read '{date}' as a date. Use the format YYYY-MM-DD.") from e
+
+ def _claim_dispatch(self, date: str) -> None:
+ """Claim `date` for this dispatch, refusing when another dispatch already holds it.
+
+ `cache.add` only writes when the key is absent, so concurrent dispatches race on the write
+ itself and exactly one wins. The claim is never released on success: releasing it before the
+ emitted events are queryable would reopen the window it exists to close.
+ """
+ if not cache.add(usage_report_dispatch_lock_key(date), "1", timeout=USAGE_REPORT_DISPATCH_LOCK_TIMEOUT_SECONDS):
+ raise CommandError(
+ f"A usage report run for {date} was already dispatched and may still be emitting. "
+ f"The claim covers the whole date, including runs scoped to specific organizations. "
+ f"Wait for that run to finish, then dispatch again to cover any organization it missed."
+ )
+
+ def _release_dispatch(self, date: str) -> None:
+ """Release the claim on `date`, without letting a cache failure replace the caller's error."""
+ try:
+ cache.delete(usage_report_dispatch_lock_key(date))
+ except Exception:
+ logger.warning(
+ "Could not release the AI observability usage report dispatch claim",
+ date=date,
+ exc_info=True,
+ )
diff --git a/posthog/management/commands/test/test_send_ai_observability_usage_report.py b/posthog/management/commands/test/test_send_ai_observability_usage_report.py
index 95499ce2c2d5..0ca547334a67 100644
--- a/posthog/management/commands/test/test_send_ai_observability_usage_report.py
+++ b/posthog/management/commands/test/test_send_ai_observability_usage_report.py
@@ -1,10 +1,27 @@
+import pytest
from freezegun import freeze_time
from unittest.mock import patch
+from django.core.cache import cache
from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from posthog.tasks.ai_observability_usage_report import usage_report_dispatch_lock_key
TASK_PATH = "posthog.management.commands.send_ai_observability_usage_report.send_ai_observability_usage_reports"
+CLAIMED_DATES = ("2026-07-15", "2026-07-16", "2026-07-22")
+
+
[email protected](autouse=True)
+def _clear_dispatch_claims() -> None:
+ # A dispatch claim deliberately outlives the run that made it, and several tests here dispatch the
+ # same frozen date, so a claim left behind would refuse the next test's dispatch. Only these keys
+ # are deleted: the test cache is process-local and shared by every test in the process, and a
+ # `cache.clear()` would also drop the materialized-column metadata the suite caches there.
+ for date in CLAIMED_DATES:
+ cache.delete(usage_report_dispatch_lock_key(date))
+
@freeze_time("2026-07-22T12:00:00Z")
def test_send_ai_observability_usage_report_defaults_to_current_date() -> None:
@@ -54,3 +71,80 @@ def test_send_ai_observability_usage_report_async_dispatches_delay_with_parsed_o
organization_ids=["org-a", "org-b"],
)
mock_send_reports.assert_not_called()
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_second_dispatch_for_the_same_date_is_refused() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ call_command("send_ai_observability_usage_report", "--async")
+
+ with pytest.raises(CommandError, match="already dispatched"):
+ call_command("send_ai_observability_usage_report", "--async")
+
+ mock_send_reports.delay.assert_called_once()
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_dispatch_claims_are_scoped_per_date() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ call_command("send_ai_observability_usage_report", "--async", "--date=2026-07-15")
+ call_command("send_ai_observability_usage_report", "--async", "--date=2026-07-16")
+
+ assert mock_send_reports.delay.call_count == 2
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_dry_run_does_not_claim_the_date() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ call_command("send_ai_observability_usage_report", "--dry-run")
+ call_command("send_ai_observability_usage_report", "--async")
+
+ mock_send_reports.delay.assert_called_once()
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_failed_dispatch_releases_the_claim() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ mock_send_reports.delay.side_effect = [RuntimeError("broker down"), None]
+
+ with pytest.raises(RuntimeError, match="broker down"):
+ call_command("send_ai_observability_usage_report", "--async")
+ call_command("send_ai_observability_usage_report", "--async")
+
+ assert mock_send_reports.delay.call_count == 2
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_equivalent_date_spellings_share_one_claim() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ call_command("send_ai_observability_usage_report", "--async", "--date=2026-07-15")
+
+ with pytest.raises(CommandError, match="already dispatched"):
+ call_command("send_ai_observability_usage_report", "--async", "--date=2026-7-15")
+
+ mock_send_reports.delay.assert_called_once_with(
+ dry_run=False,
+ at="2026-07-15",
+ organization_ids=None,
+ )
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_unreadable_date_is_rejected_without_dispatching() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ with pytest.raises(CommandError, match="Could not read"):
+ call_command("send_ai_observability_usage_report", "--async", "--date=not-a-date")
+
+ mock_send_reports.delay.assert_not_called()
+
+
+@freeze_time("2026-07-22T12:00:00Z")
+def test_failed_synchronous_run_releases_the_claim() -> None:
+ with patch(TASK_PATH) as mock_send_reports:
+ mock_send_reports.side_effect = [RuntimeError("clickhouse down"), None]
+
+ with pytest.raises(RuntimeError, match="clickhouse down"):
+ call_command("send_ai_observability_usage_report")
+ call_command("send_ai_observability_usage_report")
+
+ assert mock_send_reports.call_count == 2
diff --git a/posthog/tasks/ai_observability_usage_report.py b/posthog/tasks/ai_observability_usage_report.py
index 77c76ce8de53..316bf41cc9a2 100644
--- a/posthog/tasks/ai_observability_usage_report.py
+++ b/posthog/tasks/ai_observability_usage_report.py
@@ -17,6 +17,7 @@ from posthog.logging.timing import timed_log
from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
from posthog.models.property.util import get_property_string_expr
from posthog.models.team.team import Team
+from posthog.ph_client import PH_US_API_KEY
from posthog.schema_enums import AIEventType
from posthog.tasks.report_utils import capture_event
from posthog.tasks.utils import CeleryQueue
@@ -27,13 +28,22 @@ logger = structlog.get_logger(__name__)
@cached(cache={})
def get_ph_client() -> PostHogClient:
- """Get a PostHog client instance for capturing events."""
- return PostHogClient("sTMFPsFhdP1Ssg", sync_mode=True)
+ """Get a PostHog client instance for capturing events.
+
+ Shares `PH_US_API_KEY` with `internal_reporting_team_id`, which resolves the team the
+ already-reported lookup reads. A separate literal here could drift from that key, and the lookup
+ would then resolve no team, report that it cannot verify, and emit without checking.
+ """
+ return PostHogClient(PH_US_API_KEY, sync_mode=True)
AI_EVENTS = [event.value for event in AIEventType]
LLM_PROMPT_FETCHED_EVENT = "$llm_prompt_fetched"
+# The emitted report event. Shared by the emission and the already-reported lookup so the two
+# cannot drift: a lookup reading a different name would find nothing and silently allow duplicates.
+AI_OBSERVABILITY_USAGE_EVENT = "llm analytics usage"
+
AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS = [*AI_EVENTS, LLM_PROMPT_FETCHED_EVENT]
# Restricted to customer-emitted events that produce data downstream LLM analytics workflows can act on:
@@ -59,6 +69,10 @@ QUERY_RETRIES = 3
QUERY_RETRY_DELAY = 1
QUERY_RETRY_BACKOFF = 2
+# How long a queued report message may still be in flight before Celery discards it. The dispatch
+# claim reuses this, so the two cannot disagree about how long a run may still be emitting.
+USAGE_REPORT_MESSAGE_EXPIRY_SECONDS = 4 * 60 * 60
+
# Celery task ID for query attribution
CELERY_TASK_ID = "posthog.tasks.llm_analytics_usage_report.send_llm_analytics_usage_reports"
@@ -676,6 +690,130 @@ def get_llm_feedback_survey_metrics(
)
+# Every report is stamped this far after the start of the period it covers, whenever it is emitted.
+# A backfill of an old period therefore lands next to that period rather than at the operator's wall
+# clock, which is what lets the already-reported lookup bound its scan without missing a report.
+REPORT_STAMP_OFFSET = timedelta(days=1)
+
+# Bounds the scan for the already-reported lookup, which has to see every stamp a report for the
+# period could carry. Derived from the stamp offset rather than set independently, so moving where
+# reports are stamped cannot leave the lookup scanning a window that no longer contains them.
+#
+# The slack over the offset is deliberately far larger than the offset itself, because the two
+# directions are not symmetric. A window that is too wide reads more rows, and reads them cheaply,
+# since team_id, the timestamp range and the event name are all a prefix of the events table sort key.
+# A window that is too narrow reads a report that exists as never emitted and emits a duplicate, which
+# no consumer of these events can remove. The slack also covers reports emitted before stamping became
+# deterministic, which carry their arrival time rather than a fixed offset.
+REPORTED_LOOKUP_WINDOW = REPORT_STAMP_OFFSET + timedelta(days=89)
+
+# A claim has to outlive the run that took it, otherwise it lapses while the first dispatch is still
+# emitting and a second dispatch is admitted whose lookup cannot see the first one's events yet.
+USAGE_REPORT_DISPATCH_LOCK_TIMEOUT_SECONDS = USAGE_REPORT_MESSAGE_EXPIRY_SECONDS
+
+
+def usage_report_dispatch_lock_key(date: str) -> str:
+ """Cache key claiming a report date.
+
+ Keyed on the date alone, deliberately, even though it makes two disjoint `--org-ids` backfills of
+ one date serialize. The admin button always dispatches a whole date, so a key that also covered
+ the org scope would give the button and an org-scoped run different keys and let both through.
+ """
+ return f"ai-observability-usage-report-dispatch:{date}"
+
+
+def internal_reporting_team_id() -> int | None:
+ """The team whose events hold previously emitted reports, when this region has one.
+
+ `get_ph_client` emits with the US project's token from every region, so reports only ever land in
+ that one project and only a worker in the region hosting it can read them back. Everywhere else
+ the token matches no team. Callers must read None as "cannot verify", never as "nothing emitted".
+ """
+ return Team.objects.filter(api_token=PH_US_API_KEY).values_list("id", flat=True).first()
+
+
+@timed_log()
+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)
+def get_organizations_already_reported(period_start: datetime, internal_team_id: int) -> set[str]:
+ """Organization ids that already have a report covering `period_start`.
+
+ Matched on the `period_start` report property rather than on the event timestamp, because the
+ timestamp is a presentation choice that has already changed once, so deriving the period from it
+ would break silently if it changed again. `organization_id` and `period_start` are read from
+ `properties` rather than through `_ai_property_expr`: the `ai` property group only holds keys
+ matching `$ai_%`, so a group read of either would always return empty and allow every duplicate.
+ """
+ use_new = use_new_events_schema(internal_team_id)
+ org_id_expr, _ = get_property_string_expr(
+ "events", "organization_id", "'organization_id'", "properties", use_new_events_schema=use_new
+ )
+ period_start_expr, _ = get_property_string_expr(
+ "events", "period_start", "'period_start'", "properties", use_new_events_schema=use_new
+ )
+
+ query = f"""
+ SELECT DISTINCT {org_id_expr} AS organization_id
+ FROM {events_read_table(use_new)}
+ WHERE team_id = %(team_id)s
+ AND event = %(event)s
+ AND timestamp >= %(window_start)s
+ AND timestamp < %(window_end)s
+ AND toDate(parseDateTimeBestEffortOrNull({period_start_expr})) = toDate(%(period_start)s)
+ AND organization_id != ''
+ """
+
+ with tags_context(
+ product=Product.LLM_ANALYTICS,
+ feature=Feature.QUERY,
+ kind="celery",
+ id=CELERY_TASK_ID,
+ name="Get organizations already reported",
+ workload=Workload.OFFLINE.value,
+ ):
+ results = sync_execute(
+ query,
+ {
+ "team_id": internal_team_id,
+ "event": AI_OBSERVABILITY_USAGE_EVENT,
+ "window_start": period_start,
+ "window_end": period_start + REPORTED_LOOKUP_WINDOW,
+ "period_start": period_start,
+ },
+ workload=Workload.OFFLINE,
+ settings=CH_AI_OBSERVABILITY_SETTINGS,
+ )
+
+ return {row[0] for row in results}
+
+
+def _get_organizations_to_skip(period_start: datetime) -> set[str]:
+ """Organizations to leave out of this run because they already have a report for the period.
+
+ Returns an empty set where this region cannot read previously emitted reports, which emits
+ everything and matches the behaviour before the lookup existed. A lookup that fails for any other
+ reason raises instead, and that is deliberate: the run then cannot tell whether the period already
+ has reports, and emitting anyway would double count usage in every insight built on these events
+ with no way to remove the duplicates. Raising lets Celery retry and, if the failure persists, give
+ up having emitted nothing.
+
+ Two limits are worth knowing, both of which want a durable per organization and period record to
+ close properly. The evidence is an event in a project whose write token is public, so a forged
+ event carrying an organization id and a period start suppresses that organization's real report for
+ the period. And an emission is only visible here once ingested, so a run redelivered inside that
+ lag reads the period as unreported.
+ """
+ internal_team_id = internal_reporting_team_id()
+ if internal_team_id is None:
+ logger.warning(
+ "[AIO Usage Error] cannot check for already-emitted reports in this region, emitting without the check",
+ period_start=period_start.isoformat(),
+ event_source="ai_observability_usage_report",
+ )
+ return set()
+
+ return get_organizations_already_reported(period_start, internal_team_id)
+
+
def _is_final_attempt(task: Task) -> bool:
"""Whether a failure now is permanent: a direct (synchronous) call never retries, and the
last autoretry attempt runs with retries >= max_retries."""
@@ -693,7 +831,7 @@ AI_OBSERVABILITY_USAGE_REPORT_TASK_KWARGS = {
"autoretry_for": (Exception,),
"retry_backoff": 300, # 5min
"retry_backoff_max": 1800, # 30min
- "expires": 14400, # 4h
+ "expires": USAGE_REPORT_MESSAGE_EXPIRY_SECONDS,
}
@@ -955,7 +1093,7 @@ def capture_ai_observability_report(
capture_event(
pha_client=pha_client,
- name="llm analytics usage",
+ name=AI_OBSERVABILITY_USAGE_EVENT,
organization_id=organization_id,
properties=report_dict,
timestamp=at_date,
@@ -1025,6 +1163,10 @@ def send_ai_observability_usage_reports(
at_date = parser.parse(at) if at else None
period = get_previous_day(at=at_date)
+ # An explicit date or org filter is what distinguishes an operator-triggered run from the daily
+ # schedule.
+ is_manual_run = bool(at or organization_ids)
+
if organization_ids:
logger.info(
"Sending AI observability usage reports for specific organizations",
@@ -1036,6 +1178,14 @@ def send_ai_observability_usage_reports(
query_time_start = datetime.now(UTC)
try:
+ # Every run consults this, not only operator-triggered ones. `acks_late` with
+ # `reject_on_worker_lost` means a worker lost part way through the emission loop has its
+ # message redelivered with the same arguments, and the scheduled run carries no date, so a
+ # redelivered daily run would otherwise emit a second report for every organization it had
+ # already dispatched. It runs before the gathering so that a lookup failure costs one query
+ # rather than the whole five-query gather on each Celery retry, and inside this block so that
+ # a permanent lookup failure still reaches the terminal log the alert alerts on.
+ organizations_to_skip = _get_organizations_to_skip(period.start)
org_reports = _get_all_ai_observability_reports(period=period)
except Exception as err:
# The log alert keys on error severity: retryable attempts stay warnings, only the
@@ -1065,6 +1215,18 @@ def send_ai_observability_usage_reports(
missing_orgs=missing_orgs or None,
)
+ # Applied before the dry-run return so that a dry run previews the organizations a real run would
+ # report on, rather than the unfiltered set.
+ if organizations_to_skip:
+ before_count = len(org_reports)
+ org_reports = {org_id: report for org_id, report in org_reports.items() if org_id not in organizations_to_skip}
+ logger.info(
+ "Skipped organizations that already have an AI observability report for this period",
+ skipped_org_count=before_count - len(org_reports),
+ remaining_org_count=len(org_reports),
+ period_start=period.start.isoformat(),
+ )
+
query_time_duration = (datetime.now(UTC) - query_time_start).total_seconds()
logger.info(f"Found {len(org_reports)} AI observability org reports. It took {query_time_duration} seconds.")
@@ -1080,8 +1242,8 @@ def send_ai_observability_usage_reports(
# Deterministic nominal stamp (midnight after the covered day): keeps daily bucketing stable
# in UTC and project timezones, and stops retry stragglers landing on the wrong chart day.
# Actual arrival time remains queryable via events.created_at.
- report_timestamp = (period.start + timedelta(days=1)).isoformat()
- triggered_by = "manual" if (at or organization_ids) else "scheduled"
+ report_timestamp = (period.start + REPORT_STAMP_OFFSET).isoformat()
+ triggered_by = "manual" if is_manual_run else "scheduled"
for org_id, report in org_reports.items():
report["triggered_by"] = triggered_by
diff --git a/posthog/tasks/test/test_ai_observability_usage_report.py b/posthog/tasks/test/test_ai_observability_usage_report.py
index 400ed3a6ae43..b83b0d20530e 100644
--- a/posthog/tasks/test/test_ai_observability_usage_report.py
+++ b/posthog/tasks/test/test_ai_observability_usage_report.py
@@ -19,8 +19,10 @@ from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
from posthog.models import Organization, Team
from posthog.models.event.util import create_event
+from posthog.ph_client import PH_US_API_KEY
from posthog.tasks.ai_observability_usage_report import (
AI_OBSERVABILITY_REPORT_TRIGGER_EVENTS,
+ AI_OBSERVABILITY_USAGE_EVENT,
_get_all_ai_observability_reports,
capture_ai_observability_report,
get_all_ai_dimension_breakdowns,
@@ -1100,6 +1102,57 @@ class TestAIObservabilityUsageReport(APIBaseTest, ClickhouseTestMixin, Clickhous
assert report_dict["ai_generation_count"] == 5
assert report_dict["ai_embedding_count"] == 0 # Jan 9th events not included
+ @parameterized.expand(
+ [
+ ("covering_the_same_period", "2022-01-05T00:00:00+00:00", 0),
+ ("covering_a_different_period", "2021-12-20T00:00:00+00:00", 1),
+ ]
+ )
+ @patch("posthog.tasks.ai_observability_usage_report.capture_ai_observability_report")
+ @patch("posthog.tasks.ai_observability_usage_report.get_ph_client")
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_manual_run_skips_organizations_with_an_existing_report(
+ self,
+ _name: str,
+ existing_period_start: str,
+ expected_emissions: int,
+ mock_feature_enabled: MagicMock,
+ mock_get_ph_client: MagicMock,
+ mock_capture_report: MagicMock,
+ ) -> None:
+ self.team.api_token = PH_US_API_KEY
+ self.team.save()
+
+ distinct_id = str(uuid4())
+ _create_person(distinct_ids=[distinct_id], team=self.team)
+ self._create_ai_events(
+ self.team,
+ distinct_id,
+ "$ai_generation",
+ 5,
+ timestamp=datetime(2022, 1, 5, 12, 0, 0, tzinfo=UTC),
+ )
+
+ # Both cases stamp the existing report inside the lookup's scan window, so only the
+ # period_start property differs. A lookup that derived the period from the timestamp, or read
+ # either property out of the `ai` property group, would treat the two cases identically.
+ create_event(
+ event_uuid=uuid4(),
+ distinct_id=distinct_id,
+ event=AI_OBSERVABILITY_USAGE_EVENT,
+ properties={
+ "organization_id": str(self.organization.id),
+ "period_start": existing_period_start,
+ },
+ timestamp=datetime(2022, 1, 6, 4, 15, 0, tzinfo=UTC),
+ team=self.team,
+ )
+ flush_persons_and_events()
+
+ send_ai_observability_usage_reports(at="2022-01-06")
+
+ assert mock_capture_report.delay.call_count == expected_emissions
+
@freeze_time("2022-01-10T00:01:00Z")
class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
@@ -1110,6 +1163,7 @@ class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
("manual_by_org_filter", None, True, "2022-01-10T00:00:00+00:00", "manual"),
]
)
+ @patch("posthog.tasks.ai_observability_usage_report.internal_reporting_team_id", return_value=None)
@patch("posthog.tasks.ai_observability_usage_report.capture_ai_observability_report")
@patch("posthog.tasks.ai_observability_usage_report._get_all_ai_observability_reports")
@patch("posthoganalytics.feature_enabled", return_value=False)
@@ -1123,6 +1177,7 @@ class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
mock_feature_enabled: MagicMock,
mock_get_reports: MagicMock,
mock_capture_report: MagicMock,
+ mock_internal_team_id: MagicMock,
) -> None:
org_id = str(uuid4())
mock_get_reports.return_value = {
@@ -1141,6 +1196,77 @@ class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
assert call_kwargs["at_date"] == expected_at_date
assert call_kwargs["report_dict"]["triggered_by"] == expected_trigger
+ @patch(
+ "posthog.tasks.ai_observability_usage_report.get_organizations_already_reported",
+ side_effect=Exception("CH down"),
+ )
+ @patch("posthog.tasks.ai_observability_usage_report.internal_reporting_team_id", return_value=2)
+ @patch("posthog.tasks.ai_observability_usage_report.capture_ai_observability_report")
+ @patch("posthog.tasks.ai_observability_usage_report._get_all_ai_observability_reports")
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_run_emits_nothing_when_the_already_reported_lookup_fails(
+ self,
+ mock_feature_enabled: MagicMock,
+ mock_get_reports: MagicMock,
+ mock_capture_report: MagicMock,
+ mock_internal_team_id: MagicMock,
+ mock_already_reported: MagicMock,
+ ) -> None:
+ org_id = str(uuid4())
+ mock_get_reports.return_value = {org_id: {"organization_id": org_id}}
+
+ with pytest.raises(Exception, match="CH down"):
+ send_ai_observability_usage_reports(at="2022-01-06")
+
+ assert mock_capture_report.delay.call_count == 0
+ mock_get_reports.assert_not_called()
+
+ @parameterized.expand([("scheduled", None), ("manual", "2022-01-06")])
+ @patch("posthog.tasks.ai_observability_usage_report.get_organizations_already_reported")
+ @patch("posthog.tasks.ai_observability_usage_report.internal_reporting_team_id", return_value=2)
+ @patch("posthog.tasks.ai_observability_usage_report.capture_ai_observability_report")
+ @patch("posthog.tasks.ai_observability_usage_report._get_all_ai_observability_reports")
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_already_reported_organizations_are_skipped_on_every_run_type(
+ self,
+ _name: str,
+ at: str | None,
+ mock_feature_enabled: MagicMock,
+ mock_get_reports: MagicMock,
+ mock_capture_report: MagicMock,
+ mock_internal_team_id: MagicMock,
+ mock_already_reported: MagicMock,
+ ) -> None:
+ reported_org, fresh_org = str(uuid4()), str(uuid4())
+ mock_get_reports.return_value = {
+ reported_org: {"organization_id": reported_org},
+ fresh_org: {"organization_id": fresh_org},
+ }
+ mock_already_reported.return_value = {reported_org}
+
+ send_ai_observability_usage_reports(at=at)
+
+ emitted = [call.kwargs["organization_id"] for call in mock_capture_report.delay.call_args_list]
+ assert emitted == [fresh_org]
+
+ @patch("posthog.tasks.ai_observability_usage_report.internal_reporting_team_id", return_value=None)
+ @patch("posthog.tasks.ai_observability_usage_report.capture_ai_observability_report")
+ @patch("posthog.tasks.ai_observability_usage_report._get_all_ai_observability_reports")
+ @patch("posthoganalytics.feature_enabled", return_value=False)
+ def test_run_still_emits_where_previous_reports_cannot_be_read(
+ self,
+ mock_feature_enabled: MagicMock,
+ mock_get_reports: MagicMock,
+ mock_capture_report: MagicMock,
+ mock_internal_team_id: MagicMock,
+ ) -> None:
+ org_id = str(uuid4())
+ mock_get_reports.return_value = {org_id: {"organization_id": org_id}}
+
+ send_ai_observability_usage_reports(at="2022-01-06")
+
+ assert mock_capture_report.delay.call_count == 1
+
@parameterized.expand(
[
("retryable", 0, False, "warning", "error", "[AIO Usage Error] teams query failed"),
@@ -1162,6 +1288,7 @@ class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
),
]
)
+ @patch("posthog.tasks.ai_observability_usage_report._get_organizations_to_skip", return_value=set())
@patch("posthog.tasks.ai_observability_usage_report.logger")
@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events", side_effect=Exception("CH down"))
@patch("posthoganalytics.feature_enabled", return_value=False)
@@ -1176,6 +1303,7 @@ class TestAIObservabilityUsageReportTaskWiring(SimpleTestCase):
mock_feature_enabled: MagicMock,
mock_get_teams: MagicMock,
mock_logger: MagicMock,
+ mock_organizations_to_skip: MagicMock,
) -> None:
task = send_ai_observability_usage_reports
task.push_request(retries=retries, called_directly=called_directly, is_eager=True)
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.html
index 1c31d879d470..c557ce166275 100644
--- a/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html
+++ b/posthog/templates/admin/posthog/organization/send_ai_observability_usage_report.html
@@ -3,11 +3,23 @@
{% block content %}
<div id="content-main">
- <form method="post">
+ <form method="post" onsubmit="this.querySelector('input[name=_send_report]').disabled = true">
<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>Submitting the same date again while a run is still emitting is refused, so you cannot start two runs for
+ one date by accident.</p>
+ {% if can_skip_existing_reports %}
+ <p>Organizations that already have a report for the period are skipped, so only the organizations still
+ missing one get a report.
+ <br/>This reads back the reports that landed, so it cannot see a report emitted in the last few minutes.
+ If a run has just finished, give it time to be ingested before submitting the same date again.</p>
+ {% else %}
+ <p><b>This region cannot check which organizations already have a report.</b> Reports are emitted into the US
+ project, so a worker here cannot read them back.
+ <br/>Submitting a date that already emitted will double count usage in every insight built on these
+ events, and the duplicates cannot be removed. Check the daily <code>llm analytics usage</code> event
+ volume for that date in the internal usage-tracking project before submitting.</p>
+ {% endif %}
<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">