Skip to content

: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.

feat(logs): measure the volume rollup from the tick (#83255)

Jon McCallum532798aeee7b
diff --git a/products/logs/backend/temporal/volume_tick/activities.py b/products/logs/backend/temporal/volume_tick/activities.py
index d278453b38c0..42e508b5b1b4 100644
--- a/products/logs/backend/temporal/volume_tick/activities.py
+++ b/products/logs/backend/temporal/volume_tick/activities.py
@@ -11,15 +11,19 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.dataclasses import frozen
from posthog.sync import database_sync_to_async_pool
+from products.logs.backend.temporal.volume_tick.aggregation import RollupPreview, preview_rollup
from products.logs.backend.temporal.volume_tick.constants import (
BUCKET_MINUTES,
BUCKET_SECONDS,
FINALIZATION_ALLOWANCE,
+ TEAM_ALLOWLIST,
TEAMS_WITH_LOGS_WINDOW,
)
from products.logs.backend.temporal.volume_tick.metrics import (
increment_tick_runs,
record_clickhouse_duration,
+ record_rollup_duration,
+ record_rollup_preview,
record_teams_with_logs,
)
@@ -51,6 +55,12 @@ class VolumeTickOutput:
teams_due_in_shard: int
due_bucket_start: str
due_bucket_end: str
+ # None when the allowlist is empty and the rollup query therefore did not run.
+ rollup_rows: int | None = None
+ source_rows: int | None = None
+ distinct_services: int | None = None
+ rows_without_namespace: int | None = None
+ rows_without_environment: int | None = None
@frozen
@@ -98,13 +108,31 @@ def count_teams_with_logs(begin: datetime, end: datetime, shard: int) -> TeamsWi
_count_teams_with_logs_async = database_sync_to_async_pool(count_teams_with_logs)
+_preview_rollup_async = database_sync_to_async_pool(preview_rollup)
+
+
+@frozen
+class TimedRollupPreview:
+ preview: RollupPreview
+ duration_ms: int
+
+
+async def _preview_due_bucket(due: DueBucket) -> TimedRollupPreview | None:
+ """Measure the due bucket's rollup for the allowlisted teams, or nothing if
+ the allowlist is empty. Once the commit protocol lands this becomes the write."""
+ if not TEAM_ALLOWLIST:
+ return None
+ started = time.monotonic()
+ preview = await _preview_rollup_async(team_ids=TEAM_ALLOWLIST, start=due.start, end=due.end)
+ return TimedRollupPreview(preview=preview, duration_ms=int((time.monotonic() - started) * 1000))
@temporalio.activity.defn
async def volume_tick_heartbeat_activity(input: VolumeTickInput) -> VolumeTickOutput:
- # Skeleton for the log volume rollup tick: proves the schedule and the
- # worker's path to the logs ClickHouse cluster, and observes (never writes)
- # what the real tick would do. The rollup writer replaces this body.
+ # The log volume rollup tick, observing rather than writing: it runs the same
+ # scan and grouping the rollup writer will run, and publishes what that write
+ # would contain. The write itself needs the commit protocol to make its rows
+ # visible, so it lands with that.
ticked_at = datetime.now(UTC)
due = due_bucket_bounds(ticked_at)
# One team cohort per minute of the bucket: the every-minute schedule smears
@@ -114,6 +142,7 @@ async def volume_tick_heartbeat_activity(input: VolumeTickInput) -> VolumeTickOu
started = time.monotonic()
try:
counts = await _count_teams_with_logs_async(ticked_at - TEAMS_WITH_LOGS_WINDOW, ticked_at, minute_shard)
+ timed = await _preview_due_bucket(due)
except Exception:
increment_tick_runs("error")
raise
@@ -121,7 +150,11 @@ async def volume_tick_heartbeat_activity(input: VolumeTickInput) -> VolumeTickOu
record_clickhouse_duration(duration_ms)
record_teams_with_logs(counts.total)
+ if timed is not None:
+ record_rollup_duration(timed.duration_ms)
+ record_rollup_preview(timed.preview)
increment_tick_runs("ok")
+ preview = timed.preview if timed else None
output = VolumeTickOutput(
ticked_at=ticked_at.isoformat(),
teams_with_logs=counts.total,
@@ -129,6 +162,11 @@ async def volume_tick_heartbeat_activity(input: VolumeTickInput) -> VolumeTickOu
teams_due_in_shard=counts.due_in_shard,
due_bucket_start=due.start.isoformat(),
due_bucket_end=due.end.isoformat(),
+ rollup_rows=preview.rollup_rows if preview else None,
+ source_rows=preview.source_rows if preview else None,
+ distinct_services=preview.distinct_services if preview else None,
+ rows_without_namespace=preview.rows_without_namespace if preview else None,
+ rows_without_environment=preview.rows_without_environment if preview else None,
)
logger.info("logs_volume_tick_heartbeat", clickhouse_duration_ms=duration_ms, **dataclasses.asdict(output))
return output
diff --git a/products/logs/backend/temporal/volume_tick/aggregation.py b/products/logs/backend/temporal/volume_tick/aggregation.py
new file mode 100644
index 000000000000..445e0436ba70
--- /dev/null
+++ b/products/logs/backend/temporal/volume_tick/aggregation.py
@@ -0,0 +1,178 @@
+import os
+from collections.abc import Sequence
+from datetime import datetime
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
+
+from products.logs.backend.temporal.volume_tick.constants import BUCKET_SECONDS
+
+TABLE_NAME = "logs_volume_buckets"
+
+# Reads the physical distributed table, not `logs` — `logs` is the HogQL alias and
+# does not exist for raw `sync_execute` SQL.
+#
+# The write, once it lands, must target the *local* replicated table instead: an
+# INSERT through Distributed is async by default, so it returns before the rows
+# are readable and a commit issued straight after would publish a bucket nobody
+# can see. See products/analytics_platform/backend/lazy_computation/CONSISTENCY.md
+# — and note that dev and CI force synchronous inserts, so that failure mode
+# cannot reproduce locally.
+_SOURCE_TABLE = "logs_distributed"
+
+# `k8s.*.name` keys were never renamed, so namespace needs no fallback.
+_NAMESPACE_KEY = "k8s.namespace.name"
+
+# The one resource attribute OTel has renamed: `deployment.environment` became
+# `deployment.environment.name` in semantic conventions 1.27. `env` is not a
+# convention at all — it is where a Datadog `env:` tag lands, because that ingest
+# path stores tags verbatim. First non-empty wins.
+#
+# This chain is a guess about production data. `rows_without_environment` below
+# is what tests it: local fixtures cannot, because the fixtures encode the guess.
+_ENVIRONMENT_KEYS = ("deployment.environment.name", "deployment.environment", "env")
+
+# A truncated count is worse than no count: it becomes a permanent baseline the
+# detector trusts, and nothing downstream can tell it apart from a real drop. So
+# reads throw at the budget rather than returning what they managed to scan.
+# The cap is generous against a 5-minute window and only trips on runaway volume.
+_ROLLUP_QUERY_SETTINGS = {
+ "max_execution_time": int(os.environ.get("LOGS_VOLUME_TICK_AGGREGATION_MAX_EXECUTION_SECONDS", "55")),
+ "max_bytes_to_read": int(os.environ.get("LOGS_VOLUME_TICK_AGGREGATION_MAX_BYTES_TO_READ", str(20 * 1024**3))),
+ "read_overflow_mode": "throw",
+}
+
+
+@frozen
+class RollupPreview:
+ """What one grid bucket's rollup would contain, measured without writing it."""
+
+ rollup_rows: int
+ source_rows: int
+ distinct_services: int
+ rows_without_namespace: int
+ rows_without_environment: int
+
+
+def _first_non_empty_map_key(column: str, param_prefix: str, count: int) -> str:
+ """Nested `if()` over map keys, first non-empty wins, last is the fallback.
+
+ ClickHouse Map access yields `''` for a missing key rather than NULL, so
+ `coalesce` cannot express this.
+ """
+ expression = f"{column}[%({param_prefix}{count - 1})s]"
+ for index in reversed(range(count - 1)):
+ candidate = f"{column}[%({param_prefix}{index})s]"
+ expression = f"if({candidate} != '', {candidate}, {expression})"
+ return expression
+
+
+def _rollup_sql() -> str:
+ """The rollup itself: raw log rows grouped down to one row per series per bucket.
+
+ Kept standalone so the query validated against production is the same text the
+ writer will run. Turning this into the writer is an `INSERT INTO {TABLE_NAME}
+ (...)` prefix plus the attempt's `generation` in the select list — the read,
+ the grouping and the cost do not change.
+ """
+ environment = _first_non_empty_map_key("resource_attributes", "env_key_", len(_ENVIRONMENT_KEYS))
+ # The grid pins UTC explicitly. Without it the bucket edges follow the session
+ # timezone, so the same log would land in different buckets depending on who
+ # ran the query — and bucket identity has to be stable across ticks, backfills
+ # and recomputes.
+ #
+ # Dimensions are stored verbatim, with '' for absent. No 'unknown' sentinel:
+ # it would change which rows group together, and the correctness test
+ # compares these counts against a direct count of the same raw logs.
+ #
+ # severity_text is the exception. It is lowercased because an issue's identity
+ # will include it, so a service emitting ERROR one week and error the next
+ # would file two issues for one problem.
+ return f"""
+ SELECT
+ team_id,
+ toStartOfInterval(timestamp, INTERVAL %(bucket_seconds)s SECOND, 'UTC') AS time_bucket,
+ service_name,
+ resource_attributes[%(namespace_key)s] AS namespace,
+ {environment} AS environment,
+ lower(severity_text) AS severity_text,
+ count() AS log_count
+ FROM {_SOURCE_TABLE}
+ WHERE team_id IN %(team_ids)s
+ AND timestamp >= %(start)s
+ AND timestamp < %(end)s
+ GROUP BY team_id, time_bucket, service_name, namespace, environment, severity_text
+ """
+
+
+def _rollup_parameters(team_ids: Sequence[int], start: datetime, end: datetime) -> dict[str, object]:
+ parameters: dict[str, object] = {
+ "team_ids": list(team_ids),
+ "start": start,
+ "end": end,
+ "bucket_seconds": BUCKET_SECONDS,
+ "namespace_key": _NAMESPACE_KEY,
+ }
+ parameters.update({f"env_key_{index}": key for index, key in enumerate(_ENVIRONMENT_KEYS)})
+ return parameters
+
+
+def _preview_sql() -> str:
+ """Counts the rollup instead of writing it.
+
+ The inner query is unchanged, so this reads exactly the bytes the writer will
+ read and produces exactly the rows it will produce. Only the destination
+ differs: five numbers to a log line and a dashboard, rather than rows to a table.
+ """
+ return f"""
+ SELECT
+ count() AS rollup_rows,
+ sum(log_count) AS source_rows,
+ uniqExact(service_name) AS distinct_services,
+ countIf(namespace = '') AS rows_without_namespace,
+ countIf(environment = '') AS rows_without_environment
+ FROM ({_rollup_sql()})
+ """
+
+
+def preview_rollup(
+ *,
+ team_ids: Sequence[int],
+ start: datetime,
+ end: datetime,
+) -> RollupPreview:
+ """Measure the rollup for every grid bucket in [start, end) without writing it.
+
+ Reads only. The two `rows_without_*` counts are the point: they say whether the
+ dimensions this rollup is keyed on actually resolve against production data,
+ which is the one thing that has to hold before 42 days of rows are keyed on them.
+
+ Raises `CHQueryErrorTooManyBytes` if the scan exceeds its byte budget.
+ """
+ if not team_ids:
+ raise ValueError("preview_rollup requires at least one team id")
+ if start.tzinfo is None or end.tzinfo is None:
+ raise ValueError("start and end must be timezone-aware")
+ if start >= end:
+ raise ValueError(f"start {start.isoformat()} must precede end {end.isoformat()}")
+ for name, boundary in (("start", start), ("end", end)):
+ if int(boundary.timestamp()) % BUCKET_SECONDS:
+ raise ValueError(f"{name} {boundary.isoformat()} is not aligned to the {BUCKET_SECONDS}s grid")
+
+ with tags_context(product=Product.LOGS, feature=Feature.PREAGGREGATION):
+ rows = sync_execute(
+ _preview_sql(),
+ _rollup_parameters(team_ids, start, end),
+ workload=Workload.LOGS,
+ settings=_ROLLUP_QUERY_SETTINGS,
+ )
+ row = rows[0]
+ return RollupPreview(
+ rollup_rows=int(row[0]),
+ source_rows=int(row[1]),
+ distinct_services=int(row[2]),
+ rows_without_namespace=int(row[3]),
+ rows_without_environment=int(row[4]),
+ )
diff --git a/products/logs/backend/temporal/volume_tick/constants.py b/products/logs/backend/temporal/volume_tick/constants.py
index 954f8cad06e3..5217abdeaaf1 100644
--- a/products/logs/backend/temporal/volume_tick/constants.py
+++ b/products/logs/backend/temporal/volume_tick/constants.py
@@ -27,6 +27,14 @@ BUCKET_SECONDS = BUCKET_MINUTES * 60
# 99.96% of rows land within 10 minutes; the residual tail is reconciliation's job.
# A dial, not grid identity: env-tunable (read at import, so a worker restart applies it).
FINALIZATION_ALLOWANCE = timedelta(minutes=int(os.environ.get("LOGS_VOLUME_TICK_FINALIZATION_ALLOWANCE_MINUTES", "10")))
+# Teams the rollup runs over, as comma-separated ids. Empty means no team: an
+# unset variable does nothing rather than sweeping the whole fleet, so a wrong
+# query costs one team's scan — and later one team's rows — not 3,000.
+# Discovery is unaffected: it stays fleet-wide, because its scan is what
+# measures per-tick compute.
+TEAM_ALLOWLIST: tuple[int, ...] = tuple(
+ int(team_id) for team_id in os.environ.get("LOGS_VOLUME_TICK_TEAM_ALLOWLIST", "").split(",") if team_id.strip()
+)
# Starts as a mirror of the alerting policy but is tuned independently.
ACTIVITY_RETRY_POLICY = RetryPolicy(
maximum_attempts=3,
diff --git a/products/logs/backend/temporal/volume_tick/metrics.py b/products/logs/backend/temporal/volume_tick/metrics.py
index 02cce2bfd0c9..9ea135680a11 100644
--- a/products/logs/backend/temporal/volume_tick/metrics.py
+++ b/products/logs/backend/temporal/volume_tick/metrics.py
@@ -5,9 +5,14 @@ import datetime as dt
from posthog.temporal.common.metrics import get_metric_meter
+from products.logs.backend.temporal.volume_tick.aggregation import RollupPreview
+
# Consumed by `posthog/temporal/common/worker.py` to override Prometheus default
# buckets per-metric. Keep in sync with the histograms emitted below.
-LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS = ("logs_volume_tick_clickhouse_duration_ms",)
+LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS = (
+ "logs_volume_tick_clickhouse_duration_ms",
+ "logs_volume_tick_rollup_duration_ms",
+)
# Dense between 750ms and 3s because the discovery query lives there. Coarser
# steps put every sample in one bucket, so the high quantiles interpolate to a
@@ -55,3 +60,43 @@ def record_clickhouse_duration(duration_ms: int) -> None:
unit="ms",
)
hist.record(dt.timedelta(milliseconds=duration_ms))
+
+
+def record_rollup_duration(duration_ms: int) -> None:
+ meter = get_metric_meter()
+ hist = meter.create_histogram_timedelta(
+ name="logs_volume_tick_rollup_duration_ms",
+ description="Duration of the tick's ClickHouse rollup query",
+ unit="ms",
+ )
+ hist.record(dt.timedelta(milliseconds=duration_ms))
+
+
+def record_rollup_preview(preview: RollupPreview) -> None:
+ """Publish what the rollup would write for one due bucket.
+
+ Gauges, not counters: each is a property of the bucket the tick just measured,
+ not a running total. `rollup_rows` against `source_rows` is the compression the
+ rollup buys; the `missing_dimension` pair is whether its dimensions resolve at all.
+ """
+ meter = get_metric_meter()
+ meter.create_gauge(
+ "logs_volume_tick_rollup_rows",
+ "Rows the rollup would write for the due bucket",
+ ).set(preview.rollup_rows)
+ meter.create_gauge(
+ "logs_volume_tick_source_rows",
+ "Raw log records the due bucket's rollup rows summarize",
+ ).set(preview.source_rows)
+ meter.create_gauge(
+ "logs_volume_tick_distinct_services",
+ "Distinct services in the due bucket",
+ ).set(preview.distinct_services)
+ for dimension, count in (
+ ("namespace", preview.rows_without_namespace),
+ ("environment", preview.rows_without_environment),
+ ):
+ get_metric_meter({"dimension": dimension}).create_gauge(
+ "logs_volume_tick_rows_missing_dimension",
+ "Rollup rows whose dimension resolved to the empty string",
+ ).set(count)
diff --git a/products/logs/backend/test/test_volume_bucket_aggregation.py b/products/logs/backend/test/test_volume_bucket_aggregation.py
new file mode 100644
index 000000000000..f9916e85ba47
--- /dev/null
+++ b/products/logs/backend/test/test_volume_bucket_aggregation.py
@@ -0,0 +1,199 @@
+import json
+import uuid
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client import sync_execute
+
+from products.logs.backend.temporal.volume_tick.aggregation import (
+ RollupPreview,
+ _rollup_parameters,
+ _rollup_sql,
+ preview_rollup,
+)
+from products.logs.backend.temporal.volume_tick.constants import BUCKET_SECONDS
+
+_START = datetime(2026, 6, 23, 12, 0, tzinfo=UTC)
+_END = _START + timedelta(seconds=BUCKET_SECONDS)
+
+
+class TestVolumeBucketAggregation(ClickhouseTestMixin, BaseTest):
+ def _insert_logs(self, rows: list[dict]) -> None:
+ payload = "".join(json.dumps(row) + "\n" for row in rows)
+ sync_execute(f"INSERT INTO logs FORMAT JSONEachRow\n{payload}")
+
+ def _log(
+ self,
+ at: datetime,
+ *,
+ service: str = "checkout",
+ severity: str = "info",
+ resource_attributes: dict[str, str] | None = None,
+ ) -> dict:
+ return {
+ "uuid": str(uuid.uuid4()),
+ "team_id": self.team.id,
+ "timestamp": at.strftime("%Y-%m-%d %H:%M:%S.%f"),
+ "body": "",
+ "severity_text": severity,
+ "severity_number": 9,
+ "service_name": service,
+ "resource_attributes": resource_attributes or {},
+ "attributes_map_str": {},
+ }
+
+ def _rollup(self, *, start: datetime = _START, end: datetime = _END) -> list[tuple]:
+ """The rows the rollup would write, ordered. Runs the writer's own query,
+ so these assertions hold unchanged once it writes rather than counts."""
+ rows = sync_execute(_rollup_sql(), _rollup_parameters([self.team.id], start, end))
+ return sorted(rows, key=lambda row: (row[1], row[2], row[3], row[4], row[5]))
+
+ def _preview(self, *, start: datetime = _START, end: datetime = _END) -> RollupPreview:
+ return preview_rollup(team_ids=[self.team.id], start=start, end=end)
+
+ def test_counts_match_a_direct_raw_query(self) -> None:
+ self._insert_logs(
+ [
+ self._log(_START + timedelta(seconds=offset), service=service, severity=severity)
+ for offset, service, severity in [
+ (0, "checkout", "info"),
+ (1, "checkout", "info"),
+ (2, "checkout", "error"),
+ (3, "search", "info"),
+ ]
+ ]
+ )
+
+ rolled_up = [(row[2], row[5], row[6]) for row in self._rollup()]
+ direct = sync_execute(
+ """
+ SELECT service_name, lower(severity_text), count()
+ FROM logs_distributed
+ WHERE team_id = %(team_id)s AND timestamp >= %(start)s AND timestamp < %(end)s
+ GROUP BY service_name, lower(severity_text)
+ ORDER BY service_name, lower(severity_text)
+ """,
+ {"team_id": self.team.id, "start": _START, "end": _END},
+ )
+ # Both sides empty would compare equal and prove nothing.
+ self.assertEqual(rolled_up, [("checkout", "error", 1), ("checkout", "info", 2), ("search", "info", 1)])
+ self.assertEqual(rolled_up, [(row[0], row[1], row[2]) for row in direct])
+
+ def test_preview_summarizes_the_rows_the_rollup_would_write(self) -> None:
+ self._insert_logs(
+ [
+ self._log(_START, service="checkout", severity="info"),
+ self._log(_START, service="checkout", severity="info"),
+ self._log(_START, service="checkout", severity="error"),
+ self._log(_START, service="search", severity="info"),
+ ]
+ )
+
+ preview = self._preview()
+
+ self.assertEqual(
+ preview,
+ RollupPreview(
+ rollup_rows=3,
+ source_rows=4,
+ distinct_services=2,
+ rows_without_namespace=3,
+ rows_without_environment=3,
+ ),
+ )
+
+ def test_preview_counts_resolved_dimensions_as_present(self) -> None:
+ self._insert_logs(
+ [
+ self._log(_START, resource_attributes={"k8s.namespace.name": "web", "env": "prod"}),
+ self._log(_START, service="search", resource_attributes={"k8s.namespace.name": "web"}),
+ ]
+ )
+
+ preview = self._preview()
+
+ self.assertEqual(preview.rows_without_namespace, 0)
+ self.assertEqual(preview.rows_without_environment, 1)
+
+ def test_preview_of_an_empty_window_is_all_zeroes(self) -> None:
+ preview = self._preview()
+
+ self.assertEqual(
+ preview,
+ RollupPreview(
+ rollup_rows=0,
+ source_rows=0,
+ distinct_services=0,
+ rows_without_namespace=0,
+ rows_without_environment=0,
+ ),
+ )
+
+ def test_logs_land_in_their_own_grid_bucket(self) -> None:
+ second_bucket = _START + timedelta(seconds=BUCKET_SECONDS)
+ self._insert_logs(
+ [
+ self._log(second_bucket - timedelta(seconds=1)),
+ self._log(second_bucket),
+ ]
+ )
+ window = {"start": _START, "end": second_bucket + timedelta(seconds=BUCKET_SECONDS)}
+
+ rows = self._rollup(**window)
+
+ # Aware, and UTC: the grid pins its timezone rather than inheriting the session's.
+ self.assertEqual([(row[1], row[6]) for row in rows], [(_START, 1), (second_bucket, 1)])
+ self.assertEqual([row[1].utcoffset() for row in rows], [timedelta(0)] * 2)
+ self.assertEqual(self._preview(**window).rollup_rows, 2)
+
+ @parameterized.expand(
+ [
+ ("current_semconv", {"deployment.environment.name": "prod"}, "prod"),
+ ("previous_semconv", {"deployment.environment": "prod"}, "prod"),
+ ("datadog_tag", {"env": "prod"}, "prod"),
+ ("current_wins_over_older", {"deployment.environment.name": "prod", "env": "staging"}, "prod"),
+ ("absent", {}, ""),
+ ]
+ )
+ def test_environment_falls_back_through_the_key_chain(
+ self, _name: str, resource_attributes: dict[str, str], expected: str
+ ) -> None:
+ self._insert_logs([self._log(_START, resource_attributes=resource_attributes)])
+
+ self.assertEqual([row[4] for row in self._rollup()], [expected])
+
+ @parameterized.expand([("present", {"k8s.namespace.name": "web"}, "web"), ("absent", {}, "")])
+ def test_namespace_is_verbatim_with_no_sentinel(
+ self, _name: str, resource_attributes: dict[str, str], expected: str
+ ) -> None:
+ self._insert_logs([self._log(_START, resource_attributes=resource_attributes)])
+
+ self.assertEqual([row[3] for row in self._rollup()], [expected])
+
+ def test_severity_casing_merges_into_one_series(self) -> None:
+ self._insert_logs([self._log(_START, severity="ERROR"), self._log(_START, severity="error")])
+
+ self.assertEqual([(row[5], row[6]) for row in self._rollup()], [("error", 2)])
+
+ @parameterized.expand(
+ [
+ ("no_teams", [], _START, _END),
+ ("naive_start", [1], _START.replace(tzinfo=None), _END),
+ ("naive_end", [1], _START, _END.replace(tzinfo=None)),
+ ("end_before_start", [1], _END, _START),
+ ("empty_window", [1], _START, _START),
+ ("unaligned_start", [1], _START + timedelta(seconds=1), _END),
+ ("unaligned_end", [1], _START, _END + timedelta(seconds=1)),
+ ]
+ )
+ def test_rejects_invalid_input(self, _name: str, team_ids: list[int], start: datetime, end: datetime) -> None:
+ with self.assertRaises(ValueError):
+ preview_rollup(team_ids=team_ids, start=start, end=end)
+
+ def test_other_teams_are_not_rolled_up(self) -> None:
+ self._insert_logs([self._log(_START), {**self._log(_START), "team_id": self.team.id + 10_000}])
+
+ self.assertEqual(self._preview().rollup_rows, 1)
diff --git a/products/logs/backend/test/test_volume_tick_workflow.py b/products/logs/backend/test/test_volume_tick_workflow.py
index 772055a8eaa2..6dd47fde4c9a 100644
--- a/products/logs/backend/test/test_volume_tick_workflow.py
+++ b/products/logs/backend/test/test_volume_tick_workflow.py
@@ -6,12 +6,13 @@ from datetime import UTC, datetime, timedelta
import pytest
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from django.test import SimpleTestCase
from parameterized import parameterized
from temporalio import activity
-from temporalio.testing import WorkflowEnvironment
+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.clickhouse.client import sync_execute
@@ -21,6 +22,7 @@ from products.logs.backend.temporal.volume_tick.activities import (
VolumeTickOutput,
count_teams_with_logs,
due_bucket_bounds,
+ volume_tick_heartbeat_activity,
)
from products.logs.backend.temporal.volume_tick.constants import BUCKET_MINUTES, WORKFLOW_NAME
from products.logs.backend.temporal.volume_tick.workflow import LogsVolumeTickWorkflow
@@ -139,3 +141,24 @@ class TestCountTeamsWithLogs(ClickhouseTestMixin, BaseTest):
assert after.total == before.total + 2
# Only team_a's residue matches shard 1; team_b is in the window but in shard 2.
assert after.due_in_shard == before.due_in_shard + 1
+
+
+ "allowlist,measures_the_bucket",
+ [((), False), ((1,), True)],
+ ids=["empty_allowlist_skips", "allowlisted_team_is_measured"],
+)
+async def test_the_tick_measures_the_due_bucket_only_for_allowlisted_teams(
+ allowlist: tuple[int, ...], measures_the_bucket: bool
+) -> None:
+ # The allowlist is the whole safety story for this query: unset means the tick
+ # touches no team's data at all, rather than sweeping the fleet.
+ #
+ # ActivityEnvironment, not a direct call: the tick's metrics need an activity
+ # context to resolve a meter.
+ with patch("products.logs.backend.temporal.volume_tick.activities.TEAM_ALLOWLIST", allowlist):
+ output = await ActivityEnvironment().run(volume_tick_heartbeat_activity, VolumeTickInput())
+
+ assert (output.rollup_rows is not None) is measures_the_bucket
+ assert (output.rows_without_environment is not None) is measures_the_bucket