: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-reports): add pipeline health metrics to the v2 sender (#67922)
Marce Collabb043ac9f7f
diff --git a/posthog/temporal/ai_observability/test_metrics.py b/posthog/temporal/ai_observability/test_metrics.pyindex 05374e5c358d..6e41836a3782 100644--- a/posthog/temporal/ai_observability/test_metrics.py+++ b/posthog/temporal/ai_observability/test_metrics.py@@ -37,7 +37,8 @@ class TestExecutionTimeRecorder:call_args = mock_get.call_args[0][0]assert call_args["status"] == "FAILED"- assert call_args["exception"] == "test error"+ # Class name, not the message — free-form messages would explode label cardinality.+ assert call_args["exception"] == "ValueError"def test_raises_if_not_entered(self):"""Test that __exit__ raises if __enter__ was not called"""diff --git a/posthog/temporal/common/metrics.py b/posthog/temporal/common/metrics.pyindex 257d0c197716..f64ad3a3fccc 100644--- a/posthog/temporal/common/metrics.py+++ b/posthog/temporal/common/metrics.py@@ -60,16 +60,20 @@ class ExecutionTimeRecorder:attributes = dict(self.histogram_attributes)if exc_value is not None:attributes["status"] = "FAILED"- attributes["exception"] = str(exc_value)+ # Class name, not str(exc): a free-form message would explode label cardinality.+ attributes["exception"] = type(exc_value).__name__elif self._status_override is not None:attributes["status"] = self._status_overrideattributes["exception"] = ""else:attributes["status"] = "COMPLETED"attributes["exception"] = ""- meter = get_metric_meter(attributes)- hist = meter.create_histogram_timedelta(name=self.histogram_name, description=self.description, unit="ms")+ # The whole metric path is best-effort: meter acquisition can raise+ # too (e.g. outside an activity/workflow context), and a metric-layer+ # failure must never fail the wrapped block or mask its exception.try:+ meter = get_metric_meter(attributes)+ hist = meter.create_histogram_timedelta(name=self.histogram_name, description=self.description, unit="ms")hist.record(value=delta)except Exception:LOGGER.exception("Failed to record execution time to histogram '%s'", self.histogram_name)diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex f6bf565032dc..3c6176192454 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -51,6 +51,10 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep.metrics import (SURFACING_SCORING_LATENCY_HISTOGRAM_METRICS,SurfacingScoringMetricsInterceptor,)+from posthog.temporal.usage_report.metrics import (+ USAGE_REPORTS_LATENCY_HISTOGRAM_BUCKETS,+ USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS,+)from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptorfrom products.experiments.backend.temporal.recalculation_metrics import (@@ -301,6 +305,7 @@ async def create_worker()| dict(zip(LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(LOGS_ALERTING_COUNT_HISTOGRAM_METRICS, itertools.repeat(LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS)))+ | dict(zip(USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(USAGE_REPORTS_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,diff --git a/posthog/temporal/tests/usage_report/test_pointer_activity.py b/posthog/temporal/tests/usage_report/test_pointer_activity.pyindex 452d4cb2f49f..23c9548c56ee 100644--- a/posthog/temporal/tests/usage_report/test_pointer_activity.py+++ b/posthog/temporal/tests/usage_report/test_pointer_activity.py@@ -164,6 +164,38 @@ async def test_pointer_raises_when_send_returns_none(activity_environment) -> No)+async def test_pointer_send_survives_post_send_metric_failure(activity_environment) -> None:+ """A metric-layer failure after the SQS send must not fail the activity.++ The pointer is already delivered at that point — if the activity raised,+ Temporal would retry it and billing would receive a duplicate pointer.+ """+ fake_producer = MagicMock()+ fake_producer.send_message.return_value = {"MessageId": "abc"}++ with (+ patch("posthog.temporal.usage_report.activities.settings") as mock_settings,+ patch("posthog.temporal.usage_report.activities.bucket", return_value="posthog"),+ patch("ee.sqs.SQSProducer.get_sqs_producer", return_value=fake_producer),+ patch("posthog.temporal.usage_report.activities.get_instance_region", return_value="US"),+ patch(+ "posthog.temporal.usage_report.activities.record_aggregate_output",+ side_effect=RuntimeError("metrics backend down"),+ ),+ ):+ mock_settings.EE_AVAILABLE = True+ mock_settings.SITE_URL = "https://us.posthog.com"++ await activity_environment.run(+ enqueue_pointer_message,+ EnqueuePointerInputs(ctx=_ctx(), aggregate=_agg()),+ )++ # Sent exactly once — and the metric failure did not bubble out.+ fake_producer.send_message.assert_called_once()++def test_v2_queue_is_configured_in_settings() -> None:queues = getattr(settings, "SQS_QUEUES", {})assert SQS_QUEUE_NAME in queues, (diff --git a/posthog/temporal/usage_report/activities.py b/posthog/temporal/usage_report/activities.pyindex 8c70ec690d99..f33389a052b6 100644--- a/posthog/temporal/usage_report/activities.py+++ b/posthog/temporal/usage_report/activities.py@@ -20,6 +20,7 @@ from temporalio import activityfrom posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.tasks.usage_report import get_instance_metadatafrom posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.common.metrics import ExecutionTimeRecorderfrom posthog.temporal.usage_report.aggregator import (batched,build_manifest,@@ -31,6 +32,14 @@ from posthog.temporal.usage_report.aggregator import (load_all_data,sort_org_reports,)+from posthog.temporal.usage_report.metrics import (+ USAGE_REPORTS_AGGREGATE_LATENCY,+ USAGE_REPORTS_ENQUEUE_LATENCY,+ USAGE_REPORTS_QUERY_LATENCY,+ get_pointer_messages_sent_metric,+ record_aggregate_output,+ record_pointer_sent_timestamp,+)from posthog.temporal.usage_report.queries import QUERY_INDEXfrom posthog.temporal.usage_report.storage import (bucket,@@ -72,33 +81,38 @@ async def run_query_to_s3(inputs: RunQueryToS3Inputs) -> RunQueryToS3Result:well under Temporal's payload limits)."""async with Heartbeater():- spec = QUERY_INDEX[inputs.query_name]-- # Use the pooled variant so concurrent query activities on the same- # worker actually run in parallel. The default thread_sensitive=True- # serializes everything onto a single shared thread, defeating the- # bounded fan-out in the workflow.- @database_sync_to_async_pool- def run() -> Any:- # Snapshot specs ignore the period (they read current state);- # period specs filter on (begin, end). The signature is enforced- # by `QuerySpec.fn`'s union type and validated in registry tests.- if spec.kind == "snapshot":- return spec.fn() # type: ignore[call-arg]- return spec.fn(inputs.ctx.period_start, inputs.ctx.period_end) # type: ignore[call-arg]-- started = time.monotonic()- result = await run()- duration_ms = int((time.monotonic() - started) * 1000)-- key = queries_key(inputs.ctx, inputs.query_name)- await sync_to_async(write_json)(key, result)-- return RunQueryToS3Result(- query_name=inputs.query_name,- s3_key=key,- duration_ms=duration_ms,- )+ with ExecutionTimeRecorder(+ USAGE_REPORTS_QUERY_LATENCY,+ description="Run one usage-reports gather query and write its result to S3.",+ histogram_attributes={"query_name": inputs.query_name},+ ):+ spec = QUERY_INDEX[inputs.query_name]++ # Use the pooled variant so concurrent query activities on the same+ # worker actually run in parallel. The default thread_sensitive=True+ # serializes everything onto a single shared thread, defeating the+ # bounded fan-out in the workflow.+ @database_sync_to_async_pool+ def run() -> Any:+ # Snapshot specs ignore the period (they read current state);+ # period specs filter on (begin, end). The signature is enforced+ # by `QuerySpec.fn`'s union type and validated in registry tests.+ if spec.kind == "snapshot":+ return spec.fn() # type: ignore[call-arg]+ return spec.fn(inputs.ctx.period_start, inputs.ctx.period_end) # type: ignore[call-arg]++ started = time.monotonic()+ result = await run()+ duration_ms = int((time.monotonic() - started) * 1000)++ key = queries_key(inputs.ctx, inputs.query_name)+ await sync_to_async(write_json)(key, result)++ return RunQueryToS3Result(+ query_name=inputs.query_name,+ s3_key=key,+ duration_ms=duration_ms,+ )@activity.defn(name="aggregate-and-chunk-org-reports")@@ -110,71 +124,75 @@ async def aggregate_and_chunk_org_reports(inputs: AggregateInputs) -> AggregateRCelery flow so we can validate parity before billing cuts over."""async with Heartbeater():- all_data = await sync_to_async(load_all_data)(inputs.query_results)-- @database_sync_to_async- def aggregate_per_org() -> dict[str, Any]:- # Bulk-fetch membership counts once instead of letting the org- # builder issue a Postgres count() per organization. See- # `aggregator.build_org_reports` for the rationale.- org_user_counts = get_org_user_counts()- org_reports = build_org_reports(all_data, inputs.ctx.period_start, org_user_counts)- org_reports = filter_org_reports(org_reports, inputs.ctx.organization_ids)- return org_reports-- org_reports = await aggregate_per_org()-- instance_metadata = await database_sync_to_async(get_instance_metadata)(- (inputs.ctx.period_start, inputs.ctx.period_end)- )-- # TODO(usage-reports-v2): re-enable PostHog product-analytics- # `capture_report` per organization once the billing path is validated.- # That call updates organization group properties (member/project/dashboard- # counts) used by customer.io segmentation and emits the- # "organization usage report" event consumed for internal analytics.-- total_orgs = len(org_reports)- orgs_with_usage = filter_orgs_with_usage(org_reports)- total_orgs_with_usage = len(orgs_with_usage)-- sorted_reports = sort_org_reports(orgs_with_usage)- batches = list(enumerate(batched(sorted_reports, CHUNK_SIZE_ORGS)))- chunk_keys: list[str] = [chunk_key(inputs.ctx, index) for index, _ in batches]-- # Each chunk is an independent S3 object, so fan the encode+gzip+PUT- # out across the thread pool. `thread_sensitive=False` opts out of- # the shared-thread default so the PUTs run concurrently — boto3- # releases the GIL during the network call, so they genuinely- # overlap on the wire. Using `asyncio.TaskGroup` (over- # `asyncio.gather`) means a single failed upload doesn't cancel- # in-flight peer uploads mid-PUT; the group waits for every- # started task to finish or fail before re-raising, so Temporal- # retries from a clean state.- def write_chunk(key: str, batch: list[Any]) -> None:- write_jsonl_chunk_gzip(key, iter_chunk_lines(batch, instance_metadata))-- async with asyncio.TaskGroup() as tg:- for index, batch in batches:- tg.create_task(sync_to_async(write_chunk, thread_sensitive=False)(chunk_keys[index], batch))-- manifest = build_manifest(- inputs.ctx,- chunk_keys=chunk_keys,- total_orgs=total_orgs,- total_orgs_with_usage=total_orgs_with_usage,- region=get_instance_region() or "",- version=SQS_POINTER_VERSION,- )- m_key = manifest_key(inputs.ctx)- await sync_to_async(write_json)(m_key, manifest.model_dump(mode="json"))-- return AggregateResult(- chunk_keys=chunk_keys,- manifest_key=m_key,- total_orgs=total_orgs,- total_orgs_with_usage=total_orgs_with_usage,- )+ with ExecutionTimeRecorder(+ USAGE_REPORTS_AGGREGATE_LATENCY,+ description="Aggregate per-query S3 results into org-report chunks.",+ ):+ all_data = await sync_to_async(load_all_data)(inputs.query_results)++ @database_sync_to_async+ def aggregate_per_org() -> dict[str, Any]:+ # Bulk-fetch membership counts once instead of letting the org+ # builder issue a Postgres count() per organization. See+ # `aggregator.build_org_reports` for the rationale.+ org_user_counts = get_org_user_counts()+ org_reports = build_org_reports(all_data, inputs.ctx.period_start, org_user_counts)+ org_reports = filter_org_reports(org_reports, inputs.ctx.organization_ids)+ return org_reports++ org_reports = await aggregate_per_org()++ instance_metadata = await database_sync_to_async(get_instance_metadata)(+ (inputs.ctx.period_start, inputs.ctx.period_end)+ )++ # TODO(usage-reports-v2): re-enable PostHog product-analytics+ # `capture_report` per organization once the billing path is validated.+ # That call updates organization group properties (member/project/dashboard+ # counts) used by customer.io segmentation and emits the+ # "organization usage report" event consumed for internal analytics.++ total_orgs = len(org_reports)+ orgs_with_usage = filter_orgs_with_usage(org_reports)+ total_orgs_with_usage = len(orgs_with_usage)++ sorted_reports = sort_org_reports(orgs_with_usage)+ batches = list(enumerate(batched(sorted_reports, CHUNK_SIZE_ORGS)))+ chunk_keys: list[str] = [chunk_key(inputs.ctx, index) for index, _ in batches]++ # Each chunk is an independent S3 object, so fan the encode+gzip+PUT+ # out across the thread pool. `thread_sensitive=False` opts out of+ # the shared-thread default so the PUTs run concurrently — boto3+ # releases the GIL during the network call, so they genuinely+ # overlap on the wire. Using `asyncio.TaskGroup` (over+ # `asyncio.gather`) means a single failed upload doesn't cancel+ # in-flight peer uploads mid-PUT; the group waits for every+ # started task to finish or fail before re-raising, so Temporal+ # retries from a clean state.+ def write_chunk(key: str, batch: list[Any]) -> None:+ write_jsonl_chunk_gzip(key, iter_chunk_lines(batch, instance_metadata))++ async with asyncio.TaskGroup() as tg:+ for index, batch in batches:+ tg.create_task(sync_to_async(write_chunk, thread_sensitive=False)(chunk_keys[index], batch))++ manifest = build_manifest(+ inputs.ctx,+ chunk_keys=chunk_keys,+ total_orgs=total_orgs,+ total_orgs_with_usage=total_orgs_with_usage,+ region=get_instance_region() or "",+ version=SQS_POINTER_VERSION,+ )+ m_key = manifest_key(inputs.ctx)+ await sync_to_async(write_json)(m_key, manifest.model_dump(mode="json"))++ return AggregateResult(+ chunk_keys=chunk_keys,+ manifest_key=m_key,+ total_orgs=total_orgs,+ total_orgs_with_usage=total_orgs_with_usage,+ )@activity.defn(name="usage-reports-enqueue-pointer-message")@@ -184,45 +202,67 @@ async def enqueue_pointer_message(inputs: EnqueuePointerInputs) -> None:Body is plain JSON describing where to find the gzipped chunks; billingreads the actual usage data from S3."""- if not settings.EE_AVAILABLE:- await logger.awarning("usage_reports.sqs.skipped_no_ee")- return-- pointer = {- "version": SQS_POINTER_VERSION,- "run_id": inputs.ctx.run_id,- "date": inputs.ctx.date_str,- "period_start": inputs.ctx.period_start.isoformat(),- "period_end": inputs.ctx.period_end.isoformat(),- "region": get_instance_region(),- "site_url": settings.SITE_URL,- "bucket": bucket(),- "manifest_key": inputs.aggregate.manifest_key,- "chunk_prefix": chunks_prefix(inputs.ctx) + "/",- "chunk_count": len(inputs.aggregate.chunk_keys),- "total_orgs": inputs.aggregate.total_orgs,- "total_orgs_with_usage": inputs.aggregate.total_orgs_with_usage,- }-- @sync_to_async- def send() -> None:- from ee.sqs.SQSProducer import get_sqs_producer-- producer = get_sqs_producer(SQS_QUEUE_NAME)- if producer is None:- raise RuntimeError(f"SQS producer for queue '{SQS_QUEUE_NAME}' is not configured")- response = producer.send_message(- message_body=json.dumps(pointer, separators=(",", ":")),- message_attributes={- "content_type": "application/json",- "schema_version": str(SQS_POINTER_VERSION),- "run_id": inputs.ctx.run_id,- },- )- if response is None:- raise RuntimeError("SQS send_message returned no response")-- await send()+ with ExecutionTimeRecorder(+ USAGE_REPORTS_ENQUEUE_LATENCY,+ description="Send the usage-reports v2 SQS pointer message to billing.",+ ) as recorder:+ if not settings.EE_AVAILABLE:+ recorder.set_status("SKIPPED")+ try:+ get_pointer_messages_sent_metric(outcome="skipped_no_ee").add(1)+ except Exception as err:+ await logger.awarning("usage_reports.metrics.record_failed", error=str(err))+ await logger.awarning("usage_reports.sqs.skipped_no_ee")+ return++ pointer = {+ "version": SQS_POINTER_VERSION,+ "run_id": inputs.ctx.run_id,+ "date": inputs.ctx.date_str,+ "period_start": inputs.ctx.period_start.isoformat(),+ "period_end": inputs.ctx.period_end.isoformat(),+ "region": get_instance_region(),+ "site_url": settings.SITE_URL,+ "bucket": bucket(),+ "manifest_key": inputs.aggregate.manifest_key,+ "chunk_prefix": chunks_prefix(inputs.ctx) + "/",+ "chunk_count": len(inputs.aggregate.chunk_keys),+ "total_orgs": inputs.aggregate.total_orgs,+ "total_orgs_with_usage": inputs.aggregate.total_orgs_with_usage,+ }++ @sync_to_async+ def send() -> None:+ from ee.sqs.SQSProducer import get_sqs_producer++ producer = get_sqs_producer(SQS_QUEUE_NAME)+ if producer is None:+ raise RuntimeError(f"SQS producer for queue '{SQS_QUEUE_NAME}' is not configured")+ response = producer.send_message(+ message_body=json.dumps(pointer, separators=(",", ":")),+ message_attributes={+ "content_type": "application/json",+ "schema_version": str(SQS_POINTER_VERSION),+ "run_id": inputs.ctx.run_id,+ },+ )+ if response is None:+ raise RuntimeError("SQS send_message returned no response")++ await send()+ # Best-effort from here down: the pointer is already delivered, so a+ # metric-layer failure must not fail the activity — Temporal would+ # retry it and send billing a duplicate pointer.+ try:+ get_pointer_messages_sent_metric(outcome="sent").add(1)+ record_aggregate_output(+ total_orgs=inputs.aggregate.total_orgs,+ total_orgs_with_usage=inputs.aggregate.total_orgs_with_usage,+ chunk_count=len(inputs.aggregate.chunk_keys),+ )+ record_pointer_sent_timestamp()+ except Exception as err:+ await logger.awarning("usage_reports.metrics.record_failed", error=str(err))@activity.defn(name="usage-reports-cleanup-intermediates")diff --git a/posthog/temporal/usage_report/metrics.py b/posthog/temporal/usage_report/metrics.pynew file mode 100644index 000000000000..e26d19c8d4db--- /dev/null+++ b/posthog/temporal/usage_report/metrics.py@@ -0,0 +1,105 @@+"""Metric helpers for the usage-reports v2 sender pipeline.++Everything records through the Temporal SDK metric meter (see+`posthog.temporal.common.metrics.get_metric_meter`), so these series ride the+worker's combined Prometheus endpoint alongside the built-in `temporal_*`+metrics. Billing consumes the matching receiver-side metrics+(`billing_sqs_usage_reports_v2_*` / `billing_temporal_usage_reports_v2_*`);+together they back the "Usage Reports v2" Grafana dashboard.+"""++import time+from datetime import timedelta++from temporalio.common import MetricCounter++from posthog.temporal.common.metrics import get_metric_meter++USAGE_REPORTS_QUERY_LATENCY = "usage_reports_v2_query_latency"+USAGE_REPORTS_AGGREGATE_LATENCY = "usage_reports_v2_aggregate_latency"+USAGE_REPORTS_ENQUEUE_LATENCY = "usage_reports_v2_enqueue_latency"+USAGE_REPORTS_WORKFLOW_LATENCY = "usage_reports_v2_workflow_latency"++# Registered with `histogram_bucket_overrides` in+# `posthog.temporal.common.worker`: gather queries run up to 30 minutes,+# aggregation up to an hour, and the whole workflow can span a few hours —+# far beyond the SDK's default (sub-minute) buckets.+USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS = (+ USAGE_REPORTS_QUERY_LATENCY,+ USAGE_REPORTS_AGGREGATE_LATENCY,+ USAGE_REPORTS_ENQUEUE_LATENCY,+ USAGE_REPORTS_WORKFLOW_LATENCY,+)+USAGE_REPORTS_LATENCY_HISTOGRAM_BUCKETS = [+ 100.0, # 100ms+ 500.0, # 500ms+ 1_000.0, # 1s+ 5_000.0, # 5s+ 15_000.0, # 15s+ 30_000.0, # 30s+ 60_000.0, # 1m+ 120_000.0, # 2m+ 300_000.0, # 5m+ 600_000.0, # 10m+ 900_000.0, # 15m+ 1_800_000.0, # 30m+ 3_600_000.0, # 1h+ 7_200_000.0, # 2h+ 14_400_000.0, # 4h+]+++def get_workflow_finished_metric(status: str) -> MetricCounter:+ return get_metric_meter({"status": status}).create_counter(+ "usage_reports_v2_workflow_finished",+ "Number of usage-reports v2 workflow runs finished, for any reason (including failure).",+ )+++def record_workflow_latency(delta: timedelta, status: str) -> None:+ get_metric_meter({"status": status}).create_histogram_timedelta(+ USAGE_REPORTS_WORKFLOW_LATENCY,+ "End-to-end wall-clock duration of one usage-reports v2 workflow run.",+ unit="ms",+ ).record(delta)+++def get_pointer_messages_sent_metric(outcome: str) -> MetricCounter:+ return get_metric_meter({"outcome": outcome}).create_counter(+ "usage_reports_v2_pointer_messages_sent",+ "SQS pointer messages handed to billing, by outcome (sent / skipped_no_ee).",+ )+++def record_aggregate_output(total_orgs: int, total_orgs_with_usage: int, chunk_count: int) -> None:+ """Record the last-run volume gauges.++ Called from the enqueue activity (not aggregation) so the whole last-run+ snapshot — volumes and sent-timestamp — is written by the same worker pod,+ and only for runs that actually handed a pointer to billing.+ """+ meter = get_metric_meter()+ meter.create_gauge(+ "usage_reports_v2_orgs_considered",+ "Organizations considered by the last usage-reports v2 run.",+ ).set(total_orgs)+ meter.create_gauge(+ "usage_reports_v2_orgs_with_usage",+ "Organizations with non-zero usage reported by the last usage-reports v2 run.",+ ).set(total_orgs_with_usage)+ meter.create_gauge(+ "usage_reports_v2_chunks_written",+ "JSONL chunks uploaded to S3 by the last usage-reports v2 run.",+ ).set(chunk_count)+++def record_pointer_sent_timestamp() -> None:+ """Stamp the wall-clock time of the last successful SQS pointer send.++ Dashboards read this as `time() - max_over_time(...)` to alert on a+ missed run, so it must only be set after the send succeeded.+ """+ get_metric_meter().create_gauge_float(+ "usage_reports_v2_last_pointer_sent_timestamp_seconds",+ "Unix timestamp of the last successfully sent usage-reports v2 SQS pointer.",+ ).set(time.time())diff --git a/posthog/temporal/usage_report/workflow.py b/posthog/temporal/usage_report/workflow.pyindex bb48faa8077f..7c93570a4298 100644--- a/posthog/temporal/usage_report/workflow.py+++ b/posthog/temporal/usage_report/workflow.py@@ -29,6 +29,7 @@ from posthog.temporal.usage_report.activities import (enqueue_pointer_message,run_query_to_s3,)+from posthog.temporal.usage_report.metrics import get_workflow_finished_metric, record_workflow_latencyfrom posthog.temporal.usage_report.queries import QUERIES, QuerySpecfrom posthog.temporal.usage_report.storage import run_prefixfrom posthog.temporal.usage_report.types import (@@ -72,6 +73,8 @@ class RunUsageReportsWorkflow(PostHogWorkflow):@workflow.runasync def run(self, inputs: RunUsageReportsInputs) -> dict:+ started_at = workflow.now()+ status = "FAILED"try:ctx = build_context(inputs, run_id=workflow.info().run_id, now=workflow.now())workflow.logger.info(@@ -144,11 +147,24 @@ class RunUsageReportsWorkflow(PostHogWorkflow):},)+ status = "COMPLETED"return agg.model_dump()+ except asyncio.CancelledError:+ status = "CANCELLED"+ raiseexcept Exception as err:workflow.logger.exception("Usage reports workflow failed", extra={"error": str(err)})capture_exception(err)raise+ finally:+ # Record exactly once, whichever way the run ends. Best-effort: a+ # metric-layer failure must not fail a successful run or mask the+ # original error.+ try:+ get_workflow_finished_metric(status=status).add(1)+ record_workflow_latency(workflow.now() - started_at, status=status)+ except Exception:+ workflow.logger.warning("Failed to record usage-reports workflow metrics", exc_info=True)async def _run_query(self, ctx: WorkflowContext, spec: QuerySpec) -> RunQueryToS3Result:return await workflow.execute_activity(