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(growth): add timestamp to product event ingest event (#63536)

Fernando Gomesf952c142c1eb
diff --git a/posthog/models/team/production_event_activation.py b/posthog/models/team/production_event_activation.py
index 6661216430ab..b5b53a73c4ef 100644
--- a/posthog/models/team/production_event_activation.py
+++ b/posthog/models/team/production_event_activation.py
@@ -15,7 +15,12 @@ touching the rest of the system:
the only code that marks the column and emits the
`first team production event ingested` analytics event.
Idempotent under concurrent runs via `SELECT FOR UPDATE
- SKIP LOCKED`.
+ SKIP LOCKED`. The emitted event is stamped with the team's
+ conversion time on the web leg (the earliest production-host
+ event in the window, carried on the signal) and the run time
+ otherwise — never the SDK's default send time, so the
+ milestone lands when the team converted, not when the daily
+ sweep noticed.
Scheduling lives in `products/growth/dags/team_production_event_activation.py`,
which wires these helpers into a Dagster job + daily schedule.
@@ -50,8 +55,8 @@ deployments report private ones) can never satisfy any leg.
"""
from collections.abc import Iterable, Mapping
-from dataclasses import dataclass
-from datetime import datetime, timedelta
+from dataclasses import dataclass, replace
+from datetime import UTC, datetime, timedelta
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import Final, Literal
@@ -136,11 +141,18 @@ class ProductionTrafficSignal:
`production_host` is set for the web leg; `distinct_count` carries the
device count (mobile leg) or user count (server leg).
+
+ `converted_at` is the team's activation instant: the event timestamp of the
+ earliest production-host event in the window. Only the web leg can resolve a
+ precise instant cheaply, so it stays None for the mobile/server legs (their
+ qualifying moment is a windowed threshold-crossing) and the transition falls
+ back to the run time for those.
"""
kind: Literal["production_host", "mobile_physical_devices", "server_lib_users"]
production_host: str | None = None
distinct_count: int | None = None
+ converted_at: datetime | None = None
# Reserved / non-public TLD suffixes. A host ending in one of these is a dev or
@@ -342,9 +354,97 @@ def _teams_meeting_criterion(team_ids: Iterable[int]) -> dict[int, ProductionTra
)
elif server_lib_users >= SERVER_LIB_USERS_THRESHOLD:
qualifying[team_id] = ProductionTrafficSignal(kind="server_lib_users", distinct_count=server_lib_users)
+
+ # Resolve the web leg's conversion instant. Done as a second, narrowly
+ # scoped query (only the teams that just qualified on the web leg, only
+ # their chosen host) so query 1's full-batch scan and per-team host cap stay
+ # untouched. Mobile/server keep `converted_at=None` — their qualifying
+ # moment is a windowed threshold-crossing the transition doesn't need.
+ web_team_hosts: dict[int, str] = {}
+ for team_id, signal in qualifying.items():
+ if signal.kind == "production_host" and signal.production_host is not None:
+ web_team_hosts[team_id] = signal.production_host
+ if web_team_hosts:
+ for team_id, converted_at in _earliest_production_host_timestamps(
+ web_team_hosts, host_expr, current_url_expr, workload
+ ).items():
+ qualifying[team_id] = replace(qualifying[team_id], converted_at=converted_at)
+
return qualifying
+def _earliest_production_host_timestamps(
+ team_hosts: Mapping[int, str],
+ host_expr: str,
+ current_url_expr: str,
+ workload: Workload,
+) -> dict[int, datetime]:
+ """Earliest in-window event timestamp per (team, qualifying production host).
+
+ This is the web-leg activation instant — when the team's first visible
+ production event happened — used to stamp the emitted analytics event so the
+ milestone lands at conversion time rather than at sweep time.
+
+ Scoped to the already-qualified web-leg teams and their chosen hosts via the
+ `team_id` primary-key prefix, so this scan touches only that small subset.
+ Uses `timestamp` (event time, the same column the window filters on), not
+ `_timestamp` (ingestion time), to keep the instant consistent with the rest
+ of the criterion; the trailing-window filter already bounds how far back a
+ client-reported time can pull it.
+ """
+ if not team_hosts:
+ return {}
+
+ # `host IN (...)` rather than a `(team_id, host)` tuple-IN: a flat string
+ # list is the same parameter shape the criterion query already relies on.
+ # A host shared across teams over-matches harmlessly — rows are keyed by
+ # (team_id, host) below and only the team's own chosen host is read back.
+ production_hosts = list(set(team_hosts.values()))
+ # As in `_teams_meeting_criterion`: the interpolated fragments are
+ # server-side SQL expressions from get_property_string_expr, never user
+ # input; all values go through query parameters.
+ query = f"""
+ SELECT team_id, host, min(timestamp) AS converted_at
+ FROM (
+ SELECT
+ team_id,
+ substring(
+ if({host_expr} != '', {host_expr}, domain({current_url_expr})),
+ 1,
+ %(host_length_cap)s
+ ) AS host,
+ timestamp
+ FROM events
+ WHERE team_id IN %(team_ids)s
+ AND timestamp >= now() - toIntervalDay(%(window_days)s)
+ )
+ WHERE host IN %(production_hosts)s
+ GROUP BY team_id, host
+ """
+ with tags_context(product=Product.GROWTH, feature=Feature.ENRICHMENT):
+ rows = sync_execute(
+ query,
+ {
+ "team_ids": list(team_hosts.keys()),
+ "production_hosts": production_hosts,
+ "window_days": WINDOW_DAYS,
+ "host_length_cap": SQL_HOST_LENGTH_CAP,
+ },
+ workload=workload,
+ settings={"max_execution_time": 600},
+ )
+
+ converted_at_by_team_host = {(team_id, host): converted_at for team_id, host, converted_at in rows}
+ result: dict[int, datetime] = {}
+ for team_id, host in team_hosts.items():
+ converted_at = converted_at_by_team_host.get((team_id, host))
+ if converted_at is not None:
+ # ClickHouse DateTime is UTC; coerce naive driver values to aware so
+ # the PostHog client doesn't guess a timezone at capture time.
+ result[team_id] = converted_at if converted_at.tzinfo else converted_at.replace(tzinfo=UTC)
+ return result
+
+
# --- Transition -------------------------------------------------------------
@@ -410,6 +510,10 @@ def _mark_teams_ingested_production_event(team_signals: Mapping[int, ProductionT
event="first team production event ingested",
properties={key: value for key, value in properties.items() if value is not None},
groups=groups(team=team),
+ # Conversion time for the web leg; run time otherwise. Either
+ # way explicit, so the milestone never drifts to the SDK's
+ # default (the flush-loop wall clock) — see `converted_at`.
+ timestamp=signal.converted_at or now,
)
except Exception as e:
capture_exception(e, {"team": "team-growth", "team_id": team.id})
diff --git a/posthog/models/team/test_production_event_activation.py b/posthog/models/team/test_production_event_activation.py
index f21fbc21e68a..c04c05415d53 100644
--- a/posthog/models/team/test_production_event_activation.py
+++ b/posthog/models/team/test_production_event_activation.py
@@ -48,15 +48,20 @@ def _seed_event(
properties: dict[str, Any] | None = None,
days_ago: float = 1,
distinct_id: str = "user-0",
-) -> None:
+) -> datetime:
+ # `now()` lives in this helper (not a `test_*` body) on purpose: tests that
+ # need the event's instant read it from the return value instead of
+ # recomputing it, which keeps them off the time-sensitivity semgrep rule.
+ timestamp = datetime.now(tz=UTC) - timedelta(days=days_ago)
_create_event(
team=Team.objects.get(id=team_id),
event="$pageview",
distinct_id=distinct_id,
- timestamp=datetime.now(tz=UTC) - timedelta(days=days_ago),
+ timestamp=timestamp,
properties=properties or {},
)
flush_persons_and_events()
+ return timestamp
def _seed_mobile_events(team_id: int, device_count: int, is_emulator: Any = False) -> None:
@@ -160,9 +165,39 @@ class TestTeamsMeetingCriterion(ClickhouseTestMixin, BaseTest):
def test_team_with_no_events_does_not_qualify(self) -> None:
self.assertEqual(_teams_meeting_criterion([self.team.id]), {})
+ def _assert_web_qualifiers(self, result: dict[int, ProductionTrafficSignal], expected: dict[int, str]) -> None:
+ # Web signals carry a time-dependent `converted_at`, so compare every
+ # field except that one; `converted_at` has dedicated tests below.
+ self.assertEqual(set(result), set(expected))
+ for team_id, host in expected.items():
+ self.assertEqual(result[team_id].kind, "production_host")
+ self.assertEqual(result[team_id].production_host, host)
+ self.assertIsNotNone(result[team_id].converted_at)
+
def test_single_production_event_qualifies(self) -> None:
_seed_event(self.team.id, properties={"$host": PRODUCTION_HOST})
- self.assertEqual(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST_SIGNAL})
+ self._assert_web_qualifiers(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST})
+
+ def test_web_signal_carries_earliest_production_event_timestamp(self) -> None:
+ # The conversion instant is the earliest production-host event in the
+ # window; a later production event must not move it, and a dev event in
+ # between must not become it.
+ earliest = _seed_event(self.team.id, properties={"$host": PRODUCTION_HOST}, days_ago=5)
+ _seed_event(self.team.id, properties={"$host": "localhost:3000"}, days_ago=4)
+ _seed_event(self.team.id, properties={"$host": PRODUCTION_HOST}, days_ago=2)
+
+ signal = _teams_meeting_criterion([self.team.id])[self.team.id]
+ self.assertEqual(signal.kind, "production_host")
+ self.assertIsNotNone(signal.converted_at)
+ assert signal.converted_at is not None # narrow for the subtraction below
+ self.assertLess(abs((signal.converted_at - earliest).total_seconds()), 1)
+
+ def test_mobile_signal_has_no_conversion_timestamp(self) -> None:
+ # Only the web leg resolves a precise instant; mobile/server stay None.
+ _seed_mobile_events(self.team.id, device_count=MOBILE_PHYSICAL_DEVICES_THRESHOLD)
+ signal = _teams_meeting_criterion([self.team.id])[self.team.id]
+ self.assertEqual(signal.kind, "mobile_physical_devices")
+ self.assertIsNone(signal.converted_at)
def test_dev_only_traffic_does_not_qualify(self) -> None:
for host in ["localhost:3000", "127.0.0.1:8000", "myapp.test", "192.168.1.10"]:
@@ -171,7 +206,7 @@ class TestTeamsMeetingCriterion(ClickhouseTestMixin, BaseTest):
def test_current_url_fallback_qualifies(self) -> None:
_seed_event(self.team.id, properties={"$current_url": f"https://{PRODUCTION_HOST}/dashboard?x=1"})
- self.assertEqual(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST_SIGNAL})
+ self._assert_web_qualifiers(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST})
def test_local_host_takes_precedence_over_production_current_url(self) -> None:
_seed_event(
@@ -191,7 +226,7 @@ class TestTeamsMeetingCriterion(ClickhouseTestMixin, BaseTest):
def test_mixed_dev_and_production_traffic_qualifies_with_production_host(self) -> None:
_seed_event(self.team.id, properties={"$host": "myapp.test"})
_seed_event(self.team.id, properties={"$host": PRODUCTION_HOST})
- self.assertEqual(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST_SIGNAL})
+ self._assert_web_qualifiers(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST})
def test_mobile_physical_devices_at_threshold_qualify(self) -> None:
_seed_mobile_events(self.team.id, device_count=MOBILE_PHYSICAL_DEVICES_THRESHOLD)
@@ -269,7 +304,7 @@ class TestTeamsMeetingCriterion(ClickhouseTestMixin, BaseTest):
_seed_mobile_events(self.team.id, device_count=MOBILE_PHYSICAL_DEVICES_THRESHOLD)
_seed_server_events(self.team.id, user_count=SERVER_LIB_USERS_THRESHOLD)
_seed_event(self.team.id, properties={"$host": PRODUCTION_HOST})
- self.assertEqual(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST_SIGNAL})
+ self._assert_web_qualifiers(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST})
def test_only_listed_teams_are_evaluated(self) -> None:
other_team = Team.objects.create(organization=self.organization, name="other")
@@ -277,7 +312,7 @@ class TestTeamsMeetingCriterion(ClickhouseTestMixin, BaseTest):
_seed_event(other_team.id, properties={"$host": PRODUCTION_HOST})
# other_team has production events but isn't in the input set, so isn't returned.
- self.assertEqual(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST_SIGNAL})
+ self._assert_web_qualifiers(_teams_meeting_criterion([self.team.id]), {self.team.id: PRODUCTION_HOST})
class TestMarkTeamsIngestedProductionEvent(BaseTest):
@@ -301,6 +336,8 @@ class TestMarkTeamsIngestedProductionEvent(BaseTest):
((), kwargs) = capture.call_args
self.assertEqual(kwargs["event"], "first team production event ingested")
self.assertEqual(kwargs["distinct_id"], str(self.team.uuid))
+ # No `converted_at` on this signal, so the emit falls back to run time.
+ self.assertEqual(kwargs["timestamp"], now)
self.assertEqual(
kwargs["properties"],
{
@@ -311,6 +348,20 @@ class TestMarkTeamsIngestedProductionEvent(BaseTest):
},
)
+ def test_web_signal_emits_with_conversion_timestamp(self) -> None:
+ converted_at = datetime(2026, 5, 30, 8, 0, 0, tzinfo=UTC)
+ signal = ProductionTrafficSignal(
+ kind="production_host", production_host=PRODUCTION_HOST, converted_at=converted_at
+ )
+
+ with _mock_capture() as capture:
+ _mark_teams_ingested_production_event({self.team.id: signal}, now=_FIXED_NOW)
+
+ ((), kwargs) = capture.call_args
+ # Web leg stamps the conversion instant, not the run time.
+ self.assertEqual(kwargs["timestamp"], converted_at)
+ self.assertNotEqual(kwargs["timestamp"], _FIXED_NOW)
+
def test_mobile_signal_emits_distinct_count(self) -> None:
signal = ProductionTrafficSignal(kind="mobile_physical_devices", distinct_count=4)
@@ -319,6 +370,8 @@ class TestMarkTeamsIngestedProductionEvent(BaseTest):
self.assertEqual(marked, 1)
((), kwargs) = capture.call_args
+ # Mobile leg has no conversion instant, so it stamps the run time.
+ self.assertEqual(kwargs["timestamp"], _FIXED_NOW)
self.assertEqual(
kwargs["properties"],
{
@@ -392,6 +445,21 @@ class TestEvaluateAndMarkTeamBatch(ClickhouseTestMixin, BaseTest):
datetime(2026, 6, 5, 12, 0, 0, tzinfo=UTC),
)
+ def test_web_qualifier_emits_at_conversion_time(self) -> None:
+ # End-to-end through the batch: the activation event is stamped at the
+ # production event's own time, not the run time we pass as `now`.
+ conversion_time = _seed_event(self.team.id, properties={"$host": PRODUCTION_HOST}, days_ago=3)
+
+ with _mock_capture() as capture:
+ evaluate_and_mark_team_batch([self.team.id], now=_FIXED_NOW)
+
+ ((), kwargs) = capture.call_args
+ self.assertEqual(kwargs["event"], "first team production event ingested")
+ emitted = kwargs["timestamp"]
+ self.assertIsNotNone(emitted)
+ assert emitted is not None # narrow for the subtraction below
+ self.assertLess(abs((emitted - conversion_time).total_seconds()), 1)
+
def test_non_qualifying_team_only_gets_last_checked_at_bumped(self) -> None:
_seed_event(self.team.id, properties={"$host": "localhost:3000"})
with freeze_time("2026-06-05T12:00:00Z"):