: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
fix(signals): keep a report metric when its snapshot time is unusable (#102561)
posthog[bot]3a9cbc4db58d
diff --git a/products/signals/backend/report_generation/AGENTS.md b/products/signals/backend/report_generation/AGENTS.mdindex 154c17decab9..546425939f9c 100644--- a/products/signals/backend/report_generation/AGENTS.md+++ b/products/signals/backend/report_generation/AGENTS.md@@ -99,7 +99,7 @@ The presentation step can also author up to six typed `metrics` alongside the pr- **One bounded live measurement.** Every metric has a live query built only from event or action sources, rejects breakdown and compare mode, and must produce exactly one output series. Without a formula that means exactly one source. A conversion or rate may combine at most ten event/action sources through exactly one formula output. The longitudinal result is capped at 1,000 estimated interval points, including the current partial bucket.- **A malformed metric costs the whole report.** `metrics` rides in the same `ReportPresentationOutput` as the title and summary, and `MultiTurnSession._parse_and_validate` calls `model_validate` with no retry, so one rejected item fails the research run with nothing persisted. `_resolve_report_metrics_payload` never sees it, because `metric_batch_error` only checks whole-set rules (count, total query characters, duplicate ids, one primary, one affected-users). This is the same tradeoff as a malformed chart, on a wider surface: `ReportMetric` carries about fifteen field validators plus a cross-field one, against four on `ReportChart`, so a metric has many more ways to fail late. Giving one metric its own degrade path needs a retry or a partial parse in the runner, which is shared with every other multi-turn caller. Until then the `signals-report-metrics` flag bounds who is exposed, and the authoring guidance keeps the surface small by telling the run to omit a metric it cannot measure honestly.- **Consumers own the display.** Authored Trends display is not the report presentation contract. Consumers derive `BoldNumber` for the first output series' whole-window `aggregated_value` and `ActionsBar` for longitudinal buckets. Every metric runs through both derived shapes and the normal query cache. The inbox does not maintain a separate time-series table.-- **Snapshots are optional fallbacks.** `value` and `value_at` travel together, preserve zero as measured data, and never replace the live query. Opening the inbox list or a report refreshes the stale snapshots on screen through the query cache without changing report ordering; there is no background job. Snapshot-only or queryless rows are legacy or malformed and are always redacted.+- **Snapshots are optional fallbacks.** `value` and `value_at` travel together, preserve zero as measured data, and never replace the live query. `value_at` is stored in UTC, whatever offset the author wrote; a measurement time still ahead of the server clock drops the snapshot and keeps the metric, so an unusable timestamp never costs the report. Opening the inbox list or a report refreshes the stale snapshots on screen through the query cache without changing report ordering; there is no background job. Snapshot-only or queryless rows are legacy or malformed and are always redacted.- **Independent opt-in.** Metrics use the organization-level `signals-report-metrics` flag (`report_content_gates.py`, on in DEBUG). Charts do not require a feature flag. When off, pipeline metric guidance and schema fields are removed and the caller preserves existing metrics. Every writer reads the flag, including the scout report channel, which drops a supplied set before the safety judge. Scout-authored metrics are safety-judged with the rest of the report.- **Replace, clear, or preserve as a set.** Metrics are the report's whole typed set. A valid non-empty pipeline result replaces them, an explicit or invalid enabled result clears them, and a disabled run returns `None` to preserve them. Scout edits use the same tri-state contract: omission preserves, `[]` clears, and a non-empty list replaces.- **Persistence is atomic with prose.** The agentic activity returns the resolved metric payload on `RunAgenticReportOutput.metrics`; the ready or pending-input transition writes it in the same transaction as title and summary. There is no partially updated report state.diff --git a/products/signals/backend/report_generation/research.py b/products/signals/backend/report_generation/research.pyindex 2f4e9f1852d6..28f57988ef6b 100644--- a/products/signals/backend/report_generation/research.py+++ b/products/signals/backend/report_generation/research.py@@ -589,7 +589,7 @@ Put reproducible report-level measurements under `metrics`. A metric tells the r- **Keep every metric live and bounded.** Give every metric an `InsightVizNode` wrapping a `TrendsQuery` you successfully ran in this research session. Every source series must be an `EventsNode` or `ActionsNode`. Use a relative window no longer than {MAX_LIVE_METRIC_WINDOW_DAYS} days and leave `date_to` empty. Default the query to `dateRange.date_from: "{DEFAULT_LIVE_METRIC_DATE_FROM}"` with `interval: "day"`. This gives 14 inclusive daily buckets, including today. The inbox strip shows at most the trailing 14 buckets. For a longer window, the strip is shorter than the whole-window figure and the caption says why the longer window is needed. The longitudinal output may contain at most {MAX_LIVE_METRIC_QUERY_POINTS} estimated interval points, including the current partial bucket.- **Consumers own the display.** The stored Trends definition remains the source of truth, but its authored display is not. Consumers derive `BoldNumber` for the first output series' whole-window `aggregated_value` and `ActionsBar` for its longitudinal buckets. Run the total-value shape when you author a snapshot; a bar or line response does not supply the whole-window total.- **Keep exactly one output series per query.** Do not use a breakdown or compare mode on any report metric. Without a formula, use exactly one source series. A conversion or rate may use up to {MAX_LIVE_METRIC_QUERY_SERIES} event/action source series as formula inputs, but it must define exactly one formula output.-- **Snapshots are optional cached fallbacks.** Send `value` and `value_at` together only for a value you observed, and write `value_at` as an ISO-8601 timestamp with a timezone. Zero is valid measured data. Null means no snapshot. Never invent a value from prose or estimate one from grouped signal count. A snapshot cannot replace the required live query. When you also ran the bar shape, `series` may carry its trailing per-bucket values, oldest first, at most {MAX_METRIC_SERIES_POINTS} points; the inbox row draws them as a small trend strip.+- **Snapshots are optional cached fallbacks.** Send `value` and `value_at` together only for a value you observed, and write `value_at` as an ISO-8601 timestamp with a timezone. Any offset works, because the server reads it as one instant and stores it in UTC, but a time ahead of the server clock drops the snapshot and keeps the metric. Zero is valid measured data. Null means no snapshot. Never invent a value from prose or estimate one from grouped signal count. A snapshot cannot replace the required live query. When you also ran the bar shape, `series` may carry its trailing per-bucket values, oldest first, at most {MAX_METRIC_SERIES_POINTS} points; the inbox row draws them as a small trend strip.- **Keep semantics separate from presentation.** `kind` says what is measured; `value_format` says how to print it. A non-currency `unit` is one lowercase word that completes the figure, because the report prints it next to the number. Use `users`, `sessions`, `events`, `runs`, or `calls`, and for a rate name what the share means: `failure` for an error rate, `conversion` for a conversion rate. `%` is redundant and is dropped. Use `percentage` for percentage points (`34` means 34%) and `percentage_scaled` for 0–1 ratios (`0.34` means 34%). A percentage query must set `aggregationAxisFormat` to exactly the same value as `value_format`; missing or numeric axis formatting is invalid. A duration uses `ms` or `s`; currency uses an uppercase ISO code such as `USD`.- **Do not author comparisons.** Leave `comparison` unset. The server does not yet keep an adjacent comparison window live.- **At most {MAX_REPORT_METRICS} metrics per report.** Prefer the handful that changes a decision. `metrics` replaces the previous set with the new title and summary, so repeat any still-valid metric on re-research. Snapshot-only or queryless rows are legacy or malformed, are always redacted, and must not be re-sent.diff --git a/products/signals/backend/report_metrics.py b/products/signals/backend/report_metrics.pyindex 5dbd7f2b179a..03ca329bb2c2 100644--- a/products/signals/backend/report_metrics.py+++ b/products/signals/backend/report_metrics.py@@ -17,6 +17,7 @@ import reimport astimport jsonimport math+import loggingfrom collections.abc import Sequencefrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal@@ -27,6 +28,8 @@ from posthog.hogql.errors import BaseHogQLErrorfrom products.signals.backend.report_charts import validate_report_query+logger = logging.getLogger(__name__)+_METRIC_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")_RELATIVE_DATE_FROM_RE = re.compile(r"^-([1-9]\d*)(h|d|w|m|y)$")_RELATIVE_DATE_FROM_ERROR = (@@ -480,18 +483,14 @@ class ReportMetric(BaseModel):@field_validator("value_at")@classmethod- def value_at_must_be_a_bounded_past_timestamp(cls, value: datetime | None) -> datetime | None:+ def value_at_must_be_an_instant_in_utc(cls, value: datetime | None) -> datetime | None:if value is None:return valueif value.tzinfo is None or value.utcoffset() is None:raise ValueError("must include a timezone")- # The snapshot time is authored, not stamped by the server, so an LLM can emit a wrong year- # or a clock-confused date. A future time makes every later refresh look older than the- # stored snapshot, so the stale value would stay until real time catches up. Reject a- # time past now plus a small clock-skew allowance.- if value > datetime.now(tz=UTC) + METRIC_VALUE_AT_MAX_CLOCK_SKEW:- raise ValueError("must not be in the future")- return value+ # An offset names one instant, so keep the snapshot in UTC: the author's local time+ # `2026-09-18T00:20:00+05:30` is the same moment as `2026-09-17T18:50:00Z`.+ return value.astimezone(UTC)@field_validator("unit")@classmethod@@ -517,10 +516,31 @@ class ReportMetric(BaseModel):def query_must_be_a_live_trends_node(cls, value: dict[str, Any]) -> dict[str, Any]:return validate_live_metric_query(value)+ def _drop_a_snapshot_measured_in_the_future(self) -> None:+ """Clear a snapshot whose measurement time is still ahead of the server clock.++ The time is authored, not stamped by the server, so an agent can emit a wrong year or a+ clock-confused date, and a future time would hold the stale value until real time catches+ up. The snapshot is an optional fallback that a read replaces, so drop it and keep the+ metric: the live query stays the source of truth and the report still publishes.+ """++ if self.value_at is None or self.value_at <= datetime.now(tz=UTC) + METRIC_VALUE_AT_MAX_CLOCK_SKEW:+ return+ logger.warning(+ "report metric %s dropped a snapshot measured at %s, ahead of the server clock",+ self.metric_id,+ self.value_at.isoformat(),+ )+ self.value = None+ self.value_at = None+ self.series = None+@model_validator(mode="after")def measurement_must_be_available_and_consistent(self) -> ReportMetric:if (self.value is None) != (self.value_at is None):raise ValueError("value and value_at must be provided together")+ self._drop_a_snapshot_measured_in_the_future()if self.series is not None and self.value_at is None:raise ValueError("series is part of the snapshot and needs value and value_at")if self.kind == "affected_users":diff --git a/products/signals/backend/test/test_report_metrics.py b/products/signals/backend/test/test_report_metrics.pyindex 0fa54e684dbe..f38c21943021 100644--- a/products/signals/backend/test/test_report_metrics.py+++ b/products/signals/backend/test/test_report_metrics.py@@ -1,4 +1,6 @@-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetime++import time_machinefrom django.test import SimpleTestCase@@ -443,14 +445,36 @@ class TestReportMetric(SimpleTestCase):with self.assertRaisesRegex(ValidationError, "must include a timezone"):ReportMetric.model_validate(content)- def test_rejects_a_future_snapshot_timestamp(self) -> None:- # An author-supplied future time would make every refresh look older than the snapshot and- # freeze the stale value, so a time past now plus the clock-skew allowance is rejected.- content = _affected_users_metric().model_dump(mode="json")- content["value_at"] = (datetime.now(UTC) + timedelta(days=1)).isoformat()+ @time_machine.travel("2026-09-17T18:50:00Z", tick=False)+ def test_keeps_a_local_snapshot_timestamp_that_names_the_current_instant(self) -> None:+ # An author writes the snapshot time in their own zone, where the date can already be+ # tomorrow or still yesterday. Each of these is the frozen instant, not a future one.+ for value_at in ("2026-09-18T00:20:00+05:30", "2026-09-17T11:50:00-07:00", "2026-09-17T18:50:00Z"):+ with self.subTest(value_at=value_at):+ content = _affected_users_metric().model_dump(mode="json")+ content["value_at"] = value_at- with self.assertRaisesRegex(ValidationError, "must not be in the future"):- ReportMetric.model_validate(content)+ metric = ReportMetric.model_validate(content)++ assert metric.value == 17+ assert metric.value_at == datetime(2026, 9, 17, 18, 50, tzinfo=UTC)++ @time_machine.travel("2026-09-17T18:50:00Z", tick=False)+ def test_drops_a_snapshot_still_measured_in_the_future(self) -> None:+ # A time past now plus the clock-skew allowance would make every refresh look older than+ # the snapshot and freeze the stale value. The metric and its live query still stand, so+ # the report publishes instead of failing on an optional fallback.+ for value_at in ("2026-09-18T06:20:00+05:30", "2027-09-17T18:50:00Z"):+ with self.subTest(value_at=value_at):+ content = _affected_users_metric().model_dump(mode="json")+ content["value_at"] = value_at+ content["series"] = [3, 0, 5]++ metric = ReportMetric.model_validate(content)++ assert metric.value is None+ assert metric.value_at is None+ assert metric.series is Nonedef test_requires_a_live_query_for_every_metric(self) -> None:with self.assertRaisesRegex(ValidationError, "Field required"):