: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(logs): schedule a heartbeat-only volume tick workflow (#81868)
Jon McCallumfc3b7212726f
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 80640301367b..54c9063ecb50 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -812,6 +812,15 @@ jobs:- 'posthog/clickhouse/migrations/**'- pyproject.toml- bin/temporal-django-worker+ logsVolumeTick:+ - 'products/logs/backend/**'+ - 'products/apm/backend/logic/grid.py'+ - 'products/apm/backend/facade/constants.py'+ - 'posthog/temporal/common/**'+ - 'posthog/management/commands/start_temporal_worker.py'+ - 'posthog/clickhouse/migrations/**'+ - pyproject.toml+ - bin/temporal-django-workerdataModeling:- 'posthog/hogql/**'- 'products/managed_warehouse/backend/**'@@ -966,6 +975,27 @@ jobs:"timestamp": "${{ github.event.head_commit.timestamp }}"}+ - name: Trigger Logs Volume Tick Temporal Worker Cloud deployment+ if: steps.check_temporal_worker_changes.outputs.logsVolumeTick == 'true'+ uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1+ with:+ token: ${{ steps.deployer.outputs.token }}+ repository: PostHog/charts+ event-type: commit_state_update+ client-payload: |+ {+ "values": {+ "image": {+ "sha": "${{ github.sha }}@${{ steps.image.outputs.digest }}"+ }+ },+ "release": "temporal-worker-logs-volume-tick",+ "commit": ${{ toJson(github.event.head_commit) }},+ "repository": ${{ toJson(github.repository) }},+ "labels": ${{ steps.labels.outputs.labels }},+ "timestamp": "${{ github.event.head_commit.timestamp }}"+ }+- name: Trigger Stamphog Temporal Worker Cloud deploymentif: steps.check_temporal_worker_changes.outputs.stamphog == 'true'uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex c235d4211018..7dc3506807c2 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -208,6 +208,8 @@ from products.growth.backend.temporal import ()from products.logs.backend.facade.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,+ VOLUME_TICK_ACTIVITIES as LOGS_VOLUME_TICK_ACTIVITIES,+ VOLUME_TICK_WORKFLOWS as LOGS_VOLUME_TICK_WORKFLOWS,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,)from products.logs.backend.temporal.retention_entitlements import (@@ -499,6 +501,13 @@ _task_queue_specs = [LOGS_ALERTING_WORKFLOWS,LOGS_ALERTING_ACTIVITIES,),+ # Dedicated queue, never merged with alerting: the tick becomes the scan-heavy+ # rollup writer and must not share pods with the latency-sensitive alert checks.+ (+ settings.LOGS_VOLUME_TICK_TASK_QUEUE,+ LOGS_VOLUME_TICK_WORKFLOWS,+ LOGS_VOLUME_TICK_ACTIVITIES,+ ),(settings.STAMPHOG_TASK_QUEUE,STAMPHOG_WORKFLOWS,diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 92eebf141ed0..935aabe5194c 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -209,6 +209,11 @@ ERROR_TRACKING_TASK_QUEUE = _set_temporal_task_queue("error-tracking-task-queue"ERROR_TRACKING_LIFECYCLE_TASK_QUEUE = _set_temporal_task_queue("error-tracking-lifecycle-task-queue")EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")+# Dedicated queue: the tick becomes the scan-heavy rollup writer, and it must not+# share pods with the latency-sensitive alerting workers.+LOGS_VOLUME_TICK_TASK_QUEUE = _set_temporal_task_queue(+ os.getenv("LOGS_VOLUME_TICK_TASK_QUEUE", "logs-volume-tick-task-queue")+)RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process# Error trackingdiff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.pyindex e266e74753e6..36ddfe5cb03e 100644--- a/posthog/temporal/common/worker.py+++ b/posthog/temporal/common/worker.py@@ -72,6 +72,8 @@ from products.logs.backend.facade.temporal import (LOGS_ALERTING_COUNT_HISTOGRAM_METRICS,LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS,LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS,+ LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_BUCKETS,+ LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS,LogsAlertingMetricsInterceptor,)from products.tasks.backend.facade.temporal import (@@ -312,6 +314,11 @@ 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(+ LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS, itertools.repeat(LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_BUCKETS)+ )+ )| dict(zip(USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS, itertools.repeat(USAGE_REPORTS_LATENCY_HISTOGRAM_BUCKETS)))| dict(zip(diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 274e22c03250..cffd0e7d3dab 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -96,6 +96,7 @@ from products.error_tracking.backend.facade.temporal import ()from products.experiments.backend.temporal.schedule import create_experiment_precompute_canary_schedulefrom products.exports.backend.temporal.subscriptions.types import ScheduleAllSubscriptionsWorkflowInputs+from products.logs.backend.facade.temporal import create_logs_volume_tick_schedulefrom products.managed_warehouse.backend.facade.temporal import DucklakeCompactionInputfrom products.replay_vision.backend.temporal.estimates import create_replay_vision_estimates_schedulefrom products.replay_vision.backend.temporal.gemini_cleanup_sweep import (@@ -868,6 +869,7 @@ schedules = [create_wa_weekly_digest_schedule,create_wa_digest_notification_schedule,create_logs_alert_check_schedule,+ create_logs_volume_tick_schedule,create_schedule_due_alert_checks_schedule,create_run_investigation_safety_net_schedule,create_cleanup_alert_checks_schedule,diff --git a/products/apm/backend/facade/constants.py b/products/apm/backend/facade/constants.pynew file mode 100644index 000000000000..7aa1af4e1ace--- /dev/null+++ b/products/apm/backend/facade/constants.py@@ -0,0 +1,16 @@+"""Exported grid constants for apm.++A lightweight import path for consumers that need only the detection grid:+``facade/api.py`` also re-exports these, but importing it pulls the full+detector (numpy, scipy) along, which schedulers and workers must not pay+for one integer.+"""++from products.apm.backend.logic.grid import BUCKET_MINUTES, BUCKETS_PER_DAY, BUCKETS_PER_HOUR, BUCKETS_PER_WEEK++__all__ = [+ "BUCKET_MINUTES",+ "BUCKETS_PER_DAY",+ "BUCKETS_PER_HOUR",+ "BUCKETS_PER_WEEK",+]diff --git a/products/apm/backend/logic/anomaly_detection/constants.py b/products/apm/backend/logic/anomaly_detection/constants.pyindex 622da446a435..bd052a23e095 100644--- a/products/apm/backend/logic/anomaly_detection/constants.py+++ b/products/apm/backend/logic/anomaly_detection/constants.py@@ -1,9 +1,8 @@-"""Fixed grid constants. The 5-minute UTC bucket grid is architectural-(bucket identities must stay stable across ticks, backfills, and recomputes),-so unlike the dials in config.py these are not env-tunable.-"""+from products.apm.backend.logic.grid import BUCKET_MINUTES, BUCKETS_PER_DAY, BUCKETS_PER_HOUR, BUCKETS_PER_WEEK-BUCKET_MINUTES = 5-BUCKETS_PER_HOUR = 60 // BUCKET_MINUTES-BUCKETS_PER_DAY = 24 * BUCKETS_PER_HOUR-BUCKETS_PER_WEEK = 7 * BUCKETS_PER_DAY+__all__ = [+ "BUCKET_MINUTES",+ "BUCKETS_PER_DAY",+ "BUCKETS_PER_HOUR",+ "BUCKETS_PER_WEEK",+]diff --git a/products/apm/backend/logic/grid.py b/products/apm/backend/logic/grid.pynew file mode 100644index 000000000000..5c4ee188bd5e--- /dev/null+++ b/products/apm/backend/logic/grid.py@@ -0,0 +1,14 @@+"""Fixed grid constants. The 5-minute UTC bucket grid is architectural+(bucket identities must stay stable across ticks, backfills, and recomputes),+so unlike the dials in anomaly_detection/config.py these are not env-tunable.++Lives outside the anomaly_detection package because that package's __init__+re-exports the detector (numpy, scipy): consumers that need only the grid —+schedulers, Temporal workers — must be able to import it without paying for+the detector.+"""++BUCKET_MINUTES = 5+BUCKETS_PER_HOUR = 60 // BUCKET_MINUTES+BUCKETS_PER_DAY = 24 * BUCKETS_PER_HOUR+BUCKETS_PER_WEEK = 7 * BUCKETS_PER_DAYdiff --git a/products/logs/backend/facade/temporal.py b/products/logs/backend/facade/temporal.pyindex ed387b448d7f..ad66dc2e59d2 100644--- a/products/logs/backend/facade/temporal.py+++ b/products/logs/backend/facade/temporal.py@@ -18,6 +18,21 @@ from products.logs.backend.temporal.metrics import (LOGS_ALERTING_LATENCY_HISTOGRAM_METRICS,LogsAlertingMetricsInterceptor,)+from products.logs.backend.temporal.volume_tick import (+ ACTIVITIES as VOLUME_TICK_ACTIVITIES,+ WORKFLOWS as VOLUME_TICK_WORKFLOWS,+)+from products.logs.backend.temporal.volume_tick.activities import VolumeTickInput+from products.logs.backend.temporal.volume_tick.constants import (+ SCHEDULE_CRON as VOLUME_TICK_SCHEDULE_CRON,+ SCHEDULE_ID as VOLUME_TICK_SCHEDULE_ID,+ WORKFLOW_NAME as VOLUME_TICK_WORKFLOW_NAME,+)+from products.logs.backend.temporal.volume_tick.metrics import (+ LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_BUCKETS,+ LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS,+)+from products.logs.backend.temporal.volume_tick.schedule import create_logs_volume_tick_schedule__all__ = ["ACTIVITIES",@@ -26,6 +41,15 @@ __all__ = ["SCHEDULE_CRON","SCHEDULE_ID","WORKFLOW_NAME",+ "VOLUME_TICK_ACTIVITIES",+ "VOLUME_TICK_WORKFLOWS",+ "VOLUME_TICK_SCHEDULE_CRON",+ "VOLUME_TICK_SCHEDULE_ID",+ "VOLUME_TICK_WORKFLOW_NAME",+ "LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_BUCKETS",+ "LOGS_VOLUME_TICK_LATENCY_HISTOGRAM_METRICS",+ "VolumeTickInput",+ "create_logs_volume_tick_schedule","LOGS_ALERTING_COUNT_HISTOGRAM_BUCKETS","LOGS_ALERTING_COUNT_HISTOGRAM_METRICS","LOGS_ALERTING_LATENCY_HISTOGRAM_BUCKETS",diff --git a/products/logs/backend/temporal/volume_tick/__init__.py b/products/logs/backend/temporal/volume_tick/__init__.pynew file mode 100644index 000000000000..4c9413392aca--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/__init__.py@@ -0,0 +1,12 @@+from products.logs.backend.temporal.volume_tick.activities import volume_tick_heartbeat_activity+from products.logs.backend.temporal.volume_tick.workflow import LogsVolumeTickWorkflow++WORKFLOWS: list = [LogsVolumeTickWorkflow]+ACTIVITIES: list = [volume_tick_heartbeat_activity]++__all__ = [+ "ACTIVITIES",+ "WORKFLOWS",+ "LogsVolumeTickWorkflow",+ "volume_tick_heartbeat_activity",+]diff --git a/products/logs/backend/temporal/volume_tick/activities.py b/products/logs/backend/temporal/volume_tick/activities.pynew file mode 100644index 000000000000..d278453b38c0--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/activities.py@@ -0,0 +1,134 @@+import time+import dataclasses+from datetime import UTC, datetime, timedelta++import structlog+import temporalio.activity++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 posthog.sync import database_sync_to_async_pool++from products.logs.backend.temporal.volume_tick.constants import (+ BUCKET_MINUTES,+ BUCKET_SECONDS,+ FINALIZATION_ALLOWANCE,+ TEAMS_WITH_LOGS_WINDOW,+)+from products.logs.backend.temporal.volume_tick.metrics import (+ increment_tick_runs,+ record_clickhouse_duration,+ record_teams_with_logs,+)++logger = structlog.get_logger(__name__)++# The Temporal activity timeout cannot kill a ClickHouse query already running in+# the thread pool, so without server-side bounds each retry stacks another live+# scan. Timeout stays under half of ACTIVITY_TIMEOUT to leave retry room; the+# bytes cap is ~25x the expected read of the two narrow columns over the window,+# so it only trips on runaway volume, never on organic growth.+_DISCOVERY_QUERY_SETTINGS = {+ "max_execution_time": 25,+ "max_bytes_to_read": 5_000_000_000,+}+++# Temporal payload dataclasses stay on the stdlib form (the sibling alerting+# convention); @frozen's kw_only/slots buy nothing across the serialization boundary.[email protected](frozen=True)+class VolumeTickInput:+ pass++[email protected](frozen=True)+class VolumeTickOutput:+ ticked_at: str+ teams_with_logs: int+ minute_shard: int+ teams_due_in_shard: int+ due_bucket_start: str+ due_bucket_end: str+++@frozen+class DueBucket:+ start: datetime+ end: datetime+++def due_bucket_bounds(now: datetime) -> DueBucket:+ """The most recent 5-minute grid bucket that is due for finalization at `now`:+ the newest bucket whose close is at least FINALIZATION_ALLOWANCE in the past."""+ latest_finalizable_end = now - FINALIZATION_ALLOWANCE+ end_epoch = int(latest_finalizable_end.timestamp()) // BUCKET_SECONDS * BUCKET_SECONDS+ end = datetime.fromtimestamp(end_epoch, tz=UTC)+ return DueBucket(start=end - timedelta(seconds=BUCKET_SECONDS), end=end)+++@frozen+class TeamsWithLogs:+ total: int+ due_in_shard: int+++def count_teams_with_logs(begin: datetime, end: datetime, shard: int) -> TeamsWithLogs:+ """Distinct teams with at least one log record in [begin, end), and the subset+ whose `team_id % BUCKET_MINUTES` puts them in `shard`.++ Queries the physical `logs_distributed` table, not `logs` — `logs` is the+ HogQL table alias and does not exist for raw `sync_execute` SQL.+ """+ with tags_context(product=Product.LOGS, feature=Feature.PREAGGREGATION):+ rows = sync_execute(+ """+ SELECT+ uniqExact(team_id),+ uniqExactIf(team_id, modulo(team_id, %(shards)s) = %(shard)s)+ FROM logs_distributed+ WHERE timestamp >= %(begin)s AND timestamp < %(end)s+ """,+ {"begin": begin, "end": end, "shards": BUCKET_MINUTES, "shard": shard},+ workload=Workload.LOGS,+ settings=_DISCOVERY_QUERY_SETTINGS,+ )+ return TeamsWithLogs(total=int(rows[0][0]), due_in_shard=int(rows[0][1]))+++_count_teams_with_logs_async = database_sync_to_async_pool(count_teams_with_logs)+++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.+ ticked_at = datetime.now(UTC)+ due = due_bucket_bounds(ticked_at)+ # One team cohort per minute of the bucket: the every-minute schedule smears+ # teams across the bucket's minutes, so team_id % BUCKET_MINUTES is the shard.+ # Observed, not enforced: no per-shard work happens yet.+ minute_shard = ticked_at.minute % BUCKET_MINUTES+ started = time.monotonic()+ try:+ counts = await _count_teams_with_logs_async(ticked_at - TEAMS_WITH_LOGS_WINDOW, ticked_at, minute_shard)+ except Exception:+ increment_tick_runs("error")+ raise+ duration_ms = int((time.monotonic() - started) * 1000)++ record_clickhouse_duration(duration_ms)+ record_teams_with_logs(counts.total)+ increment_tick_runs("ok")+ output = VolumeTickOutput(+ ticked_at=ticked_at.isoformat(),+ teams_with_logs=counts.total,+ minute_shard=minute_shard,+ teams_due_in_shard=counts.due_in_shard,+ due_bucket_start=due.start.isoformat(),+ due_bucket_end=due.end.isoformat(),+ )+ logger.info("logs_volume_tick_heartbeat", clickhouse_duration_ms=duration_ms, **dataclasses.asdict(output))+ return outputdiff --git a/products/logs/backend/temporal/volume_tick/constants.py b/products/logs/backend/temporal/volume_tick/constants.pynew file mode 100644index 000000000000..954f8cad06e3--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/constants.py@@ -0,0 +1,36 @@+import os+from datetime import timedelta++from temporalio.common import RetryPolicy++from products.apm.backend.facade.constants import BUCKET_MINUTES++# Workflow+WORKFLOW_NAME = "logs-volume-tick"++# Schedule+SCHEDULE_ID = "logs-volume-tick-schedule"+SCHEDULE_CRON = "* * * * *"++# Activity+ACTIVITY_TIMEOUT = timedelta(minutes=1)+# Discovery heuristic only ("has this team logged recently"), independent of the+# grid; it equals one bucket length by coincidence.+TEAMS_WITH_LOGS_WINDOW = timedelta(minutes=5)++# The detector's fixed UTC grid, shared through the APM facade: bucket identities+# must stay stable across ticks, backfills, and recomputes, so this is+# deliberately not env-tunable.+BUCKET_SECONDS = BUCKET_MINUTES * 60+# A bucket only becomes due this long after it closes, so late-arriving logs are+# already in place when it is counted. Sized from measured prod ingestion lag:+# 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")))+# Starts as a mirror of the alerting policy but is tuned independently.+ACTIVITY_RETRY_POLICY = RetryPolicy(+ maximum_attempts=3,+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(seconds=30),+ backoff_coefficient=2.0,+)diff --git a/products/logs/backend/temporal/volume_tick/metrics.py b/products/logs/backend/temporal/volume_tick/metrics.pynew file mode 100644index 000000000000..4c99aad55d8c--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/metrics.py@@ -0,0 +1,50 @@+"""Prometheus metrics for the logs volume tick."""++import typing+import datetime as dt++from posthog.temporal.common.metrics import get_metric_meter++# 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_BUCKETS = [+ 50.0,+ 100.0,+ 250.0,+ 500.0,+ 1_000.0,+ 2_500.0,+ 5_000.0,+ 10_000.0,+ 30_000.0,+ 60_000.0,+]++TickOutcome = typing.Literal["ok", "error"]+++def increment_tick_runs(outcome: TickOutcome) -> None:+ meter = get_metric_meter({"outcome": outcome})+ counter = meter.create_counter("logs_volume_tick_runs_total", "Volume tick activity runs by outcome")+ counter.add(1)+++def record_teams_with_logs(count: int) -> None:+ meter = get_metric_meter()+ gauge = meter.create_gauge(+ "logs_volume_tick_teams_with_logs",+ "Teams that produced log records inside the tick's discovery window",+ )+ gauge.set(count)+++def record_clickhouse_duration(duration_ms: int) -> None:+ meter = get_metric_meter()+ hist = meter.create_histogram_timedelta(+ name="logs_volume_tick_clickhouse_duration_ms",+ description="Duration of the tick's ClickHouse discovery query",+ unit="ms",+ )+ hist.record(dt.timedelta(milliseconds=duration_ms))diff --git a/products/logs/backend/temporal/volume_tick/schedule.py b/products/logs/backend/temporal/volume_tick/schedule.pynew file mode 100644index 000000000000..e587e4dedcc0--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/schedule.py@@ -0,0 +1,38 @@+"""Schedule registration for the logs volume tick workflow."""++from dataclasses import asdict++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from products.logs.backend.temporal.volume_tick.activities import VolumeTickInput+from products.logs.backend.temporal.volume_tick.constants import SCHEDULE_CRON, SCHEDULE_ID, WORKFLOW_NAME+++async def create_logs_volume_tick_schedule(client: Client) -> None:+ """Create or update the logs volume tick schedule."""+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ WORKFLOW_NAME,+ asdict(VolumeTickInput()),+ id=SCHEDULE_ID,+ task_queue=settings.LOGS_VOLUME_TICK_TASK_QUEUE,+ ),+ spec=ScheduleSpec(cron_expressions=[SCHEDULE_CRON]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/logs/backend/temporal/volume_tick/workflow.py b/products/logs/backend/temporal/volume_tick/workflow.pynew file mode 100644index 000000000000..4f5fb90fb4f3--- /dev/null+++ b/products/logs/backend/temporal/volume_tick/workflow.py@@ -0,0 +1,37 @@+import temporalio+from temporalio import workflow++from posthog.temporal.common.base import PostHogWorkflow++# Activities live behind Django imports, which Temporal's workflow sandbox blocks.+# Mark them as pass-through; workflow code only passes them as references to+# `execute_activity`, never calls them.+with workflow.unsafe.imports_passed_through():+ from products.logs.backend.temporal.volume_tick.activities import (+ VolumeTickInput,+ VolumeTickOutput,+ volume_tick_heartbeat_activity,+ )++from products.logs.backend.temporal.volume_tick.constants import ACTIVITY_RETRY_POLICY, ACTIVITY_TIMEOUT, WORKFLOW_NAME++[email protected](name=WORKFLOW_NAME)+class LogsVolumeTickWorkflow(PostHogWorkflow):+ """One tick of the log volume rollup. A skeleton that writes nothing: it runs+ the every-minute schedule end to end and observes what the real tick would do+ (teams with logs, the due bucket, the minute-shard cohort) before any+ aggregation logic lands."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> VolumeTickInput:+ return VolumeTickInput()++ @temporalio.workflow.run+ async def run(self, input: VolumeTickInput) -> VolumeTickOutput:+ return await workflow.execute_activity(+ volume_tick_heartbeat_activity,+ input,+ start_to_close_timeout=ACTIVITY_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )diff --git a/products/logs/backend/test/test_volume_tick_workflow.py b/products/logs/backend/test/test_volume_tick_workflow.pynew file mode 100644index 000000000000..772055a8eaa2--- /dev/null+++ b/products/logs/backend/test/test_volume_tick_workflow.py@@ -0,0 +1,141 @@+import json+import uuid+import secrets+from dataclasses import asdict+from datetime import UTC, datetime, timedelta++import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin++from django.test import SimpleTestCase++from parameterized import parameterized+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.clickhouse.client import sync_execute++from products.logs.backend.temporal.volume_tick.activities import (+ VolumeTickInput,+ VolumeTickOutput,+ count_teams_with_logs,+ due_bucket_bounds,+)+from products.logs.backend.temporal.volume_tick.constants import BUCKET_MINUTES, WORKFLOW_NAME+from products.logs.backend.temporal.volume_tick.workflow import LogsVolumeTickWorkflow++TASK_QUEUE = "logs-volume-tick-test"+++async def test_schedule_shaped_invocation_runs_the_tick() -> None:+ # Invoke by workflow name with an asdict payload — the exact contract the+ # Temporal schedule uses — so a rename or input-shape drift fails here. The+ # activity is faked: the real one needs ClickHouse, and this test pins the+ # plumbing, not the query.+ @activity.defn(name="volume_tick_heartbeat_activity")+ async def fake_heartbeat(_input: VolumeTickInput) -> VolumeTickOutput:+ return VolumeTickOutput(+ ticked_at="2026-08-12T00:16:00+00:00",+ teams_with_logs=3,+ minute_shard=1,+ teams_due_in_shard=1,+ due_bucket_start="2026-08-12T00:00:00+00:00",+ due_bucket_end="2026-08-12T00:05:00+00:00",+ )++ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=TASK_QUEUE,+ workflows=[LogsVolumeTickWorkflow],+ activities=[fake_heartbeat],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WORKFLOW_NAME,+ asdict(VolumeTickInput()),+ id=f"test-volume-tick-{uuid.uuid4()}",+ task_queue=TASK_QUEUE,+ )++ assert result["teams_with_logs"] == 3+++class TestDueBucketBounds(SimpleTestCase):+ @parameterized.expand(+ [+ # 10:16:30 - 10min allowance = 10:06:30; newest closed grid end is 10:05.+ ("mid_window", datetime(2026, 8, 12, 10, 16, 30, tzinfo=UTC), datetime(2026, 8, 12, 10, 0, tzinfo=UTC)),+ # Exactly on the boundary: at 10:20:00 the 10:05-10:10 bucket becomes due.+ ("on_the_boundary", datetime(2026, 8, 12, 10, 20, 0, tzinfo=UTC), datetime(2026, 8, 12, 10, 5, tzinfo=UTC)),+ # One second before the boundary, the previous bucket is still the due one.+ (+ "second_before_boundary",+ datetime(2026, 8, 12, 10, 19, 59, tzinfo=UTC),+ datetime(2026, 8, 12, 10, 0, tzinfo=UTC),+ ),+ # Day boundary: just past midnight, the due bucket is yesterday's 23:45-23:50.+ ("day_rollover", datetime(2026, 8, 13, 0, 0, 30, tzinfo=UTC), datetime(2026, 8, 12, 23, 45, tzinfo=UTC)),+ ]+ )+ def test_due_bucket_bounds(self, _name: str, now: datetime, expected_start: datetime) -> None:+ due = due_bucket_bounds(now)+ assert due.start == expected_start+ assert due.end == expected_start + timedelta(minutes=5)+++class TestCountTeamsWithLogs(ClickhouseTestMixin, BaseTest):+ # The test ClickHouse keeps rows across runs and Postgres team ids repeat per+ # run, so neither a fixed window nor self.team gives isolation. Random team+ # ids plus delta assertions stay exact under any accumulated data.+ WINDOW_START = datetime(2031, 3, 1, 12, 0, tzinfo=UTC)+ WINDOW_END = WINDOW_START + timedelta(minutes=5)++ def _insert_log_rows(self, rows: list[tuple[int, datetime]]) -> None:+ payload = [+ {+ "uuid": str(uuid.uuid4()),+ "team_id": team_id,+ "timestamp": ts.strftime("%Y-%m-%d %H:%M:%S.%f"),+ "body": "volume tick test",+ "severity_text": "info",+ "severity_number": 9,+ "service_name": "svc",+ "resource_attributes": {},+ "attributes_map_str": {},+ }+ for team_id, ts in rows+ ]+ # Foreground insert: the async distributed-insert queue would race the+ # SELECT below and make the count flaky.+ sync_execute(+ "INSERT INTO logs_distributed FORMAT JSONEachRow\n" + "\n".join(json.dumps(r) for r in payload),+ settings={"distributed_foreground_insert": 1},+ )++ def test_counts_distinct_teams_inside_the_half_open_window(self) -> None:+ inside = self.WINDOW_START + timedelta(minutes=1)+ # Residue-controlled ids: team_a lands in shard 1, team_b in shard 2, so+ # the shard subset is exact regardless of what the random base is.+ base = (secrets.randbelow(2**27) + 1) * BUCKET_MINUTES+ team_a, team_b, team_c = base + 1, base + 2, base + 3+ before = count_teams_with_logs(self.WINDOW_START, self.WINDOW_END, shard=1)++ self._insert_log_rows(+ [+ (team_a, inside),+ (team_a, inside + timedelta(seconds=30)),+ (team_b, self.WINDOW_START),+ (team_c, self.WINDOW_START - timedelta(seconds=1)),+ (team_c, self.WINDOW_END),+ ]+ )++ after = count_teams_with_logs(self.WINDOW_START, self.WINDOW_END, shard=1)+ # +2, not +3: team_a counts once despite two rows, and team_c's rows sit+ # exactly on the outside of both half-open window edges.+ 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