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(web-analytics): stop classifying cookieless events as bots (#98097)

Jordan Mryyan939d1b598804
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b478c4b77c0e..768689ee62fe 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -28715,6 +28715,10 @@
"convertToProjectTimezone": {
"type": "boolean"
},
+ "cookielessTrafficIsRegular": {
+ "description": "Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients.",
+ "type": ["boolean", "null"]
+ },
"customBotDefinitions": {
"items": {
"$ref": "#/definitions/CustomBotRule"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 491fdfc92f4b..545189927c7b 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -526,6 +526,8 @@ export interface HogQLQueryModifiers {
useMaterializedViews?: boolean
customChannelTypeRules?: CustomChannelRule[]
customBotDefinitions?: CustomBotRule[]
+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
+ cookielessTrafficIsRegular?: boolean | null
useWebAnalyticsPreAggregatedTables?: boolean
/** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */
webAnalyticsFirstPageviewFilters?: boolean
diff --git a/posthog/hogql/functions/test/test_traffic_type_functions.py b/posthog/hogql/functions/test/test_traffic_type_functions.py
index 77cff376c9b6..7fa7cc420a2f 100644
--- a/posthog/hogql/functions/test/test_traffic_type_functions.py
+++ b/posthog/hogql/functions/test/test_traffic_type_functions.py
@@ -945,3 +945,126 @@ class TestCustomBotDefinitions(ClickhouseTestMixin, BaseTest):
)
assert is_bot is False
+
+
+class TestCookielessClassification(ClickhouseTestMixin, BaseTest):
+ def _classify(
+ self,
+ properties: dict,
+ cookieless_traffic_is_regular: bool = True,
+ definitions: list[CustomBotRule] | None = None,
+ ) -> tuple:
+ modifiers: dict = {"cookielessTrafficIsRegular": cookieless_traffic_is_regular}
+ if definitions:
+ modifiers["customBotDefinitions"] = [d.model_dump(mode="json") for d in definitions]
+ self.team.modifiers = modifiers
+ self.team.save()
+
+ tag = uuid4().hex
+ _create_event(
+ team=self.team,
+ distinct_id="visitor",
+ event="$pageview",
+ properties={**properties, "_test_tag": tag},
+ )
+ flush_persons_and_events()
+
+ response = execute_hogql_query(
+ "SELECT `$virt_is_bot`, `$virt_traffic_type`, `$virt_traffic_category`, `$virt_bot_name`, "
+ "`$virt_bot_operator`, getBotType(properties.`$raw_user_agent`, properties.`$ip`) "
+ f"FROM events WHERE properties._test_tag = '{tag}'",
+ self.team,
+ )
+ assert response.results is not None
+ return response.results[0]
+
+ @parameterized.expand(
+ [("missing", {}), ("empty", {"$raw_user_agent": ""}), ("string_flag", {"$cookieless_mode": "true"})]
+ )
+ def test_a_cookieless_event_is_regular_traffic(self, _name: str, properties: dict) -> None:
+ assert self._classify({"$cookieless_mode": True, **properties}) == (False, "Regular", "regular", "", "", "")
+
+ @parameterized.expand(
+ [
+ ("user_agent", {"$raw_user_agent": "Googlebot/2.1"}, False),
+ ("ip", {"$ip": "66.249.66.1"}, False),
+ ("user_agent_with_project_rules", {"$raw_user_agent": "Googlebot/2.1"}, True),
+ ("ip_with_project_rules", {"$ip": "66.249.66.1"}, True),
+ ]
+ )
+ def test_positive_bot_signals_still_classify_cookieless_events(
+ self, _name: str, properties: dict, with_project_rules: bool
+ ) -> None:
+ definitions = (
+ [_custom_bot(name="Staging checker", key=CustomBotField.FIELD_HOST, pattern="staging")]
+ if with_project_rules
+ else None
+ )
+ assert self._classify({"$cookieless_mode": True, **properties}, definitions=definitions) == (
+ True,
+ "Bot",
+ "search_crawler",
+ "Googlebot",
+ "Google",
+ "search_crawler",
+ )
+
+ def test_a_cookieless_event_is_still_automation_while_the_rollout_is_off(self):
+ assert self._classify({"$cookieless_mode": True}, cookieless_traffic_is_regular=False) == (
+ True,
+ "Automation",
+ "no_user_agent",
+ "",
+ "",
+ "no_user_agent",
+ )
+
+ def test_a_non_cookieless_event_with_no_user_agent_is_still_automation(self):
+ assert self._classify({}) == (True, "Automation", "no_user_agent", "", "", "no_user_agent")
+
+ def test_the_flag_is_read_as_a_value_not_as_presence(self):
+ is_bot, traffic_type, _category, _name, _operator, _bot_type = self._classify(
+ {"$cookieless_mode": False, "$raw_user_agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"}
+ )
+
+ assert (is_bot, traffic_type) == (True, "Bot")
+
+ @parameterized.expand(
+ [("no_builtin", {}), ("user_agent", {"$raw_user_agent": "Googlebot/2.1"}), ("ip", {"$ip": "66.249.66.1"})]
+ )
+ def test_a_project_rule_still_names_a_cookieless_event(self, _name: str, properties: dict) -> None:
+ is_bot, traffic_type, category, name, _operator, bot_type = self._classify(
+ {"$cookieless_mode": True, "$host": "staging.example.com", **properties},
+ definitions=[
+ _custom_bot(
+ name="Staging checker", key=CustomBotField.FIELD_HOST, pattern="staging", category="monitoring"
+ )
+ ],
+ )
+
+ assert (is_bot, traffic_type, category, name, bot_type) == (
+ True,
+ "Bot",
+ "monitoring",
+ "Staging checker",
+ "monitoring",
+ )
+
+
+COOKIELESS_ON = HogQLQueryModifiers(cookielessTrafficIsRegular=True)
+
+
+class TestCookielessOverrideExpression:
+ @parameterized.expand(
+ [
+ ("getTrafficType", get_traffic_type, "if"),
+ ("isLikelyBot", is_bot, "toBool"),
+ ]
+ )
+ def test_a_user_agent_with_no_properties_object_is_left_unwrapped(self, name, factory_fn, expected_top_call):
+ result = factory_fn(
+ node=ast.Call(name=name, args=[]), args=[ast.Call(name="lower", args=[])], modifiers=COOKIELESS_ON
+ )
+
+ assert isinstance(result, ast.Call)
+ assert result.name == expected_top_call
diff --git a/posthog/hogql/functions/traffic_type.py b/posthog/hogql/functions/traffic_type.py
index da0007041b48..1ba832265ffe 100644
--- a/posthog/hogql/functions/traffic_type.py
+++ b/posthog/hogql/functions/traffic_type.py
@@ -51,6 +51,9 @@ if TYPE_CHECKING:
from posthog.schema import HogQLQueryModifiers
+COOKIELESS_MODE_FIELD = "$cookieless_mode"
+
+
def _custom_groups(modifiers: Optional["HogQLQueryModifiers"]) -> list[CustomBotGroup]:
if modifiers is None:
return []
@@ -101,6 +104,34 @@ def _property_expr(key: str, args: list[ast.Expr]) -> Optional[ast.Expr]:
return None
+def _cookieless_missing_user_agent(
+ args: list[ast.Expr], modifiers: Optional["HogQLQueryModifiers"]
+) -> Optional[ast.Expr]:
+ if modifiers is None or not modifiers.cookielessTrafficIsRegular:
+ return None
+ cookieless_expr = _property_expr(COOKIELESS_MODE_FIELD, args)
+ if cookieless_expr is None:
+ return None
+ cookieless = ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Call(
+ name="ifNull",
+ args=[ast.Call(name="toString", args=[cookieless_expr]), ast.Constant(value="")],
+ ),
+ right=ast.Constant(value="true"),
+ )
+ return ast.And(
+ exprs=[
+ cookieless,
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Call(name="ifNull", args=[args[0], ast.Constant(value="")]),
+ right=ast.Constant(value=""),
+ ),
+ ]
+ )
+
+
@frozen
class CustomRuleBranch:
"""One group of a project's rules, compiled: whether it matched and which label it reports."""
@@ -281,13 +312,14 @@ def _build_bot_array_lookup(
builtin_labels = [getattr(bot_def, attr) for bot_def in BOT_DEFINITIONS.values()]
groups = _custom_groups(modifiers)
+ cookieless = _cookieless_missing_user_agent(args, modifiers)
if not groups:
# No project rules: one pass over the built-in patterns plus the empty-user-agent sentinel.
patterns_array = _string_array([*BOT_DEFINITIONS.keys(), "^$"])
labels_array = _string_array([*builtin_labels, empty_ua_value])
index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])
- return ast.Call(
+ lookup = ast.Call(
name="if",
args=[
ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=index_call, right=ast.Constant(value=0)),
@@ -295,12 +327,14 @@ def _build_bot_array_lookup(
ast.ArrayAccess(array=labels_array, property=index_call, nullish=False),
],
)
+ if cookieless is None:
+ return lookup
+ return ast.Call(name="if", args=[cookieless, fallback, lookup])
# With project rules the checks become an ordered chain, in this order: the project's own
- # rules, then the built-ins, then the empty user agent, then the built-in IP ranges. A rule
- # someone wrote by hand says more about what they want counted than a default we shipped, so
- # it wins — that also makes the setting predictable, since a rule that matches always names
- # the event.
+ # rules, then the cookieless missing-UA fallback, then the built-ins, then the empty user
+ # agent, then the built-in IP ranges. A rule someone wrote by hand says more about what
+ # they want counted than a default we shipped, so a matching project rule always wins.
#
# It has to be a branch per group rather than one shared pattern array: multiMatchAnyIndex
# reports whichever pattern matches earliest in the string rather than earliest in the array,
@@ -310,6 +344,8 @@ def _build_bot_array_lookup(
branch = _custom_group_branch(group, args, attr)
if branch is not None:
branches.extend([branch.matched, branch.label])
+ if cookieless is not None:
+ branches.extend([cookieless, fallback])
builtin_index = ast.Call(
name="multiMatchAnyIndex", args=[safe_user_agent, _string_array(list(BOT_DEFINITIONS.keys()))]
)
@@ -402,7 +438,12 @@ def is_bot(node: ast.Call, args: list[ast.Expr], modifiers: Optional["HogQLQuery
patterns_array = _string_array([*BOT_DEFINITIONS.keys(), "^$"])
index_call = ast.Call(name="multiMatchAnyIndex", args=[safe_user_agent, patterns_array])
- conditions: list[ast.Expr] = [_matched(index_call)]
+ builtin_matched: ast.Expr = _matched(index_call)
+ cookieless = _cookieless_missing_user_agent(args, modifiers)
+ if cookieless is not None:
+ builtin_matched = ast.And(exprs=[ast.Not(expr=cookieless), builtin_matched])
+
+ conditions: list[ast.Expr] = [builtin_matched]
for group in _custom_groups(modifiers):
branch = _custom_group_branch(group, args, "name")
if branch is not None:
diff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.py
index be55cb6b63bf..dd844202a21e 100644
--- a/posthog/hogql/modifiers.py
+++ b/posthog/hogql/modifiers.py
@@ -88,6 +88,14 @@ def create_default_modifiers_for_team(
if modifiers.optimizeProjections is None:
modifiers.optimizeProjections = True
+ from products.web_analytics.backend.hogql_queries.cookieless_flag import ( # noqa: PLC0415 - keeps posthog.schema off the django.setup() import path
+ resolve_cookieless_traffic_is_regular_modifier,
+ )
+
+ modifiers.cookielessTrafficIsRegular = resolve_cookieless_traffic_is_regular_modifier(
+ team, modifiers.cookielessTrafficIsRegular
+ )
+
set_default_modifier_values(modifiers, team)
return modifiers
diff --git a/posthog/schema.py b/posthog/schema.py
index e74c724d2b0f..1d92d0e36316 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5599,6 +5599,14 @@ class HogQLQueryModifiers(BaseModel):
bounceRateDurationSeconds: float | None = None
bounceRatePageViewMode: BounceRatePageViewMode | None = None
convertToProjectTimezone: bool | None = None
+ cookielessTrafficIsRegular: bool | None = Field(
+ default=None,
+ description=(
+ "Do not treat a missing user agent as automation on cookieless events."
+ " Positive bot signals and custom project rules still apply. Resolved"
+ " server-side; not intended to be set by clients."
+ ),
+ )
customBotDefinitions: list[CustomBotRule] | None = None
customChannelTypeRules: list[CustomChannelRule] | None = None
dataWarehouseEventsModifiers: list[DataWarehouseEventsModifier] | None = None
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index 00139bdb76b1..730b05323545 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -563,7 +563,7 @@ def _get_ch_expires_at(job: "PreaggregationJob", table: LazyComputationTable) ->
return job.expires_at + timedelta(seconds=EXPIRY_BUFFER_SECONDS, days=extra_days)
-@dataclass
+@dataclass(frozen=False)
class LazyComputationQuery:
"""Normalized query information for lazy computation matching."""
@@ -571,6 +571,7 @@ class LazyComputationQuery:
table: LazyComputationTable
timezone: str = "UTC"
breakdown_fields: list[str] = field(default_factory=list)
+ cache_key_context: dict[str, str] | None = None
@dataclass
@@ -599,14 +600,15 @@ def compute_query_hash(query_info: LazyComputationQuery) -> str:
# Include timezone and breakdown fields in the hash
# Timezone matters because toStartOfDay uses the team timezone
- hash_input = json.dumps(
- {
- "query": query_str,
- "timezone": query_info.timezone,
- "breakdown_fields": sorted(query_info.breakdown_fields),
- },
- sort_keys=True,
- )
+ payload: dict[str, object] = {
+ "query": query_str,
+ "timezone": query_info.timezone,
+ "breakdown_fields": sorted(query_info.breakdown_fields),
+ }
+ # Omit absent context so callers with unchanged semantics can reuse existing jobs.
+ if query_info.cache_key_context:
+ payload["cache_key_context"] = query_info.cache_key_context
+ hash_input = json.dumps(payload, sort_keys=True)
return hashlib.sha256(hash_input.encode()).hexdigest()
@@ -1559,6 +1561,7 @@ def ensure_precomputed(
empty_result_ttl_seconds: int | None = None,
empty_result_max_age_seconds: int | None = None,
end_is_data_horizon: bool = False,
+ cache_key_context: dict[str, str] | None = None,
) -> LazyComputationResult:
"""
Ensure lazy-computed data exists for the given query and time range.
@@ -1621,9 +1624,11 @@ def ensure_precomputed(
would serve stale to themselves and never recompute.
modifiers: HogQL modifiers used when printing the INSERT's SELECT (defaults to
the team's default modifiers). NOT part of job identity — the job
- hash covers only the substituted AST — so modifiers must never
- change what the query computes, only how it executes (e.g.
- `sessionIdPushdown`, which is semantics-preserving by design).
+ hash covers the substituted AST and cache_key_context. Callers
+ must include result-changing modifier semantics in cache_key_context.
+ Execution-only modifiers such as sessionIdPushdown need no context.
+ cache_key_context: Versioned result semantics not represented in the substituted AST.
+ Use the same effective modifiers for this context and SQL generation.
end_is_data_horizon: Set True when the insert query bakes `time_range_end`
into its own filters, so it stores no rows past it. Job claims
then clamp to a historical end instead of claiming the full
@@ -1686,6 +1691,7 @@ def ensure_precomputed(
query=parsed_for_hash,
table=table,
timezone=team.timezone,
+ cache_key_context=cache_key_context,
)
def _run_manual_insert(t: Team, job: PreaggregationJob) -> int:
diff --git a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
index 964cc3ca110a..63db051ca624 100644
--- a/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/tests/test_lazy_computation_executor.py
@@ -1257,7 +1257,8 @@ class TestEnsurePrecomputed(ClickhouseTestMixin, BaseTest):
assert job.status == PreaggregationJob.Status.READY
assert job.team == self.team
- def test_reuses_existing_jobs(self):
+ @parameterized.expand([("unchanged", None), ("versioned", {"classification": "v1"})])
+ def test_reuses_existing_jobs(self, _name: str, cache_key_context: dict[str, str] | None) -> None:
# First call
first_result = ensure_precomputed(
team=self.team,
@@ -1267,17 +1268,27 @@ class TestEnsurePrecomputed(ClickhouseTestMixin, BaseTest):
)
first_job_id = first_result.job_ids[0]
- # Second call with same parameters
second_result = ensure_precomputed(
team=self.team,
insert_query=self.MANUAL_INSERT_QUERY,
time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ cache_key_context=cache_key_context,
+ modifiers=HogQLQueryModifiers(sessionIdPushdown=True),
)
- # Should reuse the existing job
assert len(second_result.job_ids) == 1
- assert second_result.job_ids[0] == first_job_id
+ assert (second_result.job_ids[0] == first_job_id) is (cache_key_context is None)
+
+ restored_result = ensure_precomputed(
+ team=self.team,
+ insert_query=self.MANUAL_INSERT_QUERY,
+ time_range_start=datetime(2024, 1, 1, tzinfo=UTC),
+ time_range_end=datetime(2024, 1, 2, tzinfo=UTC),
+ run_inserts=False,
+ )
+ assert restored_result.ready is True
+ assert restored_result.job_ids == [first_job_id]
def test_creates_jobs_for_missing_ranges(self):
# Create job for Jan 1 only
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 6cca277072a6..789b2d19a268 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -1405,6 +1405,8 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
+ cookielessTrafficIsRegular?: boolean | null
customBotDefinitions?: CustomBotRuleApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 98c222735066..6b199a1dd4cc 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1623,6 +1623,8 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
+ cookielessTrafficIsRegular?: boolean | null
customBotDefinitions?: CustomBotRuleApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 4c72ab969175..71c765975cd6 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -617,6 +617,8 @@ export interface HogQLQueryModifiersApi {
bounceRateDurationSeconds?: number | null
bounceRatePageViewMode?: BounceRatePageViewModeApi | null
convertToProjectTimezone?: boolean | null
+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
+ cookielessTrafficIsRegular?: boolean | null
customBotDefinitions?: CustomBotRuleApi[] | null
customChannelTypeRules?: CustomChannelRuleApi[] | null
dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
diff --git a/products/web_analytics/backend/hogql_queries/cookieless_flag.py b/products/web_analytics/backend/hogql_queries/cookieless_flag.py
new file mode 100644
index 000000000000..c25172b1dcfe
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/cookieless_flag.py
@@ -0,0 +1,25 @@
+from typing import TYPE_CHECKING, Optional
+
+from posthog.cloud_utils import is_cloud
+
+from products.web_analytics.backend.hogql_queries.first_pageview_flag import evaluate_team_rollout_flag
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+COOKIELESS_TRAFFIC_IS_REGULAR_FEATURE_FLAG = "cookieless-traffic-is-regular"
+
+
+def resolve_cookieless_traffic_is_regular_modifier(team: "Team", current: Optional[bool]) -> Optional[bool]:
+ if current is not None:
+ return current
+ if not is_cloud():
+ return None
+ if not evaluate_team_rollout_flag(
+ team,
+ COOKIELESS_TRAFFIC_IS_REGULAR_FEATURE_FLAG,
+ "cookieless_traffic_is_regular_flag_failed",
+ log_unresolved=False,
+ ):
+ return None
+ return True
diff --git a/products/web_analytics/backend/hogql_queries/first_pageview_flag.py b/products/web_analytics/backend/hogql_queries/first_pageview_flag.py
index c7317d91c2ab..ad97c1290c4a 100644
--- a/products/web_analytics/backend/hogql_queries/first_pageview_flag.py
+++ b/products/web_analytics/backend/hogql_queries/first_pageview_flag.py
@@ -30,7 +30,9 @@ SESSION_PROPERTY_TO_FIRST_PAGEVIEW: dict[str, WebStatsBreakdown] = {
}
-def evaluate_team_rollout_flag(team: "Team", flag_key: str, failure_log_event: str) -> bool:
+def evaluate_team_rollout_flag(
+ team: "Team", flag_key: str, failure_log_event: str, *, log_unresolved: bool = True
+) -> bool:
"""Evaluate a team-scoped rollout flag locally, failing closed on flag-service errors.
A raised exception here must never fail the query: evaluation failure degrades
@@ -61,7 +63,8 @@ def evaluate_team_rollout_flag(team: "Team", flag_key: str, failure_log_event: s
send_feature_flag_events=False,
)
if enabled is None:
- logger.warning(failure_log_event, reason="feature_enabled_returned_none", team_id=team.pk)
+ if log_unresolved:
+ logger.warning(failure_log_event, reason="feature_enabled_returned_none", team_id=team.pk)
return False
return bool(enabled)
except Exception as e:
diff --git a/products/web_analytics/backend/hogql_queries/test/test_cookieless_flag.py b/products/web_analytics/backend/hogql_queries/test/test_cookieless_flag.py
new file mode 100644
index 000000000000..a57efe267b31
--- /dev/null
+++ b/products/web_analytics/backend/hogql_queries/test/test_cookieless_flag.py
@@ -0,0 +1,45 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.web_analytics.backend.hogql_queries.cookieless_flag import resolve_cookieless_traffic_is_regular_modifier
+
+IS_CLOUD = "products.web_analytics.backend.hogql_queries.cookieless_flag.is_cloud"
+FEATURE_ENABLED = "posthoganalytics.feature_enabled"
+FLAG_LOGGER = "products.web_analytics.backend.hogql_queries.first_pageview_flag.logger"
+
+
+def _team() -> MagicMock:
+ team = MagicMock()
+ team.uuid = "team-uuid"
+ team.organization_id = "org-uuid"
+ team.id = 1
+ team.pk = 1
+ return team
+
+
+class TestResolveCookielessTrafficIsRegularModifier:
+ @parameterized.expand([("on", True, True), ("off", False, None), ("missing", None, None)])
+ def test_the_flag_decides_on_cloud_without_logging(self, _name, flag_value, expected):
+ with (
+ patch(IS_CLOUD, return_value=True),
+ patch(FEATURE_ENABLED, return_value=flag_value) as feature_enabled,
+ patch(FLAG_LOGGER) as logger,
+ ):
+ assert resolve_cookieless_traffic_is_regular_modifier(_team(), None) is expected
+
+ feature_enabled.assert_called_once()
+ logger.warning.assert_not_called()
+
+ @parameterized.expand([("opted in", True), ("opted out", False)])
+ def test_an_explicit_team_setting_skips_the_flag(self, _name, current):
+ with patch(IS_CLOUD, return_value=True), patch(FEATURE_ENABLED) as feature_enabled:
+ assert resolve_cookieless_traffic_is_regular_modifier(_team(), current) is current
+
+ feature_enabled.assert_not_called()
+
+ def test_self_hosted_never_consults_the_flag(self):
+ with patch(IS_CLOUD, return_value=False), patch(FEATURE_ENABLED) as feature_enabled:
+ assert resolve_cookieless_traffic_is_regular_modifier(_team(), None) is None
+
+ feature_enabled.assert_not_called()
diff --git a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
index 02dd79bf1a98..a74626324836 100644
--- a/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/test/test_web_lazy_precompute_common.py
@@ -16,6 +16,7 @@ from posthog.schema import (
CustomEventConversionGoal,
DateRange,
EventPropertyFilter,
+ HogQLQueryModifiers,
PersonPropertyFilter,
PropertyOperator,
SessionPropertyFilter,
@@ -628,6 +629,34 @@ class TestTeamOomPin(BaseTest):
class TestWebEnsurePrecomputed(BaseTest):
+ @parameterized.expand(
+ [
+ ("off", False, None),
+ ("on", True, "webAnalyticsEagerBaselineWarming"),
+ ("revalidation", True, REVALIDATION_TRIGGER),
+ ]
+ )
+ @mock.patch(f"{_COMMON}.ensure_precomputed")
+ def test_classification_context_matches_insert_modifiers(
+ self, _name: str, enabled: bool, trigger: str | None, mock_ensure: mock.Mock
+ ) -> None:
+ mock_ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
+ runner = WebOverviewQueryRunner(
+ team=self.team,
+ query=_overview(),
+ modifiers=HogQLQueryModifiers(cookielessTrafficIsRegular=enabled),
+ )
+ insert_modifiers = HogQLQueryModifiers(cookielessTrafficIsRegular=not enabled, sessionIdPushdown=True)
+ with tags_context(trigger=trigger):
+ web_ensure_precomputed(team=self.team, runner=runner, modifiers=insert_modifiers)
+ kwargs = mock_ensure.call_args.kwargs
+ assert kwargs["modifiers"].cookielessTrafficIsRegular is enabled
+ assert kwargs["modifiers"].sessionIdPushdown is True
+ assert insert_modifiers.cookielessTrafficIsRegular is not enabled
+ assert kwargs.get("cache_key_context") == (
+ {"traffic_classification": "cookieless-missing-ua-v1"} if enabled else None
+ )
+
def tearDown(self):
redis.get_client().delete(_oom_pin_key(self.team.pk))
super().tearDown()
@@ -1041,6 +1070,7 @@ class TestServeLiveWarmBehind(BaseTest):
runner = mock.Mock()
runner.team = self.team
runner.query = _overview()
+ runner.modifiers = HogQLQueryModifiers()
runner._test_account_filters = []
return runner
@@ -1120,6 +1150,7 @@ class TestPrecomputeShapeCapWiring(BaseTest):
runner = mock.Mock()
runner.team = self.team
runner.query = _overview()
+ runner.modifiers = HogQLQueryModifiers()
runner._test_account_filters = []
return runner
diff --git a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
index 57956b8c8588..1852fc51bc43 100644
--- a/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
+++ b/products/web_analytics/backend/hogql_queries/web_lazy_precompute_common.py
@@ -28,6 +28,7 @@ from prometheus_client import Counter
from posthog.schema import SessionsV2JoinMode, WebAnalyticsPreComputeStrategy
from posthog.hogql import ast
+from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.property import get_property_type, property_to_expr
from posthog.hogql.transforms.preaggregated_table_transformation import is_integer_timezone
@@ -445,6 +446,16 @@ def web_ensure_precomputed(*, team: Team, **kwargs: Any) -> LazyComputationResul
"""
runner = kwargs.pop("runner", None)
family = kwargs.pop("family", None)
+ modifiers = create_default_modifiers_for_team(team, kwargs.get("modifiers"))
+ if runner is not None:
+ # Pin the runner's decision so a flag refresh cannot change INSERT semantics after hashing.
+ modifiers.cookielessTrafficIsRegular = runner.modifiers.cookielessTrafficIsRegular
+ kwargs["modifiers"] = modifiers
+ if modifiers.cookielessTrafficIsRegular:
+ kwargs["cache_key_context"] = {
+ **(kwargs.get("cache_key_context") or {}),
+ "traffic_classification": "cookieless-missing-ua-v1",
+ }
background = is_background_warming_request()
forced = is_forced_refresh_request()
if "stale_while_revalidate_seconds" not in kwargs:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index acf9e0bd546f..8c16f9dabaf6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1293,6 +1293,8 @@ export namespace Schemas {
bounceRateDurationSeconds?: number | null;
bounceRatePageViewMode?: BounceRatePageViewMode | null;
convertToProjectTimezone?: boolean | null;
+ /** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
+ cookielessTrafficIsRegular?: boolean | null;
customBotDefinitions?: CustomBotRule[] | null;
customChannelTypeRules?: CustomChannelRule[] | null;
dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[] | null;