: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(flags): expose flag_evaluations in HogQL behind an org flag (#92995)
Phil Haack87ddf62fa673
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex 6e3dccc59fd9..744da202bf57 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -153,7 +153,12 @@ Doing nothing means the first affected GDPR request becomes an escalation.### Event removal with a HogQL predicate does not reach `flag_evaluations`-`compile_hogql_predicate` resolves against the events HogQL table and emits events-specific physical columns. There is no HogQL table definition for `flag_evaluations`, so the fragment cannot run against it. Requests without a predicate are swept normally; requests with one are refused if the table holds matching rows.+`compile_hogql_predicate` resolves every predicate against the events HogQL table and emits events-specific physical columns.+Its only axis of variation is legacy vs native-JSON events, so while the dag does compile one fragment per target, no target selects a different table root.+Whether a given fragment would run against `flag_evaluations` depends on the predicate and the team's modifiers: one naming only `event` or `distinct_id` would, one reaching a `mat_*` column or a property-group map would not, and nothing validates which.+The dag refuses rather than guessing.+A HogQL table definition for `flag_evaluations` does not change that, because nothing routes compilation to a table.+Requests without a predicate are swept normally; requests with one are refused if the table holds matching rows.## Producer prerequisite: person_id parity@@ -165,6 +170,12 @@ If a future producer emitted rows before person resolution, leaving `person_id`The fix would belong to the producer, not the scanner.Keeping the fork downstream of person resolution is the contract, tracked on #81002.+Write-time parity is not sufficient on its own, because a later merge moves the person the sweep looks for.+`squash_person_overrides` rewrites `person_id` on `EVENTS_TARGETS` only, so after person A merges into B the events rows carry B while the flag-evaluation rows still carry A.+A deletion of B is queued under B's uuid, so it misses those rows and they survive, with their event `properties` and their stale `person_id`, until the TTL drops the part.+The squash deletes the overrides right after applying them, so nothing can reconcile the divergence afterwards.+Extending the squash to `FLAG_EVALUATIONS` is the fix, and it belongs to `posthog/dags/person_overrides.py` rather than to this table. Tracked on #93035.+## Related, and deliberately unchanged`_fetch_stats` counts only the events tables. It feeds `AUTO_APPROVE_MAX_EVENTS`, a cost heuristic rather than a completeness claim, so a request auto-approved as small may move somewhat more rows than measured.diff --git a/posthog/clickhouse/test/test_schema.py b/posthog/clickhouse/test/test_schema.pyindex 7f8d94980f68..c2c710c00ab1 100644--- a/posthog/clickhouse/test/test_schema.py+++ b/posthog/clickhouse/test/test_schema.py@@ -6,6 +6,9 @@ from pathlib import Pathimport pytest+from posthog.hogql.database.models import DatabaseField, Table+from posthog.hogql.database.schema.flag_evaluations import FLAG_EVALUATIONS_CLICKHOUSE_TABLE, FlagEvaluationsTable+from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.kafka_engine import CONSUMER_GROUP_EVENTS_JSON_NATIVE_JSON, KAFKA_COLUMNS_WITH_PARTITIONfrom posthog.clickhouse.schema import (@@ -26,6 +29,7 @@ from posthog.models.flag_evaluations.sql import (DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL,FLAG_EVALUATIONS_KAFKA_COLUMNS,FLAG_EVALUATIONS_MV_SQL,+ FLAG_EVALUATIONS_TABLE,FLAG_EVALUATIONS_TABLE_SQL,)from posthog.settings.data_stores import SUFFIX@@ -166,6 +170,36 @@ def test_flag_evaluations_read_table_declares_every_stored_column():assert _flag_evaluations_table_columns(DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL()) == stored_columns+def _hogql_column_names(table: Table) -> set[str]:+ names: set[str] = set()+ for field in table.fields.values():+ if isinstance(field, Table):+ names |= _hogql_column_names(field)+ elif isinstance(field, DatabaseField):+ names.add(field.name)+ return names+++# Kafka metadata, deliberately not exposed to customers.+_FLAG_EVALUATIONS_COLUMNS_HIDDEN_FROM_HOGQL = {"_timestamp", "_offset", "_partition"}+++def test_flag_evaluations_hogql_table_matches_the_read_table():+ # The HogQL table spells its column names by hand, and spells the read table's name again+ # because it cannot import this module (posthog/hogql/test/test_no_django_imports.py). Both+ # copies drift silently: a query naming a column the shards lack fails only when someone runs+ # it. Asserting the difference rather than a subset means a column added to the read table has+ # to be either exposed or named here, instead of staying invisible to HogQL by default.+ declared = {+ column.split()[0] for column in _flag_evaluations_table_columns(DISTRIBUTED_FLAG_EVALUATIONS_TABLE_SQL())+ }+ exposed = _hogql_column_names(FlagEvaluationsTable())++ assert FLAG_EVALUATIONS_CLICKHOUSE_TABLE == FLAG_EVALUATIONS_TABLE+ assert declared - exposed == _FLAG_EVALUATIONS_COLUMNS_HIDDEN_FROM_HOGQL+ assert exposed - declared == set()++@pytest.fixture(autouse=True)def mock_uuid4(mocker):mock_uuid4 = mocker.patch("uuid.uuid4")diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex e6b4810fdcd2..738eff93c9cd 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -436,7 +436,8 @@ def load_deletion_request(_HOGQL_UNSWEEPABLE_REASON = ("the request carries a HogQL predicate, which only compiles against the events schema "- "(this table has no HogQL table definition, so the compiled fragment names columns it lacks). "+ "(compile_hogql_predicate resolves every predicate against the events HogQL table, varying only "+ "legacy vs native-JSON, and nothing checks the result against this table's columns). ""To proceed, re-file the request without the predicate, or narrow its events to ones this "f"table never stores. See {COVERAGE_DOC}.")diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.mdindex 6d5a8a11d668..9b63e1a31822 100644--- a/posthog/hogql/ACCESS_CONTROL.md+++ b/posthog/hogql/ACCESS_CONTROL.md@@ -203,6 +203,16 @@ Because each class restricts its own key, a table dispatched as the wrong class,The exemptions are not a statement of full coverage: `accounts.properties` and `pg_embeddings.properties` are name collisions masked nowhere by design, and `ai_events.properties` carries event properties but has no branch yet, so its blob is still returned unmasked.Covering a table means moving it out of the exemptions and into the expected mapping, so neither list can keep a stale entry.+### Typed columns that mirror a property++Masking rewrites `properties.<key>` reads and strips keys from a JSON blob. It does not reach a physical column that holds a copy of the same value.+Several catalog tables expose such columns because reading them scans far less data than digging the value out of the blob: `events` exposes `$session_id`, `$window_id`, and `$group_0`..`$group_4`; `flag_evaluations` exposes `flag_key`, `response`, `session_id`, `request_id`, and `$group_0`..`$group_4`.++`events`' mirror columns are not masked: restricting the property they mirror masks the blob read and leaves the column readable.+`flag_evaluations`' mirror columns are masked, through `_FLAG_EVALUATIONS_MIRRORED_COLUMNS` in `posthog/hogql/restricted_properties.py`, consulted via `mirrored_property_for_column()` from `ClickHousePropertyResolver.visit_field` in `posthog/hogql/transforms/clickhouse_property_resolution.py`.+That resolver rewrites a restricted mirror column to the same `Constant(value=None, type=StringType(nullable=True))` the source property lowers to, before the AST reaches the printer — so the mirror column and its source property are one AST node by the time comparisons and nullability are decided, not two independently masked spellings that could drift apart.+Covering `events`' remaining mirror columns, or a future catalog table's, means adding it to `_FLAG_EVALUATIONS_MIRRORED_COLUMNS`'s sibling mapping (or a new one `mirrored_property_for_column` dispatches to) rather than a print-time patch.+### No user: default rules applyWhen no user is present, only the team **default** rules apply instead of failing every query — see `get_restricted_properties_for_team()`.diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex b23d35e4cfe5..31529c18fecc 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -90,6 +90,7 @@ from posthog.hogql.database.schema.experiment_exposures_preaggregated import Expfrom posthog.hogql.database.schema.experiment_metric_events_preaggregated import (ExperimentMetricEventsPreaggregatedTable,)+from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTablefrom posthog.hogql.database.schema.groups_revenue_analytics import GroupsRevenueAnalyticsTablefrom posthog.hogql.database.schema.heatmaps import HeatmapsTable@@ -238,6 +239,8 @@ class HogQLDatabaseSources:is_hogql_warehouse_access_control_enabled: boolis_data_quality_enabled: boolis_billing_usage_records_enabled: bool+ # Not the flag's value: a direct-connection catalog excludes the table whatever the org has.+ include_flag_evaluations_table: bool# Userless internal contexts that must resolve every warehouse table/view; skips access controlbypass_warehouse_access_control: booldirect_connection_metadata: dict[str, Any] | None@@ -464,6 +467,9 @@ def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:# Add new tables here"logs_volume_buckets": TableNode(name="logs_volume_buckets", table=LogsVolumeBucketsTable()),"ai_events": TableNode(name="ai_events", table=AiEventsTable()),+ # Pruned per org in _build_from_sources; see is_flag_evaluations_table_enabled.+ # The flag check must stay out of this cached, process-global tree.+ "flag_evaluations": TableNode(name="flag_evaluations", table=FlagEvaluationsTable()),"trace_spans": TableNode(name="trace_spans", table=TraceSpansTable()),"trace_attributes": TableNode(name="trace_attributes", table=TraceAttributesTable()),"session_replay_features": TableNode(@@ -1552,6 +1558,9 @@ class Database(BaseModel):direct_connection_metadata=None,user_access_control=None,denied_system_table_names=set(_scoped_system_tables()) | set(_system_table_required_features()),+ # Resolving the org gate needs a feature-flag check, which is exactly the I/O this path+ # exists to avoid, so the table is pruned here as the other gated tables are.+ include_flag_evaluations_table=False,group_types=[],saved_queries=[],endpoint_saved_queries=[],@@ -1638,8 +1647,11 @@ class Database(BaseModel):# Function-local + facade-only: keeps the products off the django.setup() path.from products.data_quality.backend.facade.flags import is_data_quality_checks_enabled # noqa: PLC0415+ from products.feature_flags.backend.facade.flags import is_flag_evaluations_table_enabled # noqa: PLC0415data_quality_enabled = is_data_quality_checks_enabled(team)+ # A direct-connection catalog has no "posthog" node to hold the table.+ include_flag_evaluations_table = not is_direct_query and is_flag_evaluations_table_enabled(team)with timings.measure("database", emit_span=True):# Function-local: keeps the direct-SQL driver imports off the django.setup() path.@@ -1881,6 +1893,7 @@ class Database(BaseModel):is_data_quality_enabled=data_quality_enabled,is_billing_usage_records_enabled="*" in settings.BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDSor team.organization_id in settings.BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS,+ include_flag_evaluations_table=include_flag_evaluations_table,# Managed warehouse is a built-in project datastore and has no warehouse-object ACL surface.# Principals that skip warehouse access control by design:# - synthetic users (project-wide service tokens, bypass object-level RBAC)@@ -1954,6 +1967,14 @@ class Database(BaseModel):if posthog_node is not None:posthog_node.children.pop("billing_usage_records", None)+ # Removing the node, rather than denying the table at query time, is what keeps an org that+ # lacks the flag from learning it exists: serialize(), information_schema and get_table()+ # all read this tree. Must run before apply_schema_scope(), which snapshots the table names.+ # The "posthog" node is absent on a direct-connection catalog.+ if not sources.include_flag_evaluations_table:+ if posthog_node := database.tables.children.get("posthog"):+ posthog_node.children.pop("flag_evaluations", None)+with timings.measure("modifiers", emit_span=True):if not database._is_direct_query():events_table = database.get_table("events")diff --git a/posthog/hogql/database/schema/flag_evaluations.py b/posthog/hogql/database/schema/flag_evaluations.pynew file mode 100644index 000000000000..3e1a9422a28a--- /dev/null+++ b/posthog/hogql/database/schema/flag_evaluations.py@@ -0,0 +1,127 @@+from posthog.hogql.database.models import (+ DateTimeDatabaseField,+ FieldOrTable,+ FieldTraverser,+ IntegerDatabaseField,+ StringDatabaseField,+ StringJSONDatabaseField,+ Table,+ UUIDDatabaseField,+ VirtualTable,+)++# The physical read table is the Distributed `flag_evaluations` on the DATA nodes, defined in+# posthog/models/flag_evaluations/sql.py. That module imports django.conf, and+# posthog/hogql/test/test_no_django_imports.py imports this package with no django.setup(), so the+# name is spelled out here rather than imported.+FLAG_EVALUATIONS_CLICKHOUSE_TABLE = "flag_evaluations"+++class FlagEvaluationsPersonSubTable(VirtualTable):+ """The person column carried on the flag-evaluation row itself.++ Narrower than EventsPersonSubTable, which also declares `person_created_at` and `properties` --+ columns this table does not store, so reusing it would let `person.created_at`,+ `person.properties` and `SELECT person.*` compile into a column the shards lack.+ """++ fields: dict[str, FieldOrTable] = {+ "id": UUIDDatabaseField(name="person_id", nullable=False),+ }++ def to_printed_clickhouse(self, context):+ return FLAG_EVALUATIONS_CLICKHOUSE_TABLE++ def to_printed_hogql(self):+ return FLAG_EVALUATIONS_CLICKHOUSE_TABLE+++class FlagEvaluationsTable(Table):+ description: str = (+ "One row per feature flag evaluation, from the `$feature_flag_called` event. Rows are kept for 90 days. "+ "A project that is not sending flag-evaluation telemetry yet sees an empty table."+ )+ fields: dict[str, FieldOrTable] = {+ "uuid": UUIDDatabaseField(name="uuid", nullable=False, description="Unique identifier of this row."),+ "event": StringDatabaseField(+ name="event",+ nullable=False,+ description="Always '$feature_flag_called'.",+ ),+ "properties": StringJSONDatabaseField(+ name="properties",+ nullable=False,+ description="JSON map of the event's properties. Access nested keys with `properties.$lib` etc. "+ "Prefer the `flag_key`, `response`, `session_id`, `request_id` and `$group_0`..`$group_4` columns "+ "where they cover what you need: reading the same value out of this JSON scans far more data.",+ ),+ "timestamp": DateTimeDatabaseField(+ name="timestamp", nullable=False, description="When the flag was evaluated (client timestamp, in UTC)."+ ),+ "team_id": IntegerDatabaseField(name="team_id", nullable=False),+ "distinct_id": StringDatabaseField(+ name="distinct_id",+ nullable=False,+ description="Identifier of the user/device the flag was evaluated for.",+ ),+ "created_at": DateTimeDatabaseField(+ name="created_at",+ nullable=False,+ description="When PostHog ingested the event (server timestamp); differs from `timestamp`.",+ ),+ "inserted_at": DateTimeDatabaseField(+ name="inserted_at",+ nullable=False,+ description="When the row was written to ClickHouse; later than `created_at` by the ingestion lag.",+ ),+ "person_id": UUIDDatabaseField(+ name="person_id",+ nullable=False,+ description="The person the evaluation was attributed to when it happened. A later identify or merge "+ "does not rewrite it, so it can differ from the person `events` resolves for the same `distinct_id`.",+ ),+ "flag_key": StringDatabaseField(+ name="flag_key",+ nullable=False,+ description="Key of the flag that was evaluated; the typed copy of `properties.$feature_flag`.",+ ),+ "response": StringDatabaseField(+ 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'.",+ ),+ "session_id": StringDatabaseField(+ name="session_id", nullable=False, description="Session the evaluation happened in, if the SDK sent one."+ ),+ "request_id": StringDatabaseField(+ name="request_id",+ nullable=False,+ description="Identifier of the flag-evaluation request, shared by every flag evaluated in it.",+ ),+ # The person column on the row itself. Should not be used directly; reached via `person`.+ "poe": FlagEvaluationsPersonSubTable(),+ "person": FieldTraverser(+ chain=["poe"],+ description="The person the evaluation was attributed to when it happened. Carries the id alone: the "+ "row stores no person properties, so join to `persons` to read them.",+ ),+ # Group keys only. The row carries no group properties, so there is nothing to traverse to:+ # join to `groups` on one of these keys to read a group's current properties.+ "$group_0": StringDatabaseField(+ name="$group_0",+ nullable=False,+ description="Key of the type-0 group the evaluation was attributed to. Join to `groups` for its "+ "properties.",+ ),+ "$group_1": StringDatabaseField(name="$group_1", nullable=False, description="Key of the type-1 group."),+ "$group_2": StringDatabaseField(name="$group_2", nullable=False, description="Key of the type-2 group."),+ "$group_3": StringDatabaseField(name="$group_3", nullable=False, description="Key of the type-3 group."),+ "$group_4": StringDatabaseField(name="$group_4", nullable=False, description="Key of the type-4 group."),+ }++ def to_printed_clickhouse(self, context):+ return FLAG_EVALUATIONS_CLICKHOUSE_TABLE++ def to_printed_hogql(self):+ return FLAG_EVALUATIONS_CLICKHOUSE_TABLEdiff --git a/posthog/hogql/database/schema/owners.yaml b/posthog/hogql/database/schema/owners.yamlindex e236eceace27..76c6e9133985 100644--- a/posthog/hogql/database/schema/owners.yaml+++ b/posthog/hogql/database/schema/owners.yaml@@ -5,5 +5,7 @@ rules:owners: team-web-analytics- match: '/ai_events.py'owners: team-ai-observability+ - match: '/flag_evaluations.py'+ owners: team-feature-flags- match: '/sessions*.py'owners: team-analytics-platformdiff --git a/posthog/hogql/database/schema/test/test_flag_evaluations.py b/posthog/hogql/database/schema/test/test_flag_evaluations.pynew file mode 100644index 000000000000..1067d7fce0bf--- /dev/null+++ b/posthog/hogql/database/schema/test/test_flag_evaluations.py@@ -0,0 +1,163 @@+import json+import uuid+from datetime import UTC, datetime, timedelta++from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patch++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.client import sync_execute+from posthog.constants import AvailableFeature+from posthog.models import PropertyDefinition++from products.access_control.backend.models.property_access_control import PropertyAccessControl+from products.access_control.backend.property_access_control import PropertyAccessLevel++EVENT_PROBE = "from-event-properties"++# Compares greater than 9 as a number and less than it as a string, so the assertion tells the two+# apart rather than passing under either.+NUMERIC_PROBE = 10+++class TestFlagEvaluationsTable(ClickhouseTestMixin, BaseTest):+ def setUp(self):+ super().setUp()+ self.row_uuid = uuid.uuid4()+ self.person_id = uuid.uuid4()+ occurred_at = datetime.now(UTC) - timedelta(minutes=5)+ # 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(+ """+ INSERT INTO writable_flag_evaluations+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id)+ VALUES+ """,+ [+ (+ str(self.row_uuid),+ "$feature_flag_called",+ json.dumps(+ {+ "$feature_flag": "probe-flag",+ "$feature_flag_response": "variant-x",+ "$session_id": "sess-123",+ "$feature_flag_request_id": "req-456",+ "$group_0": "acme",+ "probe": EVENT_PROBE,+ "count": NUMERIC_PROBE,+ }+ ),+ occurred_at,+ self.team.pk,+ "probe-distinct-id",+ occurred_at,+ str(self.person_id),+ )+ ],+ )++ def _select(self, columns: str, where: str = ""):+ # 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)+ with patch(+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",+ return_value=True,+ ):+ return execute_hogql_query(+ f"SELECT {columns} FROM posthog.flag_evaluations WHERE uuid = '{self.row_uuid}'{where}",+ team=self.team,+ context=context,+ pretty=False,+ ).results++ def _restrict(self, name: str, property_type, group_type_index: int | None = None) -> None:+ self.organization.available_product_features = [+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ definition = PropertyDefinition.objects.create(+ team=self.team,+ name=name,+ property_type="String",+ type=property_type,+ group_type_index=group_type_index,+ )+ PropertyAccessControl.objects.create(+ team=self.team,+ property_definition=definition,+ access_level=PropertyAccessLevel.NONE.value,+ )++ def test_every_field_reads_its_own_physical_column(self):+ results = self._select(+ "flag_key, response, session_id, request_id, `$group_0`, person_id, person.id, properties.probe"+ )++ assert results == [+ (+ "probe-flag",+ "variant-x",+ "sess-123",+ "req-456",+ "acme",+ self.person_id,+ self.person_id,+ EVENT_PROBE,+ )+ ]++ def test_numeric_property_compares_as_a_number(self):+ # Drop this table from any of the property-type dispatches and the read stays a String, so+ # the comparison no longer answers the numeric question.+ PropertyDefinition.objects.create(+ team=self.team,+ name="count",+ property_type="Numeric",+ type=PropertyDefinition.Type.EVENT,+ )++ assert self._select("properties.count > 9") == [(True,)]++ @parameterized.expand(+ [+ ("flag_key", "flag_key", "$feature_flag", "probe-flag"),+ ("response", "response", "$feature_flag_response", "variant-x"),+ ("session_id", "session_id", "$session_id", "sess-123"),+ ("request_id", "request_id", "$feature_flag_request_id", "req-456"),+ ("group_key", "`$group_0`", "$group_0", "acme"),+ ]+ )+ def test_column_copying_a_restricted_property_reads_and_filters_as_null(+ self, _name: str, column: str, source_property: str, stored_value: str+ ):+ # These columns hold a second copy of the property, so masking the property paths alone leaves the+ # value readable here. The filter matters as much as the read: an unmasked column narrows a value+ # down through which rows come back, without ever selecting it.+ self._restrict(source_property, PropertyDefinition.Type.EVENT)++ assert self._select(column) == [(None,)]+ assert self._select("uuid", where=f" AND {column} = '{stored_value}'") == []+ # A masked read is a SQL NULL. `NULL != 'x'` and `NULL NOT IN (...)` evaluate to NULL too.+ # ClickHouse's WHERE treats NULL as false unless the printer wraps the comparison in `ifNull(...)`.+ # The row must still come back on a negated comparison, matching the equivalent `properties.<key>` read.+ assert self._select("uuid", where=f" AND {column} != '{stored_value}'") == [(self.row_uuid,)]+ assert self._select("uuid", where=f" AND {column} NOT IN ('{stored_value}')") == [(self.row_uuid,)]++ def test_restricted_property_is_hidden_from_both_read_paths(self):+ # The explicit read lowers to a NULL constant and the blob read is scrubbed by the printer.+ # Both consult the same dispatch, so a table dropped from it leaks through both.+ self._restrict("probe", PropertyDefinition.Type.EVENT)++ assert self._select("properties.probe") == [(None,)]++ blob = json.loads(self._select("properties")[0][0])++ assert "probe" not in blob+ assert blob["$feature_flag"] == "probe-flag"diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex e105555c9255..74aa3e10f63c 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -423,6 +423,28 @@ class TestDatabase(BaseTest, QueryMatchingTest):for table_name in posthog_table_names:assert serialized_database.get(table_name) is not None+ @parameterized.expand([(True,), (False,)])+ def test_flag_evaluations_visibility_follows_the_org_flag(self, flag_enabled: bool) -> None:+ with patch(+ "products.feature_flags.backend.facade.flags.is_flag_evaluations_table_enabled",+ return_value=flag_enabled,+ ):+ database = Database.create_for(team=self.team)+ context = HogQLContext(team_id=self.team.pk, database=database)+ serialized = database.serialize(context, include_hidden_posthog_tables=True)++ assert ("posthog.flag_evaluations" in database.get_posthog_table_names(include_hidden=True)) is flag_enabled+ assert ("posthog.flag_evaluations" in serialized) is flag_enabled++ # The person traverser is the part that resolves through a virtual subtable rather than+ # straight to a column, so the query exercises that rather than a bare one.+ query = "SELECT flag_key, person.id, `$group_0` FROM posthog.flag_evaluations"+ if flag_enabled:+ execute_hogql_query(query, team=self.team, pretty=False)+ else:+ with pytest.raises(QueryError, match="Unknown table"):+ execute_hogql_query(query, team=self.team, pretty=False)+def test_serialize_database_without_fields_matches_full_metadata(self):credential = DataWarehouseCredential.objects.create(access_key="blah", access_secret="blah", team=self.team)warehouse_table = DataWarehouseTable.objects.create(diff --git a/posthog/hogql/property_planner.py b/posthog/hogql/property_planner.pyindex ebf2a8d813e8..617157c6bd4d 100644--- a/posthog/hogql/property_planner.py+++ b/posthog/hogql/property_planner.py@@ -7,6 +7,7 @@ from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.models import DatabaseFieldfrom posthog.hogql.database.schema.events import EventsPersonSubTable, EventsTable+from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTablefrom posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTablefrom posthog.hogql.errors import (@@ -527,9 +528,9 @@ def _property_scope(property_type: ast.PropertyType, context: HogQLContext) -> Pexcept (HogQLNotImplementedError, QueryError, ResolutionError):return PropertyScope.UNKNOWN- if isinstance(resolved_table, EventsTable):+ if isinstance(resolved_table, EventsTable | FlagEvaluationsTable):return PropertyScope.EVENT- if isinstance(resolved_table, (EventsPersonSubTable, PersonsTable, RawPersonsTable)):+ if isinstance(resolved_table, EventsPersonSubTable | PersonsTable | RawPersonsTable):return PropertyScope.PERSONif isinstance(resolved_table, GroupsTable):return PropertyScope.GROUPdiff --git a/posthog/hogql/restricted_properties.py b/posthog/hogql/restricted_properties.pyindex 7f172bde929a..fa493b080ce4 100644--- a/posthog/hogql/restricted_properties.py+++ b/posthog/hogql/restricted_properties.py@@ -4,6 +4,7 @@ from posthog.hogql import astfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.postgres_table import PostgresTablefrom posthog.hogql.database.schema.events import EventsGroupSubTable, EventsPersonSubTable, EventsTable+from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTablefrom posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTable@@ -24,6 +25,41 @@ RESTRICTABLE_JSON_BLOB_COLUMNS: frozenset[str] = frozenset(})+# flag_evaluations columns that store a verbatim copy of an event property, mapped to the property each copies.+# The shards compute them from `properties`, so both spellings return one value, and masking only reaches the+# `properties.<key>` and whole-blob paths. Restricting the property has to mask the column by name too, or the+# column answers what those two refuse.+_FLAG_EVALUATIONS_MIRRORED_COLUMNS: dict[str, str] = {+ "flag_key": "$feature_flag",+ "response": "$feature_flag_response",+ "session_id": "$session_id",+ "request_id": "$feature_flag_request_id",+ **{f"$group_{index}": f"$group_{index}" for index in range(GROUP_TYPES_LIMIT)},+}+++def mirrored_property_for_column(table_type: ast.Type, column_name: str, context: HogQLContext) -> str | None:+ """The event property a typed column copies verbatim, or None when the column copies nothing.++ A caller that prints one of these columns must mask the read when the property is restricted, in a predicate+ as much as in a SELECT: an unmasked column lets a filter narrow down a value the same user cannot read.+ `events` exposes mirror columns of its own that nothing consults this for; see ACCESS_CONTROL.md.+ """+ if not isinstance(table_type, ast.BaseTableType):+ return None++ try:+ table = table_type.resolve_database_table(context)+ except Exception:+ # Fail-open to match restricted_property_keys_for_table_type, whose docstring explains why this is+ # unreachable today; log so a future table type that can raise does not silently unmask a column.+ logger.warning("mirrored_property_table_resolution_failed", table_type=type(table_type).__name__)+ return None++ if isinstance(table, FlagEvaluationsTable):+ return _FLAG_EVALUATIONS_MIRRORED_COLUMNS.get(column_name)+ return None+def restricted_property_keys_for_table_type(table_type: ast.Type, context: HogQLContext, *, group_type_index: int | None = None@@ -54,13 +90,14 @@ def restricted_property_keys_for_table_type(return set()# EventsPersonSubTable and EventsGroupSubTable are virtual tables over `events`, not EventsTable subclasses, but- # they carry person/group properties — match them before the EventsTable branch either way.+ # they carry person/group properties — match them before the EventsTable branch either way. flag_evaluations has+ # no counterpart for either: it stores the event blob alone, plus a person id and group keys.if isinstance(table, EventsPersonSubTable):prop_def_type = PropertyDefinition.Type.PERSONelif isinstance(table, EventsGroupSubTable):prop_def_type = PropertyDefinition.Type.GROUPgroup_type_index = table.group_index- elif isinstance(table, EventsTable):+ elif isinstance(table, EventsTable | FlagEvaluationsTable):prop_def_type = PropertyDefinition.Type.EVENTelif isinstance(table, (PersonsTable, RawPersonsTable)):prop_def_type = PropertyDefinition.Type.PERSONdiff --git a/posthog/hogql/test/test_restricted_properties.py b/posthog/hogql/test/test_restricted_properties.pyindex c591f7e9da09..4feb46b15f87 100644--- a/posthog/hogql/test/test_restricted_properties.py+++ b/posthog/hogql/test/test_restricted_properties.py@@ -30,6 +30,9 @@ _MASKED_BLOBS: dict[str, frozenset[str]] = {f"events.group{index}_properties (EventsGroupSubTable)": frozenset({_GROUP_KEYS[index]})for index in range(GROUP_TYPES_LIMIT)},+ # The one blob flag_evaluations stores. It carries event properties, so it masks the event class alone:+ # the table keeps no person or group blob to mask, only a person id and the group keys.+ "flag_evaluations.properties (FlagEvaluationsTable)": frozenset({_EVENT_KEY}),"persons.properties (PersonsTable)": frozenset({_PERSON_KEY}),"raw_persons.properties (RawPersonsTable)": frozenset({_PERSON_KEY}),# The groups tables hold every group type, with the index in a column rather than in the blob's name, sodiff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.pyindex 2a989658ec62..de78a22f156f 100644--- a/posthog/hogql/transforms/clickhouse_property_resolution.py+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py@@ -32,7 +32,7 @@ from posthog.hogql.errors import QueryErrorfrom posthog.hogql.functions.mapping import HOGQL_COMPARISON_MAPPINGfrom posthog.hogql.printer.base import resolve_field_typefrom posthog.hogql.printer.clickhouse import AI_BLOOM_FILTER_PROPERTIES, COLUMNS_WITH_HACKY_OPTIMIZED_NULL_HANDLING-from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type+from posthog.hogql.restricted_properties import mirrored_property_for_column, restricted_property_keys_for_table_typefrom posthog.hogql.type_system import (ComparisonCompatibility,comparison_compatibility,@@ -892,6 +892,31 @@ class ClickHousePropertyResolver(CloningVisitor):return substitutedreturn super().visit_property_access(node)+ def visit_field(self, node: ast.Field) -> ast.Expr:+ if (+ self.context.restricted_properties+ and isinstance(node.type, ast.FieldType)+ and (masked := self._masked_mirrored_column(node.type)) is not None+ ):+ return masked+ return super().visit_field(node)++ def _masked_mirrored_column(self, field_type: ast.FieldType) -> ast.Constant | None:+ """The NULL constant a restricted mirror column reads as, or None if it is unrestricted.++ Must match what `_substitute_value_read` builds for the source property, so the mirror column and+ its source property become the same AST node and agree on nullability and comparison printing.+ """+ resolved_field = field_type.resolve_database_field(self.context)+ if not isinstance(resolved_field, DatabaseField):+ return None+ source_property = mirrored_property_for_column(field_type.table_type, resolved_field.name, self.context)+ if source_property is None:+ return None+ if source_property not in restricted_property_keys_for_table_type(field_type.table_type, self.context):+ return None+ return ast.Constant(value=None, type=ast.StringType(nullable=True))+# --- comparison / call rewrites ---def visit_call(self, node: ast.Call) -> ast.Expr:diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex 06569414d1fc..d650324a656f 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -12,6 +12,7 @@ from posthog.hogql.database.schema.events import (EventsPersonSubTable,EventsTable,)+from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTablefrom posthog.hogql.database.schema.groups import GroupsTablefrom posthog.hogql.database.schema.persons import PersonsTable, RawPersonsTablefrom posthog.hogql.errors import QueryError@@ -118,7 +119,7 @@ class PropertyFinder(TraversingVisitor):self.person_properties.add(property_name)elif isinstance(resolved_table, EventsGroupSubTable):pass # group properties are handled above via GroupsTable- elif isinstance(resolved_table, EventsTable):+ elif isinstance(resolved_table, EventsTable | FlagEvaluationsTable):self.event_properties.add(property_name)def visit_field(self, node: ast.Field):@@ -709,7 +710,7 @@ class PropertySwapper(CloningVisitor):if isinstance(resolved_table, EventsPersonSubTable):if property_name in self.person_properties:return self._convert_string_property_to_type(node, "person", property_name)- elif isinstance(resolved_table, EventsTable):+ elif isinstance(resolved_table, EventsTable | FlagEvaluationsTable):if property_name in self.event_properties:return self._convert_string_property_to_type(node, "event", property_name)if isinstance(type, ast.PropertyType) and type.field_type.name == "person_properties" and len(type.chain) == 1:diff --git a/posthog/models/deletion_targets.py b/posthog/models/deletion_targets.pyindex 656a99e42fae..a491f12c54bb 100644--- a/posthog/models/deletion_targets.py+++ b/posthog/models/deletion_targets.py@@ -93,9 +93,11 @@ class DeletionTarget:node_role: NodeRole = NodeRole.DATA# Guarded on system.tables: the table sits behind a migration that may not have run everywhere.optional: bool = False- # The schema a HogQL predicate compiles against here, None where no HogQL table definition- # exists. A compiled fragment names physical columns (mat_*, the property-group maps, or JSON- # subcolumns), so it only runs against the schema it was compiled for.+ # Which events-schema variant compile_hogql_predicate emits for this table, None where no+ # variant is known to run against its physical columns. Every predicate resolves against the+ # events HogQL table, and the only choice is legacy versus native-JSON. A fragment names+ # physical columns (mat_*, the property-group maps, or JSON subcolumns), so it only runs+ # against the schema it was compiled for.hogql_schema: HogQLSchema | None = None# properties/person_properties can be rewritten in place. True needs both halves: the property# columns are DEFAULT-kind (assignable by ALTER UPDATE, as materialize() mints them), and thediff --git a/products/feature_flags/backend/facade/flags.py b/products/feature_flags/backend/facade/flags.pynew file mode 100644index 000000000000..c8646152d118--- /dev/null+++ b/products/feature_flags/backend/facade/flags.py@@ -0,0 +1,40 @@+"""Feature-flag gates for this product, kept light so core code can import them without pulling+the facade's heavier logic surface onto its import path.+"""++from typing import TYPE_CHECKING++from django.conf import settings++from posthog.ph_client import feature_enabled_or_false++if TYPE_CHECKING:+ from posthog.models.team import Team++FLAG_EVALUATIONS_HOGQL_TABLE_FEATURE_FLAG = "flag-evaluations-hogql-table"+++def is_flag_evaluations_table_enabled(team: "Team") -> bool:+ """Gate every surface that exposes `posthog.flag_evaluations` through here.++ Cloud-only for now: a self-hosted production instance reads false. Local dev and+ end-to-end tests are the exception and read true.+ """+ # The flag is evaluated against PostHog's own analytics project, which a local or end-to-end+ # environment has no membership in. Evaluating it there would hide the table from both, so+ # return True to keep it visible in dev and E2E.+ if settings.DEBUG or settings.E2E_TESTING:+ return True+ return feature_enabled_or_false(+ FLAG_EVALUATIONS_HOGQL_TABLE_FEATURE_FLAG,+ str(team.organization_id),+ groups={"organization": str(team.organization_id)},+ group_properties={"organization": {"id": str(team.organization_id)}},+ # The HogQL database is built on the query hot path, and a local-evaluation miss otherwise+ # blocks it on a synchronous request to /flags. Failing closed hides the table instead.+ # This constrains how the flag may be configured: target organizations by the id sent+ # above, because a condition on any property not sent here cannot evaluate locally and so+ # reads false for everyone.+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )