: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(usage-ingestion): add django client observability (#100170)
Ben Whitefec4f08c7f78
diff --git a/posthog/usage_ingestion/client.py b/posthog/usage_ingestion/client.pyindex 37a3e023d775..12e7a18f3c0c 100644--- a/posthog/usage_ingestion/client.py+++ b/posthog/usage_ingestion/client.py@@ -1,16 +1,49 @@import os+import asynciofrom collections.abc import Iterablefrom dataclasses import field-from time import time+from time import sleep, timeimport grpcimport structlog+from prometheus_client import Counterfrom posthog.dataclasses import frozenfrom posthog.usage_ingestion.generated.usage_ingestion.v1 import service_pb2, service_pb2_grpclogger = structlog.get_logger(__name__)+USAGE_INGESTION_RECORDS_SENT_TOTAL = Counter(+ "usage_ingestion_records_sent_total",+ "Usage records accepted by the usage-ingestion service.",+ labelnames=["producer_id", "usage_key"],+)++USAGE_INGESTION_RECORDS_FAILED_TOTAL = Counter(+ "usage_ingestion_records_failed_total",+ "Usage records dropped after the client exhausted its retries.",+ labelnames=["producer_id", "usage_key", "error_code"],+)++USAGE_INGESTION_RETRIES_TOTAL = Counter(+ "usage_ingestion_retries_total",+ "Ingest calls retried after a transient error.",+ labelnames=["producer_id", "error_code"],+)++RETRYABLE_CODES = frozenset(+ {+ grpc.StatusCode.UNAVAILABLE,+ grpc.StatusCode.DEADLINE_EXCEEDED,+ grpc.StatusCode.RESOURCE_EXHAUSTED,+ grpc.StatusCode.ABORTED,+ grpc.StatusCode.CANCELLED,+ grpc.StatusCode.INTERNAL,+ }+)+MAX_ATTEMPTS = 3+RETRY_BACKOFF_SECONDS = 0.1+@frozenclass UsageRecord:@@ -59,6 +92,46 @@ def _request(records: list[UsageRecord]) -> service_pb2.IngestBillingUsageReques)+def _error_code(error: Exception) -> tuple[grpc.StatusCode | None, str]:+ if isinstance(error, grpc.RpcError):+ try:+ code = error.code()+ return code, code.name.replace("_", " ").title().replace(" ", "")+ except Exception:+ pass+ return None, "Unknown"+++def _record_response(records: list[UsageRecord], response: service_pb2.IngestBillingUsageResponse) -> None:+ accepted = set(response.accepted_record_ids)+ for record in records:+ counter = (+ USAGE_INGESTION_RECORDS_SENT_TOTAL if record.record_id in accepted else USAGE_INGESTION_RECORDS_FAILED_TOTAL+ )+ labels = {"producer_id": record.producer_id, "usage_key": record.usage_key}+ if record.record_id not in accepted:+ labels["error_code"] = "rejected"+ counter.labels(**labels).inc()+++def _record_failure(records: list[UsageRecord], error_code: str) -> None:+ for record in records:+ USAGE_INGESTION_RECORDS_FAILED_TOTAL.labels(+ producer_id=record.producer_id,+ usage_key=record.usage_key,+ error_code=error_code,+ ).inc()+++def _retry_delay_seconds(records: list[UsageRecord], attempt: int, error: Exception) -> float:+ status, error_code = _error_code(error)+ if attempt + 1 < MAX_ATTEMPTS and status in RETRYABLE_CODES:+ USAGE_INGESTION_RETRIES_TOTAL.labels(producer_id=records[0].producer_id, error_code=error_code).inc()+ return RETRY_BACKOFF_SECONDS * 2**attempt+ _record_failure(records, error_code)+ raise error++# Every producer calls these after committing work of its own, and the nightly report is still# the billing source of truth, so a record is worth less than the caller it runs in. Nothing# escapes either function — not a bad address, not an unencodable field, not an RPC error.@@ -66,15 +139,24 @@ def _request(records: list[UsageRecord]) -> service_pb2.IngestBillingUsageRequesdef report_usage(records: Iterable[UsageRecord], *, site: str) -> None:- enabled, address = _to_send(records)- if not enabled or not address:- return-+ enabled: list[UsageRecord] = []try:+ enabled, address = _to_send(records)+ if not enabled or not address:+ returnwith grpc.insecure_channel(address) as channel:- service_pb2_grpc.UsageIngestionStub(channel).IngestBillingUsage(- _request(enabled), timeout=_timeout_seconds()- )+ stub = service_pb2_grpc.UsageIngestionStub(channel)+ for attempt in range(MAX_ATTEMPTS):+ try:+ response = stub.IngestBillingUsage(+ _request(enabled),+ timeout=_timeout_seconds(),+ metadata=(("x-client-name", enabled[0].producer_id),),+ )+ _record_response(enabled, response)+ return+ except Exception as error:+ sleep(_retry_delay_seconds(enabled, attempt, error))except Exception:logger.warning("usage_ingestion_report_failed", site=site, records=len(enabled), exc_info=True)@@ -85,14 +167,23 @@ async def areport_usage(records: Iterable[UsageRecord], *, site: str) -> None:Prefer this to `asyncio.to_thread(report_usage, ...)`: that borrows a worker from the defaultexecutor, which a hot loop of `to_thread` calls has exhausted before."""- enabled, address = _to_send(records)- if not enabled or not address:- return-+ enabled: list[UsageRecord] = []try:+ enabled, address = _to_send(records)+ if not enabled or not address:+ returnasync with grpc.aio.insecure_channel(address) as channel:- await service_pb2_grpc.UsageIngestionStub(channel).IngestBillingUsage(- _request(enabled), timeout=_timeout_seconds()- )+ stub = service_pb2_grpc.UsageIngestionStub(channel)+ for attempt in range(MAX_ATTEMPTS):+ try:+ response = await stub.IngestBillingUsage(+ _request(enabled),+ timeout=_timeout_seconds(),+ metadata=(("x-client-name", enabled[0].producer_id),),+ )+ _record_response(enabled, response)+ return+ except Exception as error:+ await asyncio.sleep(_retry_delay_seconds(enabled, attempt, error))except Exception:logger.warning("usage_ingestion_report_failed", site=site, records=len(enabled), exc_info=True)diff --git a/posthog/usage_ingestion/test_client.py b/posthog/usage_ingestion/test_client.pyindex b44bb0b717a8..6c269f2cb324 100644--- a/posthog/usage_ingestion/test_client.py+++ b/posthog/usage_ingestion/test_client.py@@ -1,15 +1,37 @@+from dataclasses import replace+import pytest-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, call, patchimport grpc+from posthog.usage_ingestion import clientfrom posthog.usage_ingestion.client import UsageRecord, _timeout_seconds, areport_usage, report_usage, team_is_enabled+from posthog.usage_ingestion.generated.usage_ingestion.v1 import service_pb2ERRORS = [grpc.RpcError(), RuntimeError("boom")]REPORTING_ENV = {"USAGE_INGESTION_ADDR": "localhost:1", "USAGE_INGESTION_REPORT_TEAMS": "*"}RECORD = UsageRecord(record_id="r", producer_id="p", team_id=2, usage_key="k", unit="rows", quantity=1)+def _rpc_error(status_code: grpc.StatusCode) -> grpc.RpcError:+ error = grpc.RpcError()+ error.code = lambda: status_code+ return error+++def _channel() -> MagicMock:+ channel = MagicMock()+ channel.__enter__.return_value = channel+ return channel+++def _async_channel() -> MagicMock:+ channel = MagicMock()+ channel.__aenter__.return_value = channel+ return channel++def test_team_is_enabled_uses_the_shared_team_list(monkeypatch) -> None:monkeypatch.setenv("USAGE_INGESTION_REPORT_TEAMS", "2, 4")@@ -32,6 +54,139 @@ def test_timeout_converts_milliseconds_to_the_seconds_grpc_expects(monkeypatch)assert _timeout_seconds() == 0.25+ ("accepted_ids", "sent", "failed"),+ [+ (["r", "r-2"], ["k", "k-2"], []),+ (["r"], ["k"], ["k-2"]),+ ],+ ids=["accepted", "partially_rejected"],+)+def test_reporting_counts_only_records_accepted_by_the_service(+ monkeypatch, accepted_ids: list[str], sent: list[str], failed: list[str]+) -> None:+ records = [RECORD, replace(RECORD, record_id="r-2", usage_key="k-2")]+ channel = _channel()+ stub = MagicMock()+ stub.IngestBillingUsage.return_value = service_pb2.IngestBillingUsageResponse(accepted_record_ids=accepted_ids)+ sent_counter = MagicMock()+ failed_counter = MagicMock()+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_SENT_TOTAL", sent_counter)+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_FAILED_TOTAL", failed_counter)++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ report_usage(records, site="test")++ assert sent_counter.labels.call_args_list == [call(producer_id="p", usage_key=usage_key) for usage_key in sent]+ assert failed_counter.labels.call_args_list == [+ call(producer_id="p", usage_key=usage_key, error_code="rejected") for usage_key in failed+ ]+++def test_reporting_names_the_producer_in_grpc_metadata() -> None:+ channel = _channel()+ stub = MagicMock()+ stub.IngestBillingUsage.return_value = service_pb2.IngestBillingUsageResponse(accepted_record_ids=["r"])++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ report_usage([RECORD], site="test")++ assert stub.IngestBillingUsage.call_args.kwargs["metadata"] == (("x-client-name", "p"),)+++def test_reporting_counts_terminal_grpc_failures(monkeypatch) -> None:+ channel = _channel()+ stub = MagicMock()+ stub.IngestBillingUsage.side_effect = _rpc_error(grpc.StatusCode.INVALID_ARGUMENT)+ failed_counter = MagicMock()+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_FAILED_TOTAL", failed_counter)++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ report_usage([RECORD], site="test")++ assert failed_counter.labels.call_args_list == [call(producer_id="p", usage_key="k", error_code="InvalidArgument")]+++def test_reporting_retries_transient_grpc_failures(monkeypatch) -> None:+ channel = _channel()+ stub = MagicMock()+ stub.IngestBillingUsage.side_effect = [+ _rpc_error(grpc.StatusCode.UNAVAILABLE),+ service_pb2.IngestBillingUsageResponse(accepted_record_ids=["r"]),+ ]+ retries_counter = MagicMock()+ sent_counter = MagicMock()+ monkeypatch.setattr(client, "USAGE_INGESTION_RETRIES_TOTAL", retries_counter)+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_SENT_TOTAL", sent_counter)++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ with patch("posthog.usage_ingestion.client.sleep") as sleep:+ report_usage([RECORD], site="test")++ assert stub.IngestBillingUsage.call_count == 2+ assert retries_counter.labels.call_args_list == [call(producer_id="p", error_code="Unavailable")]+ sleep.assert_called_once_with(0.1)+ sent_counter.labels.assert_called_once_with(producer_id="p", usage_key="k")+++def test_reporting_drops_records_after_exhausting_transient_retries(monkeypatch) -> None:+ channel = _channel()+ stub = MagicMock()+ stub.IngestBillingUsage.side_effect = [_rpc_error(grpc.StatusCode.UNAVAILABLE) for _ in range(3)]+ retries_counter = MagicMock()+ failed_counter = MagicMock()+ monkeypatch.setattr(client, "USAGE_INGESTION_RETRIES_TOTAL", retries_counter)+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_FAILED_TOTAL", failed_counter)++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ with patch("posthog.usage_ingestion.client.sleep") as sleep:+ report_usage([RECORD], site="test")++ assert stub.IngestBillingUsage.call_count == 3+ assert retries_counter.labels.call_args_list == [+ call(producer_id="p", error_code="Unavailable"),+ call(producer_id="p", error_code="Unavailable"),+ ]+ assert failed_counter.labels.call_args_list == [call(producer_id="p", usage_key="k", error_code="Unavailable")]+ assert sleep.call_args_list == [call(0.1), call(0.2)]+++async def test_async_reporting_retries_transient_grpc_failures(monkeypatch) -> None:+ channel = _async_channel()+ stub = MagicMock()+ stub.IngestBillingUsage = AsyncMock(+ side_effect=[+ _rpc_error(grpc.StatusCode.UNAVAILABLE),+ service_pb2.IngestBillingUsageResponse(accepted_record_ids=["r"]),+ ]+ )+ retries_counter = MagicMock()+ sent_counter = MagicMock()+ monkeypatch.setattr(client, "USAGE_INGESTION_RETRIES_TOTAL", retries_counter)+ monkeypatch.setattr(client, "USAGE_INGESTION_RECORDS_SENT_TOTAL", sent_counter)++ with patch.dict("os.environ", REPORTING_ENV):+ with patch("posthog.usage_ingestion.client.grpc.aio.insecure_channel", return_value=channel):+ with patch("posthog.usage_ingestion.client.service_pb2_grpc.UsageIngestionStub", return_value=stub):+ with patch("posthog.usage_ingestion.client.asyncio.sleep", new_callable=AsyncMock) as sleep:+ await areport_usage([RECORD], site="test")++ assert stub.IngestBillingUsage.call_count == 2+ assert retries_counter.labels.call_args_list == [call(producer_id="p", error_code="Unavailable")]+ sleep.assert_awaited_once_with(0.1)+ sent_counter.labels.assert_called_once_with(producer_id="p", usage_key="k")++# Every producer calls these after committing work of its own, so a raise here fails an activity# that is already done, and the retry re-runs everything that ran before it.@pytest.mark.parametrize("error", ERRORS)