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.

fix(cohorts): make event backfill day check ignore realtime rows (#69802)

Gustavo H. Strassburger3d832f977946
diff --git a/posthog/management/commands/backfill_precalculated_events.py b/posthog/management/commands/backfill_precalculated_events.py
index 02e10c18fffb..190f87448ed7 100644
--- a/posthog/management/commands/backfill_precalculated_events.py
+++ b/posthog/management/commands/backfill_precalculated_events.py
@@ -200,7 +200,7 @@ class Command(BaseCommand):
help="Number of concurrent child workflows to run (default: 5)",
)
parser.add_argument(
- "--force-reprocess",
+ "--ignore-backfilled-dates",
action="store_true",
default=False,
help="Skip the already-backfilled check and reprocess all days unconditionally",
@@ -212,7 +212,7 @@ class Command(BaseCommand):
cohort_id = options.get("cohort_id")
days_override = options.get("days")
concurrent_workflows = options["concurrent_workflows"]
- force_reprocess = options["force_reprocess"]
+ ignore_backfilled_dates = options["ignore_backfilled_dates"]
if team_id and team_ids_option:
raise CommandError("Cannot use both --team-id and --team-ids. Please use only one.")
@@ -371,7 +371,7 @@ class Command(BaseCommand):
cohort_ids=cohort_ids,
effective_days=effective_days,
concurrent_workflows=concurrent_workflows,
- force_reprocess=force_reprocess,
+ ignore_backfilled_dates=ignore_backfilled_dates,
)
except Exception as e:
self.stdout.write(self.style.ERROR(f"Failed to start workflow for team {current_team_id}: {e}"))
@@ -395,7 +395,7 @@ class Command(BaseCommand):
cohort_ids: list[int],
effective_days: int,
concurrent_workflows: int,
- force_reprocess: bool = False,
+ ignore_backfilled_dates: bool = False,
) -> str:
"""Run the Temporal coordinator workflow for the team."""
filter_storage_key = store_event_filters(filters, team_id)
@@ -416,7 +416,7 @@ class Command(BaseCommand):
condition_hashes=condition_hashes,
days_to_backfill=effective_days,
concurrent_workflows=concurrent_workflows,
- force_reprocess=force_reprocess,
+ ignore_backfilled_dates=ignore_backfilled_dates,
)
await client.start_workflow(
diff --git a/posthog/management/commands/test/test_backfill_precalculated_events.py b/posthog/management/commands/test/test_backfill_precalculated_events.py
index aa05d4d565ce..04bff734219e 100644
--- a/posthog/management/commands/test/test_backfill_precalculated_events.py
+++ b/posthog/management/commands/test/test_backfill_precalculated_events.py
@@ -838,7 +838,7 @@ class TestRunTemporalWorkflow(BaseTest):
cohort_ids=[1, 2],
effective_days=14,
concurrent_workflows=5,
- force_reprocess=False,
+ ignore_backfilled_dates=False,
)
mock_store.assert_called_once_with(self.filters, self.team.id)
@@ -853,7 +853,7 @@ class TestRunTemporalWorkflow(BaseTest):
self.assertEqual(inputs.condition_hashes, ["hash_1", "hash_2"])
self.assertEqual(inputs.days_to_backfill, 14)
self.assertEqual(inputs.concurrent_workflows, 5)
- self.assertFalse(inputs.force_reprocess)
+ self.assertFalse(inputs.ignore_backfilled_dates)
self.assertEqual(kwargs["task_queue"], settings.MESSAGING_TASK_QUEUE)
self.assertEqual(kwargs["id_reuse_policy"], WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY)
self.assertEqual(kwargs["id"], workflow_id)
diff --git a/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py
index f8dc8f07ac54..5bb7da80ea81 100644
--- a/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_events_coordinator_workflow.py
@@ -13,6 +13,7 @@ import temporalio.exceptions
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.messaging.backfill_precalculated_events_workflow import BackfillPrecalculatedEventsInputs
+from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX
@dataclasses.dataclass
@@ -43,17 +44,22 @@ async def check_day_already_backfilled_activity(inputs: EventDateCheckInputs) ->
if not inputs.condition_hashes:
return EventDateCheckResult(date=inputs.date, already_backfilled=False)
+ # Only rows written by the backfill count: the realtime consumer also writes to this
+ # table (stamped with its ingestion day), so its rows would otherwise mask days whose
+ # pre-cohort events were never scanned - e.g. the hours before a cohort was created.
query = """
SELECT count(DISTINCT condition) as condition_count
FROM precalculated_events
WHERE team_id = %(team_id)s
AND date = %(date)s
AND condition IN %(condition_hashes)s
+ AND source LIKE %(source_prefix)s
"""
query_params = {
"team_id": inputs.team_id,
"date": inputs.date,
"condition_hashes": inputs.condition_hashes,
+ "source_prefix": f"{BACKFILL_EVENT_SOURCE_PREFIX}%",
}
with tags_context(
@@ -70,6 +76,22 @@ async def check_day_already_backfilled_activity(inputs: EventDateCheckInputs) ->
return EventDateCheckResult(date=inputs.date, already_backfilled=already_backfilled)
+def compute_day_ranges(now: dt.datetime, days_to_backfill: int) -> list[tuple[dt.datetime, dt.datetime, bool]]:
+ """Partition the backfill window into daily [start, end, is_partial) ranges, most recent first.
+
+ Today's range is partial: it ends at `now` rather than at the end of the day.
+ """
+ day_ranges: list[tuple[dt.datetime, dt.datetime, bool]] = []
+ for day_offset in range(days_to_backfill):
+ day_start = (now - dt.timedelta(days=day_offset)).replace(hour=0, minute=0, second=0, microsecond=0)
+ day_end = day_start + dt.timedelta(days=1)
+ is_partial = day_offset == 0
+ if is_partial:
+ day_end = now
+ day_ranges.append((day_start, day_end, is_partial))
+ return day_ranges
+
+
@dataclasses.dataclass
class BackfillPrecalculatedEventsCoordinatorInputs:
"""Inputs for the coordinator workflow."""
@@ -80,7 +102,7 @@ class BackfillPrecalculatedEventsCoordinatorInputs:
condition_hashes: list[str]
days_to_backfill: int
concurrent_workflows: int = 5
- force_reprocess: bool = False
+ ignore_backfilled_dates: bool = False
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -92,7 +114,7 @@ class BackfillPrecalculatedEventsCoordinatorInputs:
"days_to_backfill": self.days_to_backfill,
"concurrent_workflows": self.concurrent_workflows,
"condition_count": len(self.condition_hashes),
- "force_reprocess": self.force_reprocess,
+ "ignore_backfilled_dates": self.ignore_backfilled_dates,
}
@@ -176,14 +198,7 @@ class BackfillPrecalculatedEventsCoordinatorWorkflow(PostHogWorkflow):
# Compute the daily time ranges to process (most recent first for faster value delivery)
now = temporalio.workflow.now()
- day_ranges: list[tuple[dt.datetime, dt.datetime]] = []
- for day_offset in range(inputs.days_to_backfill):
- day_start = (now - dt.timedelta(days=day_offset)).replace(hour=0, minute=0, second=0, microsecond=0)
- day_end = day_start + dt.timedelta(days=1)
- # For today's partial day, use now as the end
- if day_offset == 0:
- day_end = now
- day_ranges.append((day_start, day_end))
+ day_ranges = compute_day_ranges(now, inputs.days_to_backfill)
workflow_logger.info(
f"Partitioned into {len(day_ranges)} daily chunks, "
@@ -196,11 +211,13 @@ class BackfillPrecalculatedEventsCoordinatorWorkflow(PostHogWorkflow):
failed_count = 0
days_skipped = 0
- for day_start, day_end in day_ranges:
+ for day_start, day_end, is_partial in day_ranges:
date_str = day_start.strftime("%Y-%m-%d")
- # Check if this day is already backfilled (skippable unless force_reprocess is set)
- if not inputs.force_reprocess:
+ # Check if this day is already backfilled (skippable unless ignore_backfilled_dates is set).
+ # Today's partial day is never skipped: existing rows only prove coverage up to an
+ # earlier run's start time, not up to now.
+ if not inputs.ignore_backfilled_dates and not is_partial:
check_result = await temporalio.workflow.execute_activity(
check_day_already_backfilled_activity,
EventDateCheckInputs(
diff --git a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py b/posthog/temporal/messaging/backfill_precalculated_events_workflow.py
index d9ee68f22200..898ca4dee665 100644
--- a/posthog/temporal/messaging/backfill_precalculated_events_workflow.py
+++ b/posthog/temporal/messaging/backfill_precalculated_events_workflow.py
@@ -21,6 +21,7 @@ from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.logger import get_logger
+from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX
from posthog.temporal.messaging.filter_storage import get_event_filters
from posthog.temporal.messaging.types import BehavioralEventFilter
@@ -327,7 +328,7 @@ async def backfill_precalculated_events_activity(
"distinct_id": distinct_id,
"condition": condition_hash,
"date": event_date,
- "source": f"cohort_event_backfill_{condition_hash}",
+ "source": f"{BACKFILL_EVENT_SOURCE_PREFIX}_{condition_hash}",
},
)
kafka_results.append(produce_result)
diff --git a/posthog/temporal/messaging/constants.py b/posthog/temporal/messaging/constants.py
index 18d25c616e52..9d0baccd0802 100644
--- a/posthog/temporal/messaging/constants.py
+++ b/posthog/temporal/messaging/constants.py
@@ -1,5 +1,10 @@
"""Shared constants for temporal messaging workflows."""
+# precalculated_events.source prefix written by the event backfill (as opposed to the
+# realtime consumer, which writes a "cohort_filter_" prefix). Shared so the day-already-
+# backfilled check and the backfill writer can't drift apart.
+BACKFILL_EVENT_SOURCE_PREFIX = "cohort_event_backfill"
+
# Workflow IDs and patterns
REALTIME_COHORT_CALCULATION_SCHEDULE_ID = "realtime-cohort-calculation-schedule"
REALTIME_COHORT_CALCULATION_COORDINATOR_WORKFLOW_NAME = "realtime-cohort-calculation-coordinator"
diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py
index cc10051abe25..07aab7232fd5 100644
--- a/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py
+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_events_coordinator_workflow.py
@@ -1,3 +1,5 @@
+import datetime as dt
+
import pytest
from unittest.mock import AsyncMock, patch
@@ -5,7 +7,9 @@ from posthog.temporal.messaging.backfill_precalculated_events_coordinator_workfl
BackfillPrecalculatedEventsCoordinatorInputs,
EventDateCheckInputs,
check_day_already_backfilled_activity,
+ compute_day_ranges,
)
+from posthog.temporal.messaging.constants import BACKFILL_EVENT_SOURCE_PREFIX
class TestEventDateCheckInputs:
@@ -47,7 +51,7 @@ class TestBackfillPrecalculatedEventsCoordinatorInputs:
)
assert inputs.concurrent_workflows == 5
- def test_default_force_reprocess(self):
+ def test_default_ignore_backfilled_dates(self):
inputs = BackfillPrecalculatedEventsCoordinatorInputs(
team_id=1,
filter_storage_key="key",
@@ -55,19 +59,19 @@ class TestBackfillPrecalculatedEventsCoordinatorInputs:
condition_hashes=["hash1"],
days_to_backfill=7,
)
- assert inputs.force_reprocess is False
+ assert inputs.ignore_backfilled_dates is False
- def test_force_reprocess_in_properties_to_log(self):
+ def test_ignore_backfilled_dates_in_properties_to_log(self):
inputs = BackfillPrecalculatedEventsCoordinatorInputs(
team_id=1,
filter_storage_key="key",
cohort_ids=[1],
condition_hashes=["hash1"],
days_to_backfill=7,
- force_reprocess=True,
+ ignore_backfilled_dates=True,
)
props = inputs.properties_to_log
- assert props["force_reprocess"] is True
+ assert props["ignore_backfilled_dates"] is True
class TestCheckDayAlreadyBackfilledActivity:
@@ -112,3 +116,42 @@ class TestCheckDayAlreadyBackfilledActivity:
assert result.date == "2024-01-15"
assert result.already_backfilled is expected_backfilled
+
+ @pytest.mark.asyncio
+ async def test_day_check_counts_only_backfill_written_rows(self):
+ inputs = EventDateCheckInputs(
+ team_id=1,
+ condition_hashes=["hash1"],
+ date="2024-01-15",
+ )
+
+ mock_client = AsyncMock()
+ mock_client.read_query = AsyncMock(return_value=b"1\n")
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=False)
+
+ with patch(
+ "posthog.temporal.messaging.backfill_precalculated_events_coordinator_workflow.get_client",
+ return_value=mock_client,
+ ):
+ await check_day_already_backfilled_activity(inputs)
+
+ executed_query, executed_params = mock_client.read_query.call_args[0]
+ assert "source LIKE %(source_prefix)s" in executed_query
+ assert executed_params["source_prefix"] == f"{BACKFILL_EVENT_SOURCE_PREFIX}%"
+
+
+class TestComputeDayRanges:
+ def test_today_is_partial_and_past_days_are_full(self):
+ now = dt.datetime(2026, 7, 9, 15, 30, 45, tzinfo=dt.UTC)
+ ranges = compute_day_ranges(now, 3)
+ assert ranges == [
+ (dt.datetime(2026, 7, 9, tzinfo=dt.UTC), now, True),
+ (dt.datetime(2026, 7, 8, tzinfo=dt.UTC), dt.datetime(2026, 7, 9, tzinfo=dt.UTC), False),
+ (dt.datetime(2026, 7, 7, tzinfo=dt.UTC), dt.datetime(2026, 7, 8, tzinfo=dt.UTC), False),
+ ]
+
+ def test_single_day_backfill_is_partial(self):
+ now = dt.datetime(2026, 7, 9, 15, 30, 45, tzinfo=dt.UTC)
+ ranges = compute_day_ranges(now, 1)
+ assert ranges == [(dt.datetime(2026, 7, 9, tzinfo=dt.UTC), now, True)]