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(flags): read flag_evaluations response sentinels as NULL (#117930)

Phil Haackf5f9ceb46c14
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
index 17d90ddd088b..49ad1021b3e0 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.test.ts
@@ -181,15 +181,11 @@ describe('featureFlagUsageQueries', () => {
})
it.each(flagEvaluationsBuilders)(
- '%s puts JSON-null and missing responses in one bucket with the events-mode label',
+ '%s labels the NULL response bucket with the events-mode label',
(_name, build) => {
- // The raw column holds 'null' for one case and '' for the other, so grouping on it shows two
- // series with their own labels where the events mode shows one.
const { query } = build(personFlagOptions)
- expect(query.source.query).toContain(
- `if(response IN ('', 'null'), '${BREAKDOWN_NULL_DISPLAY}', response) AS`
- )
+ expect(query.source.query).toContain(`ifNull(response, '${BREAKDOWN_NULL_DISPLAY}') AS`)
}
)
diff --git a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
index 6d84c9dfe13f..796763091a68 100644
--- a/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagUsageQueries.ts
@@ -201,12 +201,12 @@ function enrichedSeries(event: '$feature_view' | '$feature_interaction', seriesL
]
}
-// The table stores a JSON-null $feature_flag_response as 'null' and a missing one as ''. The events-mode
-// breakdown puts both cases in one bucket labelled BREAKDOWN_NULL_DISPLAY, so these charts do the same.
+// The table reads a null or missing $feature_flag_response as NULL. The events-mode breakdown labels that
+// bucket BREAKDOWN_NULL_DISPLAY, so these charts do the same.
// The label is in the query because the SQL line chart names a NULL series "[No value]" and the SQL
// table draws a NULL cell as a dash. A variant whose key equals the label merges into this bucket. The flag
// editor rejects that key, but the API accepts it.
-const FLAG_EVALUATIONS_VARIANT = `if(response IN ('', 'null'), ${escapeHogQLString(BREAKDOWN_NULL_DISPLAY)}, response)`
+const FLAG_EVALUATIONS_VARIANT = `ifNull(response, ${escapeHogQLString(BREAKDOWN_NULL_DISPLAY)})`
/** Pulls a range back inside the retention window, where it cannot quietly show fewer rows than the events table. */
export function clampToFlagEvaluationsRetention(dateRange: DateRange): DateRange {
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
index 1e8c07ffe8e0..002ed9bacc31 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx
@@ -996,6 +996,7 @@ describe('ActionFilterRow', () => {
type: PropertyFilterType.Event,
},
{ key: '$feature_flag_response', operator: PropertyOperator.IsSet, type: PropertyFilterType.Event },
+ { key: '$feature_flag', operator: PropertyOperator.IsNotSet, type: PropertyFilterType.Event },
{
key: '$browser',
value: 'Chrome',
@@ -1038,8 +1039,13 @@ describe('ActionFilterRow', () => {
},
{
key: 'response',
- value: ['', 'null'],
- operator: PropertyOperator.NotIn,
+ operator: PropertyOperator.IsSet,
+ type: PropertyFilterType.DataWarehouse,
+ },
+ {
+ key: 'flag_key',
+ value: [''],
+ operator: PropertyOperator.In,
type: PropertyFilterType.DataWarehouse,
},
{ key: "properties.$lib = 'web'", type: PropertyFilterType.HogQL },
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
index dacf52677d9d..78ee92b70663 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/flagCallsSeries.ts
@@ -144,12 +144,6 @@ const FLAG_CALLS_COLUMN_BY_EVENT_PROPERTY: Record<string, string> = {
$feature_flag_response: 'response',
}
-// An event read turns a missing property into NULL. The table stores a missing flag key as '' and a missing response as '' or 'null'.
-const FLAG_CALLS_UNSET_VALUES_BY_COLUMN: Record<string, string[]> = {
- flag_key: [''],
- response: ['', 'null'],
-}
-
/** Rewrites an event series' flag filters onto the flag_evaluations columns and keeps its SQL filters. */
export function flagCallsFiltersFromEventFilters(properties: AnyPropertyFilter[] | undefined): AnyPropertyFilter[] {
return (properties ?? []).flatMap((property): AnyPropertyFilter[] => {
@@ -163,12 +157,16 @@ export function flagCallsFiltersFromEventFilters(properties: AnyPropertyFilter[]
if (!column) {
return []
}
- const checksSet = property.operator === PropertyOperator.IsSet
- const checksNotSet = property.operator === PropertyOperator.IsNotSet
+ // `flag_key` stores a missing key as '' rather than NULL, so its set checks compare against ''.
+ let { value, operator } = property
+ if (column === 'flag_key' && (operator === PropertyOperator.IsSet || operator === PropertyOperator.IsNotSet)) {
+ value = ['']
+ operator = operator === PropertyOperator.IsSet ? PropertyOperator.NotIn : PropertyOperator.In
+ }
const filter: DataWarehousePropertyFilter = {
key: column,
- value: checksSet || checksNotSet ? FLAG_CALLS_UNSET_VALUES_BY_COLUMN[column] : property.value,
- operator: checksSet ? PropertyOperator.NotIn : checksNotSet ? PropertyOperator.In : property.operator,
+ value,
+ operator,
type: PropertyFilterType.DataWarehouse,
}
return [filter]
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index 6bc08416a890..64777bc540b0 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -223,6 +223,7 @@ Several catalog tables expose such columns because reading them scans far less d
`events`' mirror columns are not masked: restricting the property they mirror masks the blob read and leaves the column readable.
`flag_evaluations` and `ai_events` mirror columns are masked through `mirrored_property_for_column()` in `posthog/hogql/restricted_properties.py`, consulted by `ClickHousePropertyResolver` in `posthog/hogql/transforms/clickhouse_property_resolution.py`.
+The mapping is keyed by the stored column name, not the HogQL field name, so an expression field that reads a mirror column masks too: `flag_evaluations.response` reads the stored `response` column through `nullIf`, and the hidden `flag_evaluation_response` reads it bare, and both mask.
For AI columns, `AI_PROPERTY_TO_COLUMN` in `posthog/hogql/database/schema/ai_events.py` is shared with the query rewriter.
One rule for `$ai_input` masks both `events.properties.$ai_input` and `ai_events.input`, including nested reads such as `input[1].content`.
The same rule applies when a filter or an aggregate reads the column.
diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.py
index 630dccb03850..1813d214f56b 100644
--- a/posthog/hogql/ast.py
+++ b/posthog/hogql/ast.py
@@ -1036,7 +1036,7 @@ class Lambda(Expr):
expr: Expr | Block
-@dataclass(kw_only=True, slots=True)
+@dataclass(kw_only=True, slots=True, frozen=False)
class Constant(Expr):
value: Any
# When True, the SQL printer routes this constant through
@@ -1044,11 +1044,10 @@ class Constant(Expr):
# ``_sensitive`` suffix and ``substitute_params_for_display`` redacts the
# value to ``[HIDDEN]``
is_sensitive: bool | None = None
- # Internal ClickHouse-printer hint, not part of the logical AST. Set True only by the physical pass, only for its
- # fixed scrubbing sentinels (the nullIf ''/'null' literals, the quote-trim regex, the 'true'/'false' the property
- # group stores booleans as), to render them inline instead of as a bound parameter — matching the inline string the
- # `json_extract_trim_quotes` helper emits. The printer enforces a fixed allowlist (`INLINE_SENTINEL_LITERALS`), so it
- # can never inline arbitrary text. Unset (None) by default, like `type`, so the "skip None" AST serializers (Hog
+ # Internal ClickHouse-printer hint. Set True only on fixed scrubbing sentinels (the nullIf ''/'null' literals, the
+ # quote-trim regex, the 'true'/'false' the property group stores booleans as), to render them inline instead of as a
+ # bound parameter — matching the inline string the `json_extract_trim_quotes` helper emits. The printer enforces a
+ # fixed allowlist (`INLINE_SENTINEL_LITERALS`), so it can never inline arbitrary text. Unset (None) by default, like `type`, so the "skip None" AST serializers (Hog
# compilers, `pretty_dataclasses` snapshots) leave it out.
inline_sentinel: bool | None = None
diff --git a/posthog/hogql/database/schema/flag_evaluations.py b/posthog/hogql/database/schema/flag_evaluations.py
index 36b37c31e71f..a47d92164f00 100644
--- a/posthog/hogql/database/schema/flag_evaluations.py
+++ b/posthog/hogql/database/schema/flag_evaluations.py
@@ -16,6 +16,7 @@ from posthog.hogql.database.models import (
VirtualTable,
)
from posthog.hogql.database.schema.person_distinct_id_overrides import PersonDistinctIdOverridesTable
+from posthog.hogql.database.schema.util.null_sentinels import null_if_sentinels
from posthog.hogql.database.schema.util.uuid import uuid_string_expr_to_uint128_expr
from posthog.hogql.parser import parse_expr
@@ -138,11 +139,17 @@ class FlagEvaluationsTable(Table):
nullable=False,
description="Key of the flag that was evaluated; the typed copy of `properties.$feature_flag`.",
),
- "response": StringDatabaseField(
+ # `flag_key` is in the sort key, and `session_id` and `request_id` carry bloom filters. They stay bare because
+ # a `nullIf` wrap stops a filter from using either. `$group_0`..`$group_4` keep '' as the events columns do.
+ "flag_evaluation_response": StringDatabaseField(name="response", nullable=False, hidden=True),
+ "response": ExpressionField(
name="response",
- nullable=False,
- description="What the flag returned: 'true', 'false', or a variant key. A flag that returned JSON null "
- "stores the literal string 'null'.",
+ expr=null_if_sentinels(ast.Field(chain=["flag_evaluation_response"])),
+ isolate_scope=True,
+ nullable=True,
+ description="What the flag returned: 'true', 'false', or a variant key. NULL when the flag returned null "
+ "or the SDK sent no response, as on events. A variant named 'null' also reads NULL. "
+ "`JSONHas(properties, '$feature_flag_response')` tells a null response from a missing one.",
),
"session_id": StringDatabaseField(
name="session_id", nullable=False, description="Session the evaluation happened in, if the SDK sent one."
diff --git a/posthog/hogql/database/schema/test/test_flag_evaluations.py b/posthog/hogql/database/schema/test/test_flag_evaluations.py
index ca51e0347398..b455811478c8 100644
--- a/posthog/hogql/database/schema/test/test_flag_evaluations.py
+++ b/posthog/hogql/database/schema/test/test_flag_evaluations.py
@@ -8,6 +8,7 @@ from unittest.mock import patch
from parameterized import parameterized
from posthog.schema import (
+ DataWarehousePropertyFilter,
ElementPropertyFilter,
EventPropertyFilter,
GroupPropertyFilter,
@@ -98,6 +99,20 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
self.row_uuid = uuid.uuid4()
self.person_id = uuid.uuid4()
self.occurred_at = datetime.now(UTC) - timedelta(minutes=5)
+ self._insert_row(
+ self.row_uuid,
+ {
+ "$feature_flag": "probe-flag",
+ "$feature_flag_response": "variant-x",
+ "$session_id": SESSION_ID,
+ "$feature_flag_request_id": "req-456",
+ "$group_0": "acme",
+ "probe": EVENT_PROBE,
+ "count": NUMERIC_PROBE,
+ },
+ )
+
+ def _insert_row(self, row_uuid: uuid.UUID, properties: dict[str, str | int | None]) -> None:
# The nine typed columns are DEFAULT-computed from `properties` on the sharded table, so a
# producer cannot write them and this insert must not name them.
sync_execute(
@@ -108,19 +123,9 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
""",
[
(
- str(self.row_uuid),
+ str(row_uuid),
"$feature_flag_called",
- json.dumps(
- {
- "$feature_flag": "probe-flag",
- "$feature_flag_response": "variant-x",
- "$session_id": SESSION_ID,
- "$feature_flag_request_id": "req-456",
- "$group_0": "acme",
- "probe": EVENT_PROBE,
- "count": NUMERIC_PROBE,
- }
- ),
+ json.dumps(properties),
self.occurred_at,
self.team.pk,
"probe-distinct-id",
@@ -131,7 +136,16 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
],
)
- def _execute(self, columns: str, where: str = "", source: str = "posthog.flag_evaluations"):
+ def _execute(
+ self,
+ columns: str,
+ where: str = "",
+ source: str = "posthog.flag_evaluations",
+ *,
+ row_uuids: tuple[uuid.UUID, ...] = (),
+ placeholders: dict[str, ast.Expr] | None = None,
+ ):
+ uuids = ", ".join(f"'{row_uuid}'" for row_uuid in row_uuids or (self.row_uuid,))
# settings.DEBUG is False under the test runner, so the org gate fail-closes and prunes the
# table. test_database.py covers the gate itself; here it only has to be out of the way.
context = HogQLContext(team_id=self.team.pk, team=self.team, user=self.user, enable_select_queries=True)
@@ -140,14 +154,22 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
return_value=True,
):
return execute_hogql_query(
- f"SELECT {columns} FROM {source} WHERE uuid = '{self.row_uuid}'{where}",
+ f"SELECT {columns} FROM {source} WHERE uuid IN ({uuids}){where}",
team=self.team,
+ placeholders=placeholders,
context=context,
pretty=False,
)
- def _select(self, columns: str, where: str = ""):
- return self._execute(columns, where).results
+ def _select(
+ self,
+ columns: str,
+ where: str = "",
+ *,
+ row_uuids: tuple[uuid.UUID, ...] = (),
+ placeholders: dict[str, ast.Expr] | None = None,
+ ):
+ return self._execute(columns, where, row_uuids=row_uuids, placeholders=placeholders).results
def _override(self, person_id: uuid.UUID, version: int, is_deleted: bool = False) -> None:
sync_execute(
@@ -220,6 +242,35 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
assert rows == [({"quote": 'a"b', "keep": "yes"}, {"email": "[email protected]"})]
+ @parameterized.expand(
+ [
+ ("json_null", {"$feature_flag_response": None}),
+ ("missing", {}),
+ ("empty_string", {"$feature_flag_response": ""}),
+ ("null_string", {"$feature_flag_response": "null"}),
+ ]
+ )
+ def test_null_or_missing_response_reads_and_filters_as_null(
+ self, _name: str, response_property: dict[str, str | None]
+ ):
+ row_uuid = uuid.uuid4()
+ self._insert_row(row_uuid, {"$feature_flag": "probe-flag", **response_property})
+ is_set, is_not_set = (
+ property_to_expr(DataWarehousePropertyFilter(key="response", operator=operator), self.team)
+ for operator in (PropertyOperator.IS_SET, PropertyOperator.IS_NOT_SET)
+ )
+
+ both_rows = (row_uuid, self.row_uuid)
+
+ assert self._select("response", row_uuids=(row_uuid,)) == [(None,)]
+ assert self._select("uuid", " AND {filter}", row_uuids=both_rows, placeholders={"filter": is_not_set}) == [
+ (row_uuid,)
+ ]
+ assert self._select("uuid", " AND {filter}", row_uuids=both_rows, placeholders={"filter": is_set}) == [
+ (self.row_uuid,)
+ ]
+ assert self._select("uuid", " AND response != 'variant-x'", row_uuids=(row_uuid,)) == [(row_uuid,)]
+
def test_person_id_follows_a_later_merge(self):
# Ingestion never rewrites the person on the row, so only the read can correct it. Drop the
# override join and `uniq(person_id)` counts the pre-merge and the post-merge person as two
@@ -274,10 +325,26 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
columns = response.columns or []
assert "flag_evaluation_person_id" not in columns
+ assert "flag_evaluation_response" not in columns
assert response.results[0][columns.index("person_id")] == merged_person_id
# The fields copied from events exist only so that filters resolve. They must not reach the expansion.
assert not [column for column in columns if column.startswith(("$virt_", "elements_chain", "$session_id"))]
+ def test_catalog_lists_response_as_nullable(self):
+ # Schema discovery reads the declared nullability, not the expression's type.
+ with patch(
+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",
+ return_value=True,
+ ):
+ results = execute_hogql_query(
+ "SELECT column_name, is_nullable FROM system.information_schema.columns "
+ "WHERE table_name = 'posthog.flag_evaluations' AND column_name IN ('response', 'flag_key')",
+ team=self.team,
+ user=self.user,
+ ).results
+
+ assert {name: bool(nullable) for name, nullable in results or []} == {"response": True, "flag_key": False}
+
@parameterized.expand(
[
("event", "properties", "count", PropertyDefinition.Type.EVENT),
@@ -300,6 +367,7 @@ class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):
[
("flag_key", "flag_key", "$feature_flag", "probe-flag"),
("response", "response", "$feature_flag_response", "variant-x"),
+ ("raw_response", "flag_evaluation_response", "$feature_flag_response", "variant-x"),
("session_id", "session_id", "$session_id", SESSION_ID),
("request_id", "request_id", "$feature_flag_request_id", "req-456"),
("group_key", "`$group_0`", "$group_0", "acme"),
diff --git a/posthog/hogql/database/schema/util/null_sentinels.py b/posthog/hogql/database/schema/util/null_sentinels.py
new file mode 100644
index 000000000000..82fc26759721
--- /dev/null
+++ b/posthog/hogql/database/schema/util/null_sentinels.py
@@ -0,0 +1,16 @@
+from collections.abc import Sequence
+
+from posthog.hogql import ast
+
+# In non-nullable materialized columns these stored strings are treated as NULL.
+MAT_COL_NULL_SENTINELS: tuple[str, ...] = ("", "null")
+
+
+def null_if_sentinels(expr: ast.Expr, sentinels: Sequence[str] = MAT_COL_NULL_SENTINELS) -> ast.Expr:
+ """`expr` with each of `sentinels` read as NULL, the way HogQL reads a non-nullable materialized column.
+
+ The sentinels render inline, so the printed SQL matches the JSON-extract read of the same property.
+ """
+ for sentinel in sentinels:
+ expr = ast.Call(name="nullIf", args=[expr, ast.Constant(value=sentinel, inline_sentinel=True)])
+ return expr
diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.py
index 7eaf7ab71389..617a535a4b83 100644
--- a/posthog/hogql/transforms/clickhouse_property_resolution.py
+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py
@@ -37,6 +37,7 @@ from posthog.hogql.constants import (
)
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.models import DatabaseField, MapStringDatabaseField, StringJSONDatabaseField
+from posthog.hogql.database.schema.util.null_sentinels import MAT_COL_NULL_SENTINELS, null_if_sentinels
from posthog.hogql.errors import QueryError
from posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPING
from posthog.hogql.printer.base import resolve_field_type
@@ -71,8 +72,6 @@ from posthog.clickhouse.property_groups import property_groups
from posthog.clickhouse.workload import Workload
from posthog.schema_enums import MaterializationMode, PropertyGroupsMode
-# In non-nullable materialized columns these stored strings are treated as NULL.
-MAT_COL_NULL_SENTINELS = ["", "null"]
MAX_MATERIALIZED_LIKE_PATTERN_LENGTH = 16 * 1024
# Leave the legacy $ai_* bloom-filter columns to the printer: its comparison code already keeps them index-eligible
@@ -396,10 +395,9 @@ def _materialized_head_expr(
return column_field
# Non-nullable materialized column: scrub the '' / 'null' string sentinels back to NULL.
- scrubbed_empty = ast.Call(name="nullIf", args=[column_field, _sentinel("")])
if materialization_mode == MaterializationMode.LEGACY_NULL_AS_STRING:
- return scrubbed_empty
- return ast.Call(name="nullIf", args=[scrubbed_empty, _sentinel("null")])
+ return null_if_sentinels(column_field, ("",))
+ return null_if_sentinels(column_field)
def _json_subcolumn_access(
@@ -2709,7 +2707,7 @@ class ClickHousePropertyResolver(CloningVisitor):
return None
# Bail if a value could collide with a stored NULL sentinel.
- null_sentinels = [""] if prop.source.is_nullable else MAT_COL_NULL_SENTINELS
+ null_sentinels = ("",) if prop.source.is_nullable else MAT_COL_NULL_SENTINELS
if any(v in null_sentinels for v in values):
return None
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 49c2b329e8e7..13156a921be3 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1813,7 +1813,7 @@ def _create_flag_evaluations(
distinct_id: str = "evaluator",
person_id: uuid.UUID | str | None = None,
person_created_at: dt.datetime | None = None,
- response: str | bool = True,
+ response: str | bool | None = True,
properties: dict[str, Any] | None = None,
person_properties: dict[str, str] | None = None,
) -> None:
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 561ca39f7352..28ff6c34ea7e 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1263,7 +1263,7 @@
9 products/signals/backend/temporal/grouping.py
10 products/signals/backend/temporal/summary.py
10 products/tasks/backend/temporal/process_task/activities/provision_sandbox.py
-104 posthog/hogql/ast.py
+102 posthog/hogql/ast.py
12 ee/clickhouse/materialized_columns/columns.py
14 products/marketing_analytics/backend/hogql_queries/adapters/base.py
14 products/subscriptions/backend/temporal/types.py
diff --git a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
index 275e6789a6d1..c361f6094409 100644
--- a/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
+++ b/products/product_analytics/backend/tests/test_flag_evaluations_insight_series.py
@@ -48,6 +48,7 @@ from posthog.schema import (
from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_HOGQL_TABLE
from posthog.hogql_queries.query_runner import QueryRunner
+from posthog.hogql_queries.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL
from posthog.models.group.util import create_group
from posthog.models.person import Person
@@ -156,6 +157,7 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
alice = self.alice = _create_person(team_id=self.team.pk, distinct_ids=["alice"], created_at=IN_DATE_RANGE)
bob = _create_person(team_id=self.team.pk, distinct_ids=["bob"], created_at=IN_DATE_RANGE)
alice_2 = _create_person(team_id=self.team.pk, distinct_ids=["alice-2"], created_at=IN_DATE_RANGE)
+ self.bob_uuid = bob.uuid
for distinct_id, person, flag_key, response, occurred_at, properties in [
(
"alice",
@@ -232,12 +234,21 @@ class TestFlagEvaluationsInsightSeries(ClickhouseTestMixin, BaseTest):
@parameterized.expand(
[
- ("total_calls", BaseMathType.TOTAL, {"test": 3, "control": 1}),
- ("unique_users", BaseMathType.DAU, {"test": 1, "control": 1}),
- ("unique_sessions", BaseMathType.UNIQUE_SESSION, {"test": 2, "control": 1}),
+ ("total_calls", BaseMathType.TOTAL, {"test": 3, "control": 1, BREAKDOWN_NULL_STRING_LABEL: 1}),
+ ("unique_users", BaseMathType.DAU, {"test": 1, "control": 1, BREAKDOWN_NULL_STRING_LABEL: 1}),
+ ("unique_sessions", BaseMathType.UNIQUE_SESSION, {"test": 2, "control": 1, BREAKDOWN_NULL_STRING_LABEL: 1}),
]
)
def test_trend_by_variant(self, _name: str, math: BaseMathType, expected: dict[str, int]):
+ _create_flag_evaluations(
+ self.team.pk,
+ "probe-flag",
+ timestamp=datetime(2025, 1, 8, 14, tzinfo=UTC),
+ distinct_id="bob",
+ person_id=self.bob_uuid,
+ response=None,
+ properties={"$session_id": "s-bob", "$group_0": "org-b"},
+ )
query = TrendsQuery(
dateRange=DATE_RANGE,
interval=IntervalType.DAY,