: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(metrics): stop counter charts starting at zero (#87128)
Frank Hamand1e8be28c056c
diff --git a/products/metrics/backend/diagnostics.py b/products/metrics/backend/diagnostics.pyindex 5ac83f99763d..122eb6ec620a 100644--- a/products/metrics/backend/diagnostics.py+++ b/products/metrics/backend/diagnostics.py@@ -37,9 +37,10 @@ from products.metrics.backend.facade.contracts import ()from products.metrics.backend.fundamentals import Sample, TemporalReducer, apply_plan, plan_reduction, reduce_temporalfrom products.metrics.backend.metric_query_runner import (- _INTERVAL_LADDER,_QUERY_SETTINGS,MetricQueryRunner,+ _interval_step,+ counter_lookback,filters_expr,type_filter_expr,)@@ -56,14 +57,6 @@ DEFAULT_MAX_SAMPLES_PER_SERIES = 12_MAX_ROWS_READ = 50000-def _interval_step(interval: str) -> dt.timedelta:- """The bucket's width, from the same ladder the chart uses."""- for name, step, _ in _INTERVAL_LADDER:- if name == interval:- return step- raise ValueError(f"Unknown interval: {interval!r}")--def _as_utc(timestamp: dt.datetime) -> dt.datetime:"""ClickHouse hands timestamps back naive; the bucket edges are aware."""return timestamp.replace(tzinfo=dt.UTC) if timestamp.tzinfo is None else timestamp.astimezone(dt.UTC)@@ -114,7 +107,6 @@ def _actual_value(team: Team,metric_name: str,aggregation: str,- date_from: dt.datetime,bucket_start: dt.datetime,bucket_end: dt.datetime,interval: str,@@ -124,15 +116,15 @@ def _actual_value() -> float | None:"""What the product would plot for this point, through the real runner.- `date_from` reaches back one bucket for the counter functions so the- runner's window function sees the predecessor sample, exactly as it does- under the chart; only the requested bucket's row is returned.+ The runner reaches back past `date_from` on its own for the counter+ functions' predecessor sample, so this asks for exactly the one bucket the+ decomposition is explaining."""rows = MetricQueryRunner(team=team,metric_name=metric_name,aggregation=aggregation,- date_from=date_from,+ date_from=bucket_start,date_to=bucket_end,interval=interval,filters=filters,@@ -162,17 +154,18 @@ def decompose_bucket(bucket_start = _as_utc(bucket_start)step = _interval_step(interval)bucket_end = bucket_start + step- # The counter functions diff against the last sample before the bucket, the- # way the chart's window function does, so their raw read reaches back one- # bucket for that predecessor.+ # The counter functions diff against the newest sample before the bucket,+ # the way the chart's window function does, so their raw read reaches back+ # over exactly the runner's lookback. A shorter reach here would find a+ # different predecessor and report a disagreement the chart does not have.needs_boundary = aggregation in ("rate", "increase")- date_from = bucket_start - step if needs_boundary else bucket_start+ read_from = bucket_start - counter_lookback(interval) if needs_boundary else bucket_startresponse = execute_hogql_query(query_type="MetricBucketDecomposition",query=_raw_samples_query(metric_name=metric_name,- date_from=date_from,+ date_from=read_from,bucket_end=bucket_end,filters=filters,metric_type=metric_type,@@ -264,7 +257,6 @@ def decompose_bucket(team=team,metric_name=metric_name,aggregation=aggregation,- date_from=date_from,bucket_start=bucket_start,bucket_end=bucket_end,interval=interval,diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.pyindex 6d7561e4887d..db3c9941d0eb 100644--- a/products/metrics/backend/metric_query_runner.py+++ b/products/metrics/backend/metric_query_runner.py@@ -42,7 +42,10 @@ _ROW_LIMIT = 10000# Widest queryable range. Counter/histogram queries scan raw samples within# the range on the ClickHouse cluster shared with the live logs/traces-# products, so the span has to be bounded.+# products, so the span has to be bounded. Those two also scan+# `counter_lookback(interval)` before `date_from` for a predecessor sample;+# the bound stays on the requested range, since the extra reach costs at most+# one more daily partition and returns no extra rows.MAX_QUERY_SPAN = dt.timedelta(days=31)# These run on the shared logs cluster; cap how much one query may read.@@ -250,6 +253,37 @@ def _interval_expr(name: str) -> ast.Call:raise ValueError(f"Unknown interval: {name!r}")+def _interval_step(name: str) -> dt.timedelta:+ for entry_name, step, _ in _INTERVAL_LADDER:+ if entry_name == name:+ return step+ raise ValueError(f"Unknown interval: {name!r}")+++# Prometheus's default lookback delta. One interval step on its own is not+# enough when the scrape interval is coarser than the bucket — a 60s scrape on+# a `second` or `minute` chart — and `metrics1` is partitioned by day with+# `timestamp` last in the sort key, so reaching back five minutes inside a day+# reads the same partitions as reaching back one.+_MIN_COUNTER_LOOKBACK = dt.timedelta(minutes=5)+++def counter_lookback(interval: str) -> dt.timedelta:+ """How far before `date_from` the counter and histogram scans reach.++ Those aggregations diff each sample against the one before it, so the last+ sample *outside* the requested range is an input to the first bucket inside+ it. Without it the first bucket diffs against nothing and plots 0+ (histograms drop the point instead). The pre-range rows are cut again+ before bucketing, so the returned grid is exactly the requested range.++ `diagnostics.decompose_bucket` reads its raw samples over the same window+ through this helper: a shorter reach there would find a different+ predecessor and report a disagreement the chart does not have.+ """+ return max(_interval_step(interval), _MIN_COUNTER_LOOKBACK)++def _filter_condition(filter: MetricFilter) -> ast.Expr:"""One label predicate as a HogQL boolean expression.@@ -524,15 +558,20 @@ class MetricQueryRunner:- cumulative temporality: contribution = value - prev, clamped forcounter resets (value < prev means the counter restarted, so the- post-reset absolute value IS the increase); the first sample of a- series contributes 0 (its history is unknown).+ post-reset absolute value IS the increase); a sample with no+ predecessor within `counter_lookback` contributes 0 (its history is+ unknown).- delta temporality: each sample already is the increase, so itcontributes its own value.`increase` sums contributions per bucket; `rate` divides by thebucket length in seconds.++ The scan starts a lookback before `date_from` so the first sample in+ the range has a predecessor to diff against; the outer `WHERE` drops+ those pre-range rows again, leaving the requested bucket grid."""- step_seconds = next(step.total_seconds() for name, step, _ in _INTERVAL_LADDER if name == self.interval)+ step_seconds = _interval_step(self.interval).total_seconds()divisor = step_seconds if self.aggregation == "rate" else 1.0query = parse_select("""@@ -566,12 +605,13 @@ class MetricQueryRunner:) AS prev_valueFROM posthog.metricsWHERE metric_name = {metric_name}- AND timestamp >= {date_from}+ AND timestamp >= {scan_from}AND timestamp < {date_to}AND {filters}AND {type_filter}))+ WHERE sample_timestamp >= {date_from}GROUP BY timeORDER BY time ASCLIMIT {row_limit}@@ -581,6 +621,7 @@ class MetricQueryRunner:"divisor": ast.Constant(value=divisor),"series_key": ast.Tuple(exprs=_series_key_exprs()),"metric_name": ast.Constant(value=self.metric_name),+ "scan_from": ast.Constant(value=self.date_from - counter_lookback(self.interval)),"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"filters": filters_expr(self.filters),@@ -595,7 +636,8 @@ class MetricQueryRunner:def _build_histogram_query(self) -> ast.SelectQuery:"""Per-time-bucket summed bucket-count distributions for histogramrows, with the same per-series temporality/reset handling as- rate/increase applied element-wise to the counts array."""+ rate/increase applied element-wise to the counts array — including the+ lookback that gives the first in-range sample a predecessor."""query = parse_select("""SELECT@@ -633,13 +675,14 @@ class MetricQueryRunner:) AS prev_countsFROM posthog.metricsWHERE metric_name = {metric_name}- AND timestamp >= {date_from}+ AND timestamp >= {scan_from}AND timestamp < {date_to}AND notEmpty(histogram_counts)AND {filters}AND {type_filter}))+ WHERE sample_timestamp >= {date_from}GROUP BY timeORDER BY time ASCLIMIT {row_limit}@@ -648,6 +691,7 @@ class MetricQueryRunner:"interval": _interval_expr(self.interval),"series_key": ast.Tuple(exprs=_series_key_exprs()),"metric_name": ast.Constant(value=self.metric_name),+ "scan_from": ast.Constant(value=self.date_from - counter_lookback(self.interval)),"date_from": ast.Constant(value=self.date_from),"date_to": ast.Constant(value=self.date_to),"filters": filters_expr(self.filters),diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.pyindex b7f73eb97562..8ea4ed7c835f 100644--- a/products/metrics/backend/tests/test_diagnostics.py+++ b/products/metrics/backend/tests/test_diagnostics.py@@ -267,6 +267,35 @@ class TestCounterBoundary(ClickhouseTestMixin, APIBaseTest):assert decomposition.actual_value == 40.0assert decomposition.agrees is True+ def test_agrees_when_the_predecessor_sits_further_back_than_one_bucket(self) -> None:+ # A minute chart of a series scraped every few minutes: the reference+ # reduction and the runner have to reach back over the same window, or+ # one of them finds a predecessor the other doesn't and the tab reports+ # a disagreement the chart never had.+ seed_metric(+ team_id=self.team.pk,+ metric_name="packets_total",+ metric_type="sum",+ aggregation_temporality="cumulative",+ is_monotonic=True,+ points=[+ (BUCKET - dt.timedelta(minutes=3), 100.0),+ (BUCKET + dt.timedelta(seconds=30), 120.0),+ ],+ )++ decomposition = decompose_bucket(+ team=self.team,+ metric_name="packets_total",+ aggregation="increase",+ bucket_start=BUCKET,+ interval="minute",+ )++ assert decomposition.reference_value == 20.0+ assert decomposition.actual_value == 20.0+ assert decomposition.agrees is True+def test_rate_normalizes_the_boundary_increase_too(self) -> None:decomposition = decompose_bucket(team=self.team,diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex c42ba1e2470e..7a19940b41c8 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -796,6 +796,31 @@ class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):# bucket 1: first sample contributes 0, then 5+5+5; bucket 2: 5+5self.assertEqual(values, [15.0, 10.0])+ @parameterized.expand(+ [+ ("increase", [10.0, 20.0]),+ ("rate", [10.0 / 60.0, 20.0 / 60.0]),+ ]+ )+ def test_first_bucket_diffs_against_the_sample_before_the_range(self, aggregation: str, expected: list[float]):+ # Scraped about once per bucket, which is the normal case: without a+ # predecessor from before date_from the first point is a flat 0.+ self._seed_counter(+ [+ (self.anchor - dt.timedelta(seconds=90), 100.0),+ (self.anchor - dt.timedelta(seconds=30), 110.0),+ (self.anchor + dt.timedelta(seconds=30), 130.0),+ ]+ )+ rows = self._run(aggregation)+ for row, expected_value in zip(rows, expected):+ self.assertAlmostEqual(row["value"], expected_value)+ # The pre-range sample only feeds the window function; its own bucket+ # must not widen the grid the chart plots.+ self.assertEqual(len(rows), len(expected))+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)+ self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))+def test_rate_divides_by_bucket_seconds(self):self._seed_counter([@@ -1016,6 +1041,22 @@ class TestHistogramQuantileRunner(ClickhouseTestMixin, APIBaseTest):rows = self._run(0.95)self.assertEqual(rows, [])+ def test_first_bucket_diffs_against_the_histogram_before_the_range(self):+ # Same missing-predecessor defect as the counter functions, but here it+ # drops the point entirely rather than plotting a zero.+ self._seed_histogram(+ [+ (self.anchor - dt.timedelta(seconds=90), [100, 100, 100, 0]),+ (self.anchor - dt.timedelta(seconds=30), [110, 110, 110, 0]),+ ],+ temporality="cumulative",+ )+ rows = self._run(0.5)+ self.assertEqual(len(rows), 1)+ self.assertAlmostEqual(rows[0]["value"], 0.3)+ earliest = dt.datetime.fromisoformat(rows[0]["time"]).astimezone(dt.UTC)+ self.assertEqual(earliest, self.anchor - dt.timedelta(minutes=1))+def test_mismatched_bounds_raise(self):self._seed_histogram([(self.anchor + dt.timedelta(seconds=0), [1, 1, 1, 0])], temporality="delta")self._seed_histogram(