: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(business-knowledge): add chunk and query counters to the usage r… (#127419)
Alex V40af0fcb2895
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.pyindex d68f07cf35c7..04f308d855ad 100644--- a/posthog/tasks/test/test_usage_report.py+++ b/posthog/tasks/test/test_usage_report.py@@ -97,6 +97,7 @@ from products.batch_exports.backend.facade.enums import (BatchExportModel,BatchExportRunStatus,)+from products.business_knowledge.backend.models import KnowledgeUsageKey, KnowledgeUsageRecordfrom products.cdp.backend.models.plugin import Plugin, PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQuery@@ -332,6 +333,20 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesMErrorTrackingIssue.objects.create(team=self.org_1_team_1)+ # Different amounts per meter and team, so a swapped or misattributed counter fails the expectations.+ for team, usage_key, quantity in [+ (self.org_1_team_1, KnowledgeUsageKey.CHUNKS, 120),+ (self.org_1_team_1, KnowledgeUsageKey.QUERIES, 7),+ (self.org_1_team_2, KnowledgeUsageKey.CHUNKS, 30),+ (self.org_2_team_3, KnowledgeUsageKey.QUERIES, 4),+ ]:+ row = KnowledgeUsageRecord.objects.unscoped().create(+ team_id=team.id, usage_key=usage_key, quantity=quantity, surface="text"+ )+ KnowledgeUsageRecord.objects.unscoped().filter(id=row.id).update(+ created_at=now() - relativedelta(hours=12)+ )+uuids = [uuid4() for _ in range(0, 10)]for uuid in uuids:create_event(@@ -798,6 +813,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"exceptions_captured_in_period": 0,"ai_event_count_in_period": 7,"mcp_event_count_in_period": 0,+ "business_knowledge_chunks_in_period": 150,+ "business_knowledge_queries_in_period": 7,"hog_function_calls_in_period": 0,"hog_function_fetch_calls_in_period": 0,"cdp_billable_invocations_in_period": 0,@@ -905,6 +922,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"rows_exported_in_period": 0,"ai_event_count_in_period": 7,"mcp_event_count_in_period": 0,+ "business_knowledge_chunks_in_period": 120,+ "business_knowledge_queries_in_period": 7,},str(self.org_1_team_2.id): {"event_count_in_period": 11,@@ -1002,6 +1021,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"rows_exported_in_period": 0,"ai_event_count_in_period": 0,"mcp_event_count_in_period": 0,+ "business_knowledge_chunks_in_period": 30,+ "business_knowledge_queries_in_period": 0,},},},@@ -1122,6 +1143,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"rows_exported_in_period": 0,"ai_event_count_in_period": 0,"mcp_event_count_in_period": 0,+ "business_knowledge_chunks_in_period": 0,+ "business_knowledge_queries_in_period": 4,"date": "2022-01-09","organization_id": str(self.org_2.id),"organization_name": "Org 2",@@ -1227,6 +1250,8 @@ class TestUsageReport(APIBaseTest, ClickhouseTestMixin, ClickhouseDestroyTablesM"rows_exported_in_period": 0,"ai_event_count_in_period": 0,"mcp_event_count_in_period": 0,+ "business_knowledge_chunks_in_period": 0,+ "business_knowledge_queries_in_period": 4,}},},@@ -2488,6 +2513,8 @@ class TestHasNonZeroUsage(SimpleTestCase):("empty", None),("events", "event_count_in_period"),("mcp_events", "mcp_event_count_in_period"),+ ("business_knowledge_chunks", "business_knowledge_chunks_in_period"),+ ("business_knowledge_queries", "business_knowledge_queries_in_period"),("logs_bytes", "logs_bytes_in_period"),("logs_retention_mb_days", "logs_retention_mb_days_in_period"),("signals_credits", "signals_credits_used_in_period"),diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.pyindex 2e0bc9d563f5..76caf9f650df 100644--- a/posthog/tasks/usage_report.py+++ b/posthog/tasks/usage_report.py@@ -65,6 +65,8 @@ from posthog.utils import DayRange, get_helm_info_env, get_instance_realm, get_ifrom products.ai_observability.backend.offline_evaluation_billing import get_offline_evaluation_usagefrom products.batch_exports.backend.facade import api as batch_exports_api+from products.business_knowledge.backend.facade import api as business_knowledge_api+from products.business_knowledge.backend.facade.contracts import KnowledgeUsageByTeamfrom products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom products.cdp.backend.models.plugin import PluginConfigfrom products.dashboards.backend.models.dashboard import Dashboard@@ -317,6 +319,10 @@ class UsageReportCounters:# MCP analyticsmcp_event_count_in_period: int+ # Business knowledge+ business_knowledge_chunks_in_period: int+ business_knowledge_queries_in_period: int+# AI Billing Credits (PostHog AI feature usage)ai_credits_used_in_period: int@@ -1353,6 +1359,21 @@ def _replay_vision_spend_projection_rows(begin: datetime, end: datetime) -> dict}+@timed_log()+@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)+def get_teams_with_business_knowledge_usage_in_period(begin: datetime, end: datetime) -> KnowledgeUsageByTeam:+ # Read from the Business Knowledge usage ledger in Postgres, keyed by the canonical team.+ return business_knowledge_api.get_usage_by_team(begin, end)+++def _business_knowledge_usage_rows(begin: datetime, end: datetime) -> dict[str, TeamUsageRows]:+ usage = get_teams_with_business_knowledge_usage_in_period(begin, end)+ return {+ "teams_with_business_knowledge_chunks_in_period": usage.chunks,+ "teams_with_business_knowledge_queries_in_period": usage.queries,+ }++@timed_log()@retry(tries=QUERY_RETRIES, delay=QUERY_RETRY_DELAY, backoff=QUERY_RETRY_BACKOFF)def get_teams_with_zero_duration_recording_count_in_period(begin: datetime, end: datetime) -> list[tuple[int, int]]:@@ -3086,6 +3107,8 @@ def has_non_zero_usage(report: UsageReportCounters) -> bool:or report.exceptions_captured_in_period > 0or report.ai_event_count_in_period > 0or report.mcp_event_count_in_period > 0+ or report.business_knowledge_chunks_in_period > 0+ or report.business_knowledge_queries_in_period > 0or report.ai_credits_used_in_period > 0or report.signals_credits_used_in_period > 0or report.posthog_code_credits_used_in_period > 0@@ -3417,6 +3440,7 @@ def _get_all_usage_data(period_start: datetime, period_end: datetime) -> dict[st"teams_with_metrics_bytes_in_period": metrics_usage["bytes"],"teams_with_metrics_records_in_period": metrics_usage["records"],"teams_with_mcp_event_count_in_period": get_teams_with_mcp_event_count_in_period(period_start, period_end),+ **_business_knowledge_usage_rows(period_start, period_end),}@@ -3659,6 +3683,10 @@ def _get_team_report(all_data: dict[str, Any], team: Team) -> UsageReportCounterai_event_count_in_period=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),ai_ingested_event_count_in_period=all_data["teams_with_ai_event_count_in_period"].get(team.id, 0),mcp_event_count_in_period=all_data["teams_with_mcp_event_count_in_period"].get(team.id, 0),+ business_knowledge_chunks_in_period=all_data["teams_with_business_knowledge_chunks_in_period"].get(team.id, 0),+ business_knowledge_queries_in_period=all_data["teams_with_business_knowledge_queries_in_period"].get(+ team.id, 0+ ),ai_credits_used_in_period=all_data["teams_with_ai_credits_used_in_period"].get(team.id, 0),signals_credits_used_in_period=all_data["teams_with_signals_credits_used_in_period"].get(team.id, 0),posthog_code_credits_used_in_period=combine_posthog_code_credits(diff --git a/posthog/temporal/tests/usage_report/test_aggregator.py b/posthog/temporal/tests/usage_report/test_aggregator.pyindex ff3907ad9fbc..5a93e2a7b6f4 100644--- a/posthog/temporal/tests/usage_report/test_aggregator.py+++ b/posthog/temporal/tests/usage_report/test_aggregator.py@@ -25,6 +25,7 @@ from posthog.tasks.usage_report import ()from posthog.temporal.tests.usage_report.test_aggregate_activity import _instance_metadatafrom posthog.temporal.usage_report.aggregator import (+ add_pre_business_knowledge_usage_patch_defaults,add_pre_logs_distinct_patterns_patch_defaults,add_pre_mcp_event_count_patch_defaults,add_pre_replay_vision_spend_projection_patch_defaults,@@ -207,6 +208,22 @@ def test_load_all_data_defaults_replay_vision_spend_projection_for_pre_patch_worassert patched_data == {}+def test_load_all_data_defaults_business_knowledge_usage_for_pre_patch_workflow_history() -> None:+ all_data: dict[str, dict[int, int]] = {}+ add_pre_business_knowledge_usage_patch_defaults(all_data, [])++ assert all_data == {+ "teams_with_business_knowledge_chunks_in_period": {},+ "teams_with_business_knowledge_queries_in_period": {},+ }++ patched_data: dict[str, dict[int, int]] = {"teams_with_business_knowledge_queries_in_period": {1: 3}}+ results = [RunQueryToS3Result(query_name="business_knowledge_usage", s3_key="unused", duration_ms=1)]+ add_pre_business_knowledge_usage_patch_defaults(patched_data, results)++ assert patched_data == {"teams_with_business_knowledge_queries_in_period": {1: 3}}++def test_load_all_data_does_not_default_compute_for_patched_workflow_history() -> None:all_data: dict[str, dict[int, int]] = {}results = [RunQueryToS3Result(query_name="sandbox_compute_usage", s3_key="unused", duration_ms=1)]diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.pyindex 0896d0d8c387..f83db418431b 100644--- a/posthog/temporal/tests/usage_report/test_parity.py+++ b/posthog/temporal/tests/usage_report/test_parity.py@@ -78,6 +78,8 @@ def _seed_all_data(team_a_id: int, team_b_id: int, team_c_id: int) -> dict[str,"teams_with_event_count_in_period": {team_a_id: 100, team_b_id: 50, team_c_id: 25},"teams_with_enhanced_persons_event_count_in_period": {team_a_id: 80, team_b_id: 40},"teams_with_mcp_event_count_in_period": {team_a_id: 30, team_c_id: 5},+ "teams_with_business_knowledge_chunks_in_period": {team_a_id: 1_200, team_b_id: 300},+ "teams_with_business_knowledge_queries_in_period": {team_b_id: 40, team_c_id: 7},"teams_with_recording_count_in_period": {team_a_id: 8, team_c_id: 3},"teams_with_recording_bytes_in_period": {team_a_id: 1_234_567, team_c_id: 89_012},"teams_with_decide_requests_count_in_period": {team_a_id: 1_000, team_b_id: 200, team_c_id: 50},@@ -441,6 +443,8 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(# suspect.assert temporal_per_org[str(org_a.id)]["event_count_in_period"] == 100 + 50assert temporal_per_org[str(org_a.id)]["mcp_event_count_in_period"] == 30+ assert temporal_per_org[str(org_a.id)]["business_knowledge_chunks_in_period"] == 1_200 + 300+ assert temporal_per_org[str(org_b.id)]["business_knowledge_queries_in_period"] == 7assert temporal_per_org[str(org_b.id)]["event_count_in_period"] == 25assert temporal_per_org[str(org_a.id)]["team_count"] == 2assert temporal_per_org[str(org_b.id)]["team_count"] == 1diff --git a/posthog/temporal/tests/usage_report/test_workflow.py b/posthog/temporal/tests/usage_report/test_workflow.pyindex 94652baea726..3ead8755e816 100644--- a/posthog/temporal/tests/usage_report/test_workflow.py+++ b/posthog/temporal/tests/usage_report/test_workflow.py@@ -47,6 +47,7 @@ from posthog.temporal.usage_report.types import ()from posthog.temporal.usage_report.workflow import (AGGREGATION_QUEUE_PATCH_ID,+ BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME,LOGS_DISTINCT_PATTERNS_QUERY_NAME,MCP_EVENT_COUNT_QUERY_NAME,PARALLEL_COUNTER_QUERIES_PATCH_ID,@@ -56,6 +57,7 @@ from posthog.temporal.usage_report.workflow import (TRANSACTIONAL_EMAILS_QUERY_NAME,USAGE_COUNTER_SERVICE_PATCH_ID,RunUsageReportsWorkflow,+ _queries_for_business_knowledge_usage_patch,_queries_for_logs_distinct_patterns_patch,_queries_for_mcp_event_count_patch,_queries_for_replay_vision_spend_projection_patch,@@ -87,6 +89,7 @@ def test_sandbox_compute_query_is_versioned_for_existing_histories() -> None:_queries_for_replay_vision_spend_projection_patch,REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME,),+ ("business_knowledge_usage", _queries_for_business_knowledge_usage_patch, BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME),])def test_single_query_is_versioned_for_existing_histories(diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex 637f26cc898d..21ab30256a62 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -26,6 +26,7 @@ from posthog.tasks.usage_report import get_instance_metadata, iter_reports_with_from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.metrics import ExecutionTimeRecorderfrom posthog.temporal.usage_report.aggregator import (+ add_pre_business_knowledge_usage_patch_defaults,add_pre_logs_distinct_patterns_patch_defaults,add_pre_mcp_event_count_patch_defaults,add_pre_replay_vision_spend_projection_patch_defaults,@@ -254,6 +255,7 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateRadd_pre_transactional_emails_patch_defaults(all_data, inputs.query_results)add_pre_mcp_event_count_patch_defaults(all_data, inputs.query_results)add_pre_replay_vision_spend_projection_patch_defaults(all_data, inputs.query_results)+ add_pre_business_knowledge_usage_patch_defaults(all_data, inputs.query_results)check_cancelled()counter_report = load_usage_counter_report(inputs)all_data.update({field: dict(rows) for field, rows in counter_report.counts.items()})diff --git a/posthog/temporal/usage_report/aggregator.py b/posthog/temporal/usage_report/aggregator.pyindex 896de5da6741..10145604274d 100644--- a/posthog/temporal/usage_report/aggregator.py+++ b/posthog/temporal/usage_report/aggregator.py@@ -66,6 +66,11 @@ _REPLAY_VISION_SPEND_PROJECTION_DESTINATION_KEYS = ("teams_with_replay_vision_scanner_projected_credits","teams_with_replay_vision_backfill_committed_credits",)+_BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME = "business_knowledge_usage"+_BUSINESS_KNOWLEDGE_USAGE_DESTINATION_KEYS = (+ "teams_with_business_knowledge_chunks_in_period",+ "teams_with_business_knowledge_queries_in_period",+)def load_usage_counter_report(inputs: AggregateInputs) -> UsageCounterReport:@@ -134,6 +139,14 @@ def add_pre_replay_vision_spend_projection_patch_defaults(all_data[key] = {}+def add_pre_business_knowledge_usage_patch_defaults(+ all_data: dict[str, dict[int, int]], query_results: list[RunQueryToS3Result]+) -> None:+ if not any(result.query_name == _BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME for result in query_results):+ for key in _BUSINESS_KNOWLEDGE_USAGE_DESTINATION_KEYS:+ all_data[key] = {}++def iter_chunk_lines(org_reports: Iterable[OrgReport],instance_metadata: InstanceMetadata,diff --git a/posthog/temporal/usage_report/queries.py b/posthog/temporal/usage_report/queries.pyindex 3c350342ff0d..fdcbfada4458 100644--- a/posthog/temporal/usage_report/queries.py+++ b/posthog/temporal/usage_report/queries.py@@ -60,6 +60,7 @@ from posthog.tasks.usage_report import (get_teams_with_billable_enhanced_persons_event_count_in_period,get_teams_with_billable_event_count_in_period,get_teams_with_billable_sandbox_compute_usage_in_period,+ get_teams_with_business_knowledge_usage_in_period,get_teams_with_dwh_mat_views_storage_in_s3,get_teams_with_dwh_tables_storage_in_s3,get_teams_with_dwh_total_storage_in_s3,@@ -239,6 +240,14 @@ def _replay_vision_spend_projection(begin: datetime, end: datetime) -> dict[str,}+def _business_knowledge_usage(begin: datetime, end: datetime) -> dict[str, TeamUsageRows]:+ usage = get_teams_with_business_knowledge_usage_in_period(begin, end)+ return {+ "chunks": usage.chunks,+ "queries": usage.queries,+ }++def _sandbox_compute_usage(begin: datetime, end: datetime) -> dict[str, list[tuple[int, int]]]:usage = get_teams_with_billable_sandbox_compute_usage_in_period(begin, end)return {@@ -555,6 +564,16 @@ QUERIES: list[QuerySpec] = ["memory_mib_seconds": "teams_with_sandbox_compute_memory_mib_seconds_in_period",},),+ # ---- Postgres: business knowledge usage ledger --------------------------+ QuerySpec(+ name="business_knowledge_usage",+ fn=_business_knowledge_usage,+ output="multi",+ multi_keys_mapping={+ "chunks": "teams_with_business_knowledge_chunks_in_period",+ "queries": "teams_with_business_knowledge_queries_in_period",+ },+ ),# ---- ClickHouse: workflows / messaging ----------------------------------QuerySpec(name="teams_with_workflow_emails_sent_in_period",diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex 1bbe1be09fe7..f44fdbe69dd7 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -64,6 +64,8 @@ MCP_EVENT_COUNT_QUERY_PATCH_ID = "usage-report-mcp-event-count-query-2026-10"MCP_EVENT_COUNT_QUERY_NAME = "teams_with_mcp_event_count_in_period"REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID = "usage-report-replay-vision-spend-projection-query-2026-10"REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME = "replay_vision_spend_projection"+BUSINESS_KNOWLEDGE_USAGE_QUERY_PATCH_ID = "usage-report-business-knowledge-usage-query-2026-11"+BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME = "business_knowledge_usage"def _queries_for_sandbox_compute_patch(patch_applied: bool) -> list[QuerySpec]:@@ -96,6 +98,12 @@ def _queries_for_replay_vision_spend_projection_patch(queries: list[QuerySpec],return [spec for spec in queries if spec.name != REPLAY_VISION_SPEND_PROJECTION_QUERY_NAME]+def _queries_for_business_knowledge_usage_patch(queries: list[QuerySpec], patch_applied: bool) -> list[QuerySpec]:+ if patch_applied:+ return queries+ return [spec for spec in queries if spec.name != BUSINESS_KNOWLEDGE_USAGE_QUERY_NAME]++def build_context(inputs: RunUsageReportsInputs, run_id: str, now: datetime) -> WorkflowContext:"""Compute the period and S3 layout context. Pure function so it's safeto call from the workflow body (no real-time access).@@ -166,6 +174,9 @@ class RunUsageReportsWorkflow(PostHogWorkflow):queries = _queries_for_replay_vision_spend_projection_patch(queries, workflow.patched(REPLAY_VISION_SPEND_PROJECTION_QUERY_PATCH_ID))+ queries = _queries_for_business_knowledge_usage_patch(+ queries, workflow.patched(BUSINESS_KNOWLEDGE_USAGE_QUERY_PATCH_ID)+ )if workflow.patched(USAGE_COUNTER_SERVICE_PATCH_ID):ctx.usage_counter_plan = await workflow.execute_activity(plan_usage_counters,diff --git a/products/business_knowledge/backend/billing.py b/products/business_knowledge/backend/billing.pyindex d558f78d5106..6df28ad95765 100644--- a/products/business_knowledge/backend/billing.py+++ b/products/business_knowledge/backend/billing.py@@ -9,16 +9,20 @@ Two meters, matching the pricing RFC:- `business_knowledge_queries`: every knowledge search made with a `RetrievalTrace`, on any customersurface. PostHog's internal docs-shadow comparison is not metered.-This is metering only. Nothing is sent to the usage report or the billing service yet, and no quota is-enforced, so a metering failure is logged and never fails the ingest or search that triggered it.+The nightly usage report reads these totals (`usage_by_team`) and sends them to the billing service, which+does not charge for them until it has Business Knowledge products. No quota is enforced yet, so a metering+failure is logged and never fails the ingest or search that triggered it."""+from datetime import datetimefrom uuid import UUIDfrom django.db import transaction+from django.db.models import Sumimport structlog+from .facade.contracts import KnowledgeUsageByTeamfrom .models import KnowledgeUsageKey, KnowledgeUsageRecordlogger = structlog.get_logger(__name__)@@ -78,3 +82,21 @@ def record_query(*, team_id: int, trace_id: str, surface: str) -> None:logger.exception("business_knowledge.usage_record_failed", usage_key=KnowledgeUsageKey.QUERIES.value, team_id=team_id)+++def usage_by_team(begin: datetime, end: datetime) -> KnowledgeUsageByTeam:+ """(team_id, total) rows for each meter, from rows written in [begin, end).++ Buckets by write time, so a row written late lands in the next report instead of being missed.+ """+ rows = (+ KnowledgeUsageRecord.objects.unscoped()+ .filter(created_at__gte=begin, created_at__lt=end)+ .values("team_id", "usage_key")+ .annotate(total=Sum("quantity"))+ .order_by("team_id", "usage_key")+ )+ totals: dict[KnowledgeUsageKey, list[tuple[int, int]]] = {key: [] for key in KnowledgeUsageKey}+ for row in rows:+ totals[KnowledgeUsageKey(row["usage_key"])].append((row["team_id"], row["total"]))+ return KnowledgeUsageByTeam(chunks=totals[KnowledgeUsageKey.CHUNKS], queries=totals[KnowledgeUsageKey.QUERIES])diff --git a/products/business_knowledge/backend/facade/api.py b/products/business_knowledge/backend/facade/api.pyindex 59f680ffab1f..28d8c1aa0c67 100644--- a/products/business_knowledge/backend/facade/api.py+++ b/products/business_knowledge/backend/facade/api.py@@ -1,5 +1,8 @@+from datetime import datetimefrom uuid import UUID+from products.business_knowledge.backend import billing+from products.business_knowledge.backend.facade.contracts import KnowledgeUsageByTeamfrom products.business_knowledge.backend.models import KnowledgeGapSuggestion, KnowledgeLearningRun@@ -11,3 +14,8 @@ def purge_ticket_derived_rows(*, team_id: int, ticket_id: UUID) -> None:"""KnowledgeGapSuggestion.objects.for_team(team_id).filter(ticket_id=ticket_id).delete()KnowledgeLearningRun.objects.for_team(team_id).filter(evidence_key__startswith=f"{ticket_id}:").delete()+++def get_usage_by_team(begin: datetime, end: datetime) -> KnowledgeUsageByTeam:+ """Chunks ingested and queries per canonical team in [begin, end), for the usage report."""+ return billing.usage_by_team(begin, end)diff --git a/products/business_knowledge/backend/facade/contracts.py b/products/business_knowledge/backend/facade/contracts.pyindex e69de29bb2d1..82867483ceb4 100644--- a/products/business_knowledge/backend/facade/contracts.py+++ b/products/business_knowledge/backend/facade/contracts.py@@ -0,0 +1,9 @@+from posthog.dataclasses import frozen+++@frozen+class KnowledgeUsageByTeam:+ """Business knowledge usage in a period, as (team_id, total) rows per meter, for the usage report."""++ chunks: list[tuple[int, int]]+ queries: list[tuple[int, int]]diff --git a/products/business_knowledge/backend/models/knowledge_usage_record.py b/products/business_knowledge/backend/models/knowledge_usage_record.pyindex e9e11fa20f8f..7d73e15fabb6 100644--- a/products/business_knowledge/backend/models/knowledge_usage_record.py+++ b/products/business_knowledge/backend/models/knowledge_usage_record.py@@ -18,8 +18,8 @@ class KnowledgeUsageRecord(UUIDModel):write records nothing. Retrieval writes one row per search. Rows are never updated, and deleting thesource, document or chunks they describe leaves them in place, so a delete never removes usage.- Nothing reads this table for billing yet. It meters usage so the pricing can be checked against real- data before the usage report and the billing service start counting it.+ The nightly usage report reads this table. The billing service receives the totals but does not charge+ for them until it has Business Knowledge products."""# Canonical team, no FK: deleting a team must not cascade into usage history.diff --git a/products/business_knowledge/backend/tests/test_billing.py b/products/business_knowledge/backend/tests/test_billing.pyindex c432de45bed6..126d385b6913 100644--- a/products/business_knowledge/backend/tests/test_billing.py+++ b/products/business_knowledge/backend/tests/test_billing.py@@ -1,4 +1,5 @@import asyncio+from datetime import UTC, datetimefrom uuid import UUIDfrom posthog.test.base import BaseTest@@ -11,6 +12,7 @@ from posthog.models.scoping import team_scopefrom posthog.models.team import Teamfrom products.business_knowledge.backend import billing, logic+from products.business_knowledge.backend.facade import api as facade_apifrom products.business_knowledge.backend.llm_telemetry import RetrievalTrace, stable_trace_idfrom products.business_knowledge.backend.models import (KnowledgeChunk,@@ -186,3 +188,36 @@ class TestRetrievalMetering(_UsageTest):def test_stable_trace_ids_repeat_for_the_same_parts_only(self) -> None:assert stable_trace_id("a", 1) == stable_trace_id("a", 1)assert stable_trace_id("a", 1) != stable_trace_id("a", 2)+++class TestUsageByTeam(_UsageTest):+ PERIOD_START = datetime(2026, 1, 2, tzinfo=UTC)+ PERIOD_END = datetime(2026, 1, 3, tzinfo=UTC)++ def _record(self, usage_key: KnowledgeUsageKey, quantity: int, created_at: datetime, team_id: int) -> None:+ row = KnowledgeUsageRecord.objects.unscoped().create(+ team_id=team_id, usage_key=usage_key, quantity=quantity, surface="text"+ )+ # `created_at` is set on insert, so move the row into the period afterwards.+ KnowledgeUsageRecord.objects.unscoped().filter(id=row.id).update(created_at=created_at)++ def test_sums_each_meter_per_team_for_rows_written_in_the_period(self) -> None:+ other = Team.objects.create(organization=self.organization, name="Other project")+ inside = datetime(2026, 1, 2, 12, tzinfo=UTC)+ self._record(KnowledgeUsageKey.CHUNKS, 3, inside, self.team.id)+ self._record(KnowledgeUsageKey.CHUNKS, 4, inside, self.team.id)+ self._record(KnowledgeUsageKey.QUERIES, 1, inside, self.team.id)+ self._record(KnowledgeUsageKey.QUERIES, 1, inside, other.id)+ self._record(KnowledgeUsageKey.CHUNKS, 9, datetime(2026, 1, 1, 23, 59, tzinfo=UTC), self.team.id)+ self._record(KnowledgeUsageKey.QUERIES, 1, self.PERIOD_END, self.team.id)++ usage = facade_api.get_usage_by_team(self.PERIOD_START, self.PERIOD_END)++ assert usage.chunks == [(self.team.id, 7)]+ assert sorted(usage.queries) == sorted([(self.team.id, 1), (other.id, 1)])++ def test_no_usage_returns_empty_meters(self) -> None:+ usage = facade_api.get_usage_by_team(self.PERIOD_START, self.PERIOD_END)++ assert usage.chunks == []+ assert usage.queries == []