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.

feat(hogql): add query-time geoip dict fallback behind modifier (#63191)

Robbied3d568b116d1
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index b6281ed4b0cb..d9977b49567b 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -53,6 +53,11 @@ class HogQLContext:
values: dict = field(default_factory=dict)
# Are we small part of a non-HogQL query? If so, use custom syntax for accessed person properties.
within_non_hogql_query: bool = False
+ # Temporary (June 2026 MaxMind incident): the geoip dict fallback decision, evaluated exactly once per query in
+ # `prepare_ast_for_printing` so the transform and the printer's `_lookupGeoip*` gate can never disagree mid-query
+ # (the underlying probe is a background-refreshed cache that may flip between evaluations). Remove with the
+ # transform in posthog/hogql/transforms/geoip_dict_fallback.py.
+ geoip_dict_fallback_enabled: bool = False
# Enable full SELECT queries and subqueries in ClickHouse
enable_select_queries: bool = False
# Do we apply a limit of MAX_SELECT_RETURNED_ROWS=10000 to the topmost select query?
diff --git a/posthog/hogql/functions/posthog.py b/posthog/hogql/functions/posthog.py
index 5124d65579e3..824a192051d0 100644
--- a/posthog/hogql/functions/posthog.py
+++ b/posthog/hogql/functions/posthog.py
@@ -26,6 +26,10 @@ HOGQL_POSTHOG_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
signatures=[((StringType(),), ArrayType(item_type=IntegerType()))],
),
"embedText": HogQLFunctionMeta("embedText", 1, 2),
+ # Temporary (June 2026 MaxMind incident: https://posthog.slack.com/archives/C0B9DDSCTF1): geoip lookups against the city_postal_ip_trie ClickHouse dictionary,
+ # used by posthog/hogql/transforms/geoip_dict_fallback.py and rendered in the ClickHouse printer. Remove with it.
+ "_lookupGeoipCityName": HogQLFunctionMeta("_lookupGeoipCityName", 1, 1),
+ "_lookupGeoipPostalCode": HogQLFunctionMeta("_lookupGeoipPostalCode", 1, 1),
# posthog/models/channel_type/sql.py and posthog/hogql/database/schema/channel_type.py
"lookupDomainType": HogQLFunctionMeta("lookupDomainType", 1, 1),
"lookupPaidSourceType": HogQLFunctionMeta("lookupPaidSourceType", 1, 1),
diff --git a/posthog/hogql/functions/udfs.py b/posthog/hogql/functions/udfs.py
index 3b0d767c8dc5..368509dea093 100644
--- a/posthog/hogql/functions/udfs.py
+++ b/posthog/hogql/functions/udfs.py
@@ -28,9 +28,14 @@ UDFS: dict[str, HogQLFunctionMeta] = {
),
}
+# JSONDropKeys is an executable UDF like the funnel UDFs, but it is printer-internal (restricted-property blob
+# stripping), not HogQL-exposed, so it lives outside UDFS. Its deployed name is versioned the same way.
+JSON_DROP_KEYS_CLICKHOUSE_NAME = "JSONDropKeys"
+
# We want CI to fail if there is a breaking change and the version hasn't been incremented
if is_cloud() or is_ci():
from posthog.udf_versioner import augment_function_name
for v in UDFS.values():
v.clickhouse_name = augment_function_name(v.clickhouse_name)
+ JSON_DROP_KEYS_CLICKHOUSE_NAME = augment_function_name(JSON_DROP_KEYS_CLICKHOUSE_NAME)
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 89c41e610757..43ef15750dc1 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -47,6 +47,15 @@ def get_channel_definition_dict():
return f"{django_settings.CLICKHOUSE_DATABASE}.channel_definition_dict"
+def get_geoip_city_postal_dict():
+ """Temporary (June 2026 MaxMind incident: https://posthog.slack.com/archives/C0B9DDSCTF1): the ip_trie dictionary backing the lookupGeoip* functions.
+
+ The dictionary maps an IP to GeoLite2 `city_name` / `postal_code` and was created manually on the cloud clusters
+ for the incident backfill — it is not part of any migration, so the functions only work where it exists.
+ """
+ return f"{django_settings.CLICKHOUSE_DATABASE}.city_postal_ip_trie"
+
+
def resolve_field_type(expr: ast.Expr) -> ast.Type | None:
expr_type = expr.type
while isinstance(expr_type, ast.FieldAliasType):
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 9d3134a3bd5f..a2eab46a9abd 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -15,7 +15,13 @@ from posthog.hogql.errors import ImpossibleASTError, InternalHogQLError, QueryEr
from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string, safe_identifier
from posthog.hogql.functions import ADD_OR_NULL_DATETIME_FUNCTIONS, FIRST_ARG_DATETIME_FUNCTIONS
from posthog.hogql.functions.embed_text import resolve_embed_text
-from posthog.hogql.printer.base import BasePrinter, get_channel_definition_dict, resolve_field_type
+from posthog.hogql.functions.udfs import JSON_DROP_KEYS_CLICKHOUSE_NAME
+from posthog.hogql.printer.base import (
+ BasePrinter,
+ get_channel_definition_dict,
+ get_geoip_city_postal_dict,
+ resolve_field_type,
+)
from posthog.hogql.printer.hogql import HogQLPrinter
from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type
from posthog.hogql.type_system import parse_sql_runtime_type
@@ -249,6 +255,31 @@ class ClickHousePrinter(BasePrinter):
if node.name == "embedText":
return self.visit_constant(resolve_embed_text(self.context.team, node))
+ elif node.name in ("_lookupGeoipCityName", "_lookupGeoipPostalCode"):
+ # Temporary (June 2026 MaxMind incident: https://posthog.slack.com/archives/C0B9DDSCTF1), remove with the
+ # geoip_dict_fallback transform. toIPv6OrDefault
+ # covers both families (v4 input becomes a ::ffff: mapped address, which the ip_trie dict resolves against
+ # its IPv4 prefixes); empty or invalid input becomes '::', which misses and returns the '' default.
+ # Reads the once-per-query decision from the context (set in prepare_ast_for_printing) rather than
+ # re-probing, so a background cache refresh can never make this gate reject the transform's own calls.
+ if not self.context.geoip_dict_fallback_enabled:
+ raise QueryError(f"{node.name} is not available on this instance")
+ # Deliberately NO property-restriction guard here, reviewers included AI ones: these are pure functions
+ # over GeoLite2, a public IP->geo dataset, and they cannot circumvent property-level access control.
+ # (1) They never expose a restricted input: a restricted property read in the argument (e.g.
+ # `properties.$ip`) is scrubbed to constant NULL by the restriction layer before this function sees it,
+ # so the lookup misses and returns '' — there is no oracle for the restricted value. (2) They never serve
+ # a restricted *stored* property: the "restricted property reads as NULL" contract is enforced where
+ # properties are read (clickhouse_property_resolution + JSONDropKeys) and by the geoip_dict_fallback
+ # transform's own target guard. (3) The only capability left is deriving geo data from an IP the user can
+ # already read, which any external geo service provides — a guard here would add zero protection while
+ # risking the printer rejecting the transform's own emitted calls. Pinned by tests in
+ # test_geoip_dict_fallback.py.
+ attribute = "city_name" if node.name == "_lookupGeoipCityName" else "postal_code"
+ geoip_dict = get_geoip_city_postal_dict()
+ return (
+ f"dictGetStringOrDefault('{geoip_dict}', '{attribute}', toIPv6OrDefault(coalesce({args[0]}, '')), '')"
+ )
elif node.name == "lookupDomainType":
channel_dict = get_channel_definition_dict()
return f"coalesce(dictGetOrNull('{channel_dict}', 'domain_type', (coalesce({args[0]}, ''), 'source')), dictGetOrNull('{channel_dict}', 'domain_type', (cutToFirstSignificantSubdomain(coalesce({args[0]}, '')), 'source')))"
@@ -455,7 +486,7 @@ class ClickHousePrinter(BasePrinter):
return field_sql
keys_placeholder = self.context.add_sensitive_value(sorted(keys_to_drop))
- return f"JSONDropKeys({keys_placeholder})({field_sql})"
+ return f"{JSON_DROP_KEYS_CLICKHOUSE_NAME}({keys_placeholder})({field_sql})"
def _get_events_session_id_table_type(self, node: ast.Expr) -> ast.BaseTableType | None:
"""If the expression resolves to $session_id on the events table, return the table type."""
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index a81dbb0494f9..8529bf61f811 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -26,6 +26,10 @@ from posthog.hogql.printer.postgres import PostgresPrinter
from posthog.hogql.resolver import ResolverFactory, resolve_types
from posthog.hogql.transforms.clickhouse_property_resolution import clickhouse_property_resolution
from posthog.hogql.transforms.events_predicate_pushdown import apply_events_predicate_pushdown, events_pushdown_enabled
+from posthog.hogql.transforms.geoip_dict_fallback import (
+ apply_geoip_dict_fallback_delete_this_function_when_inc_2026_06_11_maxmind_missing_data_is_resolved,
+ geoip_dict_fallback_enabled_for_team,
+)
from posthog.hogql.transforms.in_cohort import resolve_in_cohorts, resolve_in_cohorts_conjoined
from posthog.hogql.transforms.lazy_tables import resolve_lazy_tables
from posthog.hogql.transforms.logical_property_lowering import lower_property_access
@@ -212,6 +216,24 @@ def prepare_ast_for_printing(
with context.timings.measure("lower_property_access"):
node = lower_property_access(node, context)
+ # Temporary (June 2026 MaxMind incident: https://posthog.slack.com/archives/C0B9DDSCTF1): recover blanked geoip city/postal reads from the IP via a ClickHouse
+ # dictionary. Runs on the lowered AST so the reads it adds are plain PropertyAccess nodes, which the resolution
+ # pass below routes to materialized columns. Operator-controlled via env only, per team. Decided exactly once
+ # per query, on the context, so the printer's `_lookupGeoip*` gate can never disagree with the transform.
+ # Never applies within_non_hogql_query: those fragments splice into DELETE mutations (data deletion requests)
+ # and legacy filters, where the matched row set must not depend on env/probe state and a missing dictionary
+ # would wedge the sticky mutation queue. Remove with the transform.
+ context.geoip_dict_fallback_enabled = (
+ not context.within_non_hogql_query and geoip_dict_fallback_enabled_for_team(context.team_id)
+ )
+ if context.geoip_dict_fallback_enabled:
+ with context.timings.measure("geoip_dict_fallback"):
+ node = (
+ apply_geoip_dict_fallback_delete_this_function_when_inc_2026_06_11_maxmind_missing_data_is_resolved(
+ node, context
+ )
+ )
+
# Events predicate pushdown runs on the lowered AST (between lowering and property resolution), so it matches the
# dialect-neutral PropertyAccess form. Its pre-filtering subquery projects only source columns (raw blobs and
# bare events columns); outer blob references are re-typed onto the subquery, so the resolution pass substitutes
diff --git a/posthog/hogql/transforms/geoip_dict_fallback.py b/posthog/hogql/transforms/geoip_dict_fallback.py
new file mode 100644
index 000000000000..b7c90772fe1b
--- /dev/null
+++ b/posthog/hogql/transforms/geoip_dict_fallback.py
@@ -0,0 +1,232 @@
+"""Temporary ClickHouse pass: recover blanked `$geoip_city_name` / `$geoip_postal_code` event properties at query time.
+
+A bad MaxMind GeoLite2-City release (June 2026 incident: https://posthog.slack.com/archives/C0B9DDSCTF1) blanked city and postal data on enriched events, and the
+ALTER UPDATE backfill over the affected partitions is slow. Until it catches up, this pass patches reads of the two
+affected properties: when the stored value is blank but geoip enrichment did run (`$geoip_country_code` is set) the
+value is recovered from the event's `$ip` via the `city_postal_ip_trie` ClickHouse dictionary, which was built from a
+healthy GeoLite2 build. The country-code guard keeps never-enriched rows (geoip disabled, pre-geoip events) blank, so
+only rows the incident could have affected change.
+
+Gated on the `HOGQL_GEOIP_DICT_FALLBACK_TEAMS` env var: a comma-separated list of team ids, or "*" for all teams;
+empty (the default) disables it everywhere. Deliberately not a query modifier so it is operator-controlled only and
+leaves nothing persisted in `team.modifiers` or saved queries to scrub at removal time. The gate also verifies at
+runtime that the dictionary exists, healthy, on every node of the cluster (cached in-process like materialized-column
+discovery), so the transform stands down instead of printing failing SQL wherever the manually provisioned dictionary
+is absent or broken. The transform never applies to `within_non_hogql_query` fragments: those splice into DELETE
+mutations (data deletion requests) and legacy filters, where the matched row set must not depend on env/probe state.
+
+Operational runbook (the env var must be set identically on every deployment that compiles HogQL — web, celery,
+query service, temporal — per region):
+- Enable: provision the dictionary ON CLUSTER and verify `system.dictionaries` on every node FIRST, then set the env
+ var, staged team lists before "*" ("*" changes every team's query cache key at once, a fleet-wide recompute).
+- Remove: empty the env var on all deployments and confirm rollout, then delete this file with its callsite in
+ `printer/utils.py`, the context field in `context.py`, the cache-payload entry in `query_runner.py`, the env
+ setting, and the `_lookupGeoip*` functions — and only then drop the dictionary and its source table (dropping the
+ dictionary first leaves up to 15 minutes of cached "healthy" probes printing SQL that hard-fails).
+
+Runs between logical property lowering and ClickHouse property resolution: each affected `PropertyAccess` becomes a
+conditional over three property reads (the property itself, `$geoip_country_code`, `$ip`), and the resolution pass
+then routes each read through its materialized column where one exists — so on cloud the whole fallback runs off
+`mat_*` columns plus an in-RAM dictionary lookup, without touching the `properties` blob.
+
+Known limitation: property-level access control applies to the fallback's source reads like to any other read, so for
+a user with `$ip` (or `$geoip_country_code`) restricted, those reads scrub to NULL, the dictionary lookup misses, and
+the blanked values stay blank — even though the derived city/postal is itself readable to them. Accepted deliberately:
+making that case recover would mean exempting the internal reads from the restriction boundary, which is not worth it
+for a temporary fix. Nothing leaks and nothing errors; recovery just quietly misses for those users.
+
+Scope: only event-property reads are covered. The incident also blanked person geo properties (the enrichment `$set`s
+the same `$geoip_*` fields onto persons) and the values baked into derived stores (sessions, web analytics
+preaggregated tables); those need their own fixes and are deliberately out of scope here — there is no per-person
+`$ip` to recover from at query time.
+"""
+
+from datetime import timedelta
+from typing import cast
+
+from django.conf import settings
+
+import structlog
+
+from posthog.hogql import ast
+from posthog.hogql.base import _T_AST
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.models import DatabaseField
+from posthog.hogql.printer.base import get_geoip_city_postal_dict
+from posthog.hogql.restricted_properties import restricted_property_keys_for_table_type
+from posthog.hogql.visitor import CloningVisitor, clone_expr
+
+from posthog.cache_utils import cache_for
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.settings import CLICKHOUSE_CLUSTER
+
+logger = structlog.get_logger(__name__)
+
+FALLBACK_PROPERTY_TO_FUNCTION = {
+ "$geoip_city_name": "_lookupGeoipCityName",
+ "$geoip_postal_code": "_lookupGeoipPostalCode",
+}
+
+
+@cache_for(timedelta(minutes=15), background_refresh=True)
+def _geoip_dict_exists() -> bool:
+ """Whether the `city_postal_ip_trie` dictionary exists, healthy, on every node of the cluster.
+
+ The dictionary is manually provisioned (no migration), so this mirrors the runtime materialized-column discovery:
+ checked against `system.dictionaries` and cached in-process. The emitted `dictGet` executes on every shard and
+ replica that serves events queries, so the probe fans out via `clusterAllReplicas` and requires the dictionary
+ DDL on every node with none in a failed state — partial provisioning or a broken source disables the fallback
+ everywhere rather than hard-failing queries on the nodes that lack it. A failed probe counts as absent: a
+ ClickHouse blip degrades the fallback, never the query.
+ """
+ database, _, name = get_geoip_city_postal_dict().partition(".")
+ try:
+ # The cluster name comes from operator settings, not user input, mirroring ON_CLUSTER_CLAUSE.
+ rows = sync_execute(
+ f"""
+ SELECT
+ (SELECT count() FROM clusterAllReplicas('{CLICKHOUSE_CLUSTER}', system.one)) AS total_nodes,
+ count() AS nodes_with_dictionary,
+ countIf(status IN ('FAILED', 'FAILED_AND_RELOADING')) AS failed_nodes
+ FROM clusterAllReplicas('{CLICKHOUSE_CLUSTER}', system.dictionaries)
+ WHERE database = %(database)s AND name = %(name)s
+ """,
+ {"database": database, "name": name},
+ settings={"max_execution_time": 5},
+ ch_user=ClickHouseUser.HOGQL,
+ )
+ total_nodes, nodes_with_dictionary, failed_nodes = rows[0]
+ healthy = total_nodes > 0 and nodes_with_dictionary == total_nodes and failed_nodes == 0
+ if not healthy:
+ logger.warning(
+ "geoip_dict_fallback_dictionary_unhealthy",
+ total_nodes=total_nodes,
+ nodes_with_dictionary=nodes_with_dictionary,
+ failed_nodes=failed_nodes,
+ )
+ return healthy
+ except Exception:
+ # The fallback silently standing down is itself an incident-mitigation failure, so make it visible.
+ logger.warning("geoip_dict_fallback_dictionary_probe_failed", exc_info=True)
+ return False
+
+
+def geoip_dict_fallback_team_in_env(team_id: int | None) -> bool:
+ """Whether the env var lists this team ("*" matches every team). Pure config, no ClickHouse dependency.
+
+ This is the half used for query cache keys: keys must depend only on operator-controlled config, never on the
+ runtime dictionary probe, or a transient probe failure would flip every enabled team's cache keys at once and
+ recompute the fleet against an already-degraded cluster.
+ """
+ raw = settings.HOGQL_GEOIP_DICT_FALLBACK_TEAMS.strip()
+ if not raw or team_id is None:
+ return False
+ return raw == "*" or str(team_id) in {part.strip() for part in raw.split(",")}
+
+
+def geoip_dict_fallback_enabled_for_team(team_id: int | None) -> bool:
+ """Whether the env var enables the fallback for this team and the dictionary is healthy cluster-wide."""
+ return geoip_dict_fallback_team_in_env(team_id) and _geoip_dict_exists()
+
+
+class GeoipDictFallback(CloningVisitor):
+ """Wraps events `properties.$geoip_city_name` / `properties.$geoip_postal_code` reads with the dictionary fallback."""
+
+ def __init__(self, context: HogQLContext) -> None:
+ super().__init__(clear_types=False)
+ self.context = context
+
+ def visit_property_access(self, node: ast.PropertyAccess) -> ast.Expr:
+ node = super().visit_property_access(node)
+ if len(node.keys) != 1:
+ return node
+ property_name = str(node.keys[0])
+ function_name = FALLBACK_PROPERTY_TO_FUNCTION.get(property_name)
+ if function_name is None:
+ return node
+ table_type = self._events_properties_table_type(node)
+ if table_type is None:
+ return node
+ # Property-level access control resolves restricted reads to NULL later in the pipeline; wrapping such a read
+ # would reconstruct the restricted value from `$ip` on every enriched row, so the fallback must stand down
+ # when the target property is restricted. Only the event scope counts: this is an events-table read, so a
+ # person/group-scoped restriction on the same name doesn't affect it. Restricted sources need no guard and
+ # don't disable it: the restriction layer scrubs those reads to NULL, so recovery quietly misses without
+ # exposing them. Known accepted limitation: a user with `$ip` restricted keeps blank values even though the
+ # derived property is readable — punching the restriction boundary for the internal reads was not worth it
+ # for a temporary fix.
+ if property_name in restricted_property_keys_for_table_type(table_type, self.context):
+ return node
+ return self._with_fallback(node, function_name)
+
+ def _events_properties_table_type(self, node: ast.PropertyAccess) -> ast.TableType | None:
+ """The events table type when the read targets the events `properties` blob, else None.
+
+ Person/group properties keep their stored values — including under persons-on-events, where they live on the
+ events table behind a virtual sub-table whose blob field is also named `properties` but resolves to the
+ `person_properties` / `group{N}_properties` column. Checking the resolved column name catches those. Note the
+ incident DID blank person geo properties too (the enrichment `$set`s the same fields onto persons), but
+ recovering them is a separate, harder fix that is deliberately out of scope here: this expression recovers
+ from the event-time `$ip`, which has no per-person equivalent to read.
+ """
+ expr_type = node.expr.type
+ if not isinstance(expr_type, ast.FieldType) or expr_type.name != "properties":
+ return None
+ field = expr_type.resolve_database_field(self.context)
+ if not isinstance(field, DatabaseField) or field.name != "properties":
+ return None
+ table_type: ast.Type | None = expr_type.table_type
+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.VirtualTableType)):
+ table_type = table_type.table_type
+ if not isinstance(table_type, ast.TableType):
+ return None
+ if table_type.table.to_printed_clickhouse(self.context) != "events":
+ return None
+ return table_type
+
+ def _with_fallback(self, node: ast.PropertyAccess, function_name: str) -> ast.Expr:
+ # The stored value wins whenever it is set; both NULL and '' mean "not set" for these string properties.
+ def blob_read(key: str) -> ast.PropertyAccess:
+ return ast.PropertyAccess(expr=clone_expr(node.expr), keys=[key], type=ast.StringType(nullable=True))
+
+ def is_set(expr: ast.Expr) -> ast.Expr:
+ return ast.Call(
+ name="notEmpty",
+ args=[ast.Call(name="ifNull", args=[expr, ast.Constant(value="")])],
+ type=ast.BooleanType(),
+ )
+
+ # On a dictionary miss, fall back to the stored value rather than NULL, so blanks keep their existing
+ # representation (materialized reads scrub '' to NULL, raw JSON reads return '' for a present-but-empty key).
+ recovered = ast.Call(
+ name="coalesce",
+ args=[
+ ast.Call(
+ name="nullIf",
+ args=[
+ ast.Call(name=function_name, args=[blob_read("$ip")], type=ast.StringType()),
+ ast.Constant(value=""),
+ ],
+ type=ast.StringType(nullable=True),
+ ),
+ clone_expr(node),
+ ],
+ type=ast.StringType(nullable=True),
+ )
+ guarded = ast.Call(
+ name="if",
+ args=[is_set(blob_read("$geoip_country_code")), recovered, clone_expr(node)],
+ type=ast.StringType(nullable=True),
+ )
+ return ast.Call(
+ name="if",
+ args=[is_set(clone_expr(node)), clone_expr(node), guarded],
+ type=ast.StringType(nullable=True),
+ )
+
+
+def apply_geoip_dict_fallback_delete_this_function_when_inc_2026_06_11_maxmind_missing_data_is_resolved(
+ node: _T_AST, context: HogQLContext
+) -> _T_AST:
+ return cast(_T_AST, GeoipDictFallback(context).visit(node))
diff --git a/posthog/hogql/transforms/test/__snapshots__/test_geoip_dict_fallback.ambr b/posthog/hogql/transforms/test/__snapshots__/test_geoip_dict_fallback.ambr
new file mode 100644
index 000000000000..078662807016
--- /dev/null
+++ b/posthog/hogql/transforms/test/__snapshots__/test_geoip_dict_fallback.ambr
@@ -0,0 +1,58 @@
+# serializer version: 1
+# name: TestGeoipDictFallbackExecution.test_env_disabled_leaves_values_blank
+ '''
+ SELECT events.event AS event,
+ nullIf(nullIf(events.`mat_$geoip_city_name`, ''), 'null') AS `$geoip_city_name`,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$geoip_postal_code'), ''), 'null'), '^"|"$', '') AS `$geoip_postal_code`
+ FROM events
+ WHERE equals(events.team_id, 99999)
+ ORDER BY events.event ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestGeoipDictFallbackExecution.test_fallback_recovers_blanked_values
+ '''
+
+ SELECT
+ (SELECT count()
+ FROM clusterAllReplicas('posthog', system.one)) AS total_nodes,
+ count() AS nodes_with_dictionary,
+ countIf(status IN ('FAILED', 'FAILED_AND_RELOADING')) AS failed_nodes
+ FROM clusterAllReplicas('posthog', system.dictionaries)
+ WHERE database = 'posthog_test'
+ AND name = 'city_postal_ip_trie'
+ '''
+# ---
+# name: TestGeoipDictFallbackExecution.test_fallback_recovers_blanked_values.1
+ '''
+ SELECT events.event AS event,
+ if(notEmpty(ifNull(nullIf(nullIf(events.`mat_$geoip_city_name`, ''), 'null'), '')), nullIf(nullIf(events.`mat_$geoip_city_name`, ''), 'null'), if(notEmpty(ifNull(nullIf(nullIf(events.`mat_$geoip_country_code`, ''), 'null'), '')), coalesce(nullIf(dictGetStringOrDefault('posthog_test.city_postal_ip_trie', 'city_name', toIPv6OrDefault(coalesce(nullIf(nullIf(events.`mat_$ip`, ''), 'null'), '')), ''), ''), nullIf(nullIf(events.`mat_$geoip_city_name`, ''), 'null')), nullIf(nullIf(events.`mat_$geoip_city_name`, ''), 'null'))) AS `$geoip_city_name`,
+ if(notEmpty(ifNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$geoip_postal_code'), ''), 'null'), '^"|"$', ''), '')), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$geoip_postal_code'), ''), 'null'), '^"|"$', ''), if(notEmpty(ifNull(nullIf(nullIf(events.`mat_$geoip_country_code`, ''), 'null'), '')), coalesce(nullIf(dictGetStringOrDefault('posthog_test.city_postal_ip_trie', 'postal_code', toIPv6OrDefault(coalesce(nullIf(nullIf(events.`mat_$ip`, ''), 'null'), '')), ''), ''), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$geoip_postal_code'), ''), 'null'), '^"|"$', '')), replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$geoip_postal_code'), ''), 'null'), '^"|"$', ''))) AS `$geoip_postal_code`
+ FROM events
+ WHERE equals(events.team_id, 99999)
+ ORDER BY events.event ASC
+ LIMIT 100 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
diff --git a/posthog/hogql/transforms/test/test_geoip_dict_fallback.py b/posthog/hogql/transforms/test/test_geoip_dict_fallback.py
new file mode 100644
index 000000000000..b9ae7bd77413
--- /dev/null
+++ b/posthog/hogql/transforms/test/test_geoip_dict_fallback.py
@@ -0,0 +1,484 @@
+import pytest
+from posthog.test.base import (
+ BaseTest,
+ ClickhouseTestMixin,
+ _create_event,
+ flush_persons_and_events,
+ materialized,
+ snapshot_clickhouse_queries,
+)
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import PersonsOnEventsMode
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import QueryError
+from posthog.hogql.hogql import translate_hogql
+from posthog.hogql.modifiers import HogQLQueryModifiers
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer.base import get_geoip_city_postal_dict
+from posthog.hogql.printer.utils import prepare_and_print_ast
+from posthog.hogql.query import execute_hogql_query
+from posthog.hogql.transforms.geoip_dict_fallback import (
+ geoip_dict_fallback_enabled_for_team,
+ geoip_dict_fallback_team_in_env,
+)
+
+from posthog.clickhouse.client import sync_execute
+from posthog.constants import AvailableFeature
+from posthog.settings import CLICKHOUSE_DATABASE, CLICKHOUSE_PASSWORD
+
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
+from products.event_definitions.backend.models.property_definition import PropertyDefinition
+
+
+class TestGeoipDictFallback(ClickhouseTestMixin, BaseTest):
+ maxDiff = None
+
+ def _print_select(
+ self,
+ select: str,
+ teams: str = "*",
+ modifiers: HogQLQueryModifiers | None = None,
+ restricted_properties: set[tuple[str, int]] | None = None,
+ dict_exists: bool = True,
+ ) -> tuple[str, HogQLContext]:
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=modifiers if modifiers is not None else HogQLQueryModifiers(),
+ restricted_properties=restricted_properties,
+ )
+ # The dictionary only exists on the test ClickHouse in the execution tests below, so stub its discovery here.
+ with (
+ override_settings(HOGQL_GEOIP_DICT_FALLBACK_TEAMS=teams),
+ patch(
+ "posthog.hogql.transforms.geoip_dict_fallback._geoip_dict_exists",
+ return_value=dict_exists,
+ ),
+ ):
+ query, _ = prepare_and_print_ast(parse_select(select), context, "clickhouse")
+ return query, context
+
+ @parameterized.expand(
+ [
+ ("$geoip_city_name", "city_name"),
+ ("$geoip_postal_code", "postal_code"),
+ ]
+ )
+ def test_fallback_wraps_affected_event_properties(self, property_name: str, dict_attribute: str) -> None:
+ sql, context = self._print_select(f"SELECT properties.{property_name} FROM events")
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', '{dict_attribute}'" in sql
+ assert "toIPv6OrDefault" in sql
+ # The recovery is guarded on enrichment having run, so never-enriched rows stay blank. The property keys print
+ # as bound parameters, so look for them in the context values rather than the SQL text.
+ assert "$geoip_country_code" in context.values.values()
+ assert "$ip" in context.values.values()
+
+ @parameterized.expand(
+ [
+ ("env empty", "SELECT properties.$geoip_city_name FROM events", ""),
+ ("other team only", "SELECT properties.$geoip_city_name FROM events", "99999999"),
+ ("unaffected property", "SELECT properties.$browser FROM events", "*"),
+ ("person property", "SELECT properties.$geoip_city_name FROM persons", "*"),
+ ("nested key", "SELECT properties.$geoip_city_name.x FROM events", "*"),
+ ]
+ )
+ def test_no_fallback(self, _name: str, select: str, teams: str) -> None:
+ sql, _ = self._print_select(select, teams=teams)
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_fallback_enabled_for_listed_team(self) -> None:
+ sql, _ = self._print_select("SELECT properties.$geoip_city_name FROM events", teams=f"99999999, {self.team.pk}")
+ assert "dictGetStringOrDefault" in sql
+
+ def test_no_fallback_when_dictionary_missing(self) -> None:
+ sql, _ = self._print_select("SELECT properties.$geoip_city_name FROM events", dict_exists=False)
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_enabled_helper_requires_real_dictionary(self) -> None:
+ # No stub here: the dictionary does not exist on the test ClickHouse, so the runtime discovery says no even
+ # though the env var enables the team. The env-membership half (used for cache keys) stays True regardless:
+ # cache keys must depend only on operator config, never on the probe.
+ with override_settings(HOGQL_GEOIP_DICT_FALLBACK_TEAMS="*"):
+ assert geoip_dict_fallback_enabled_for_team(self.team.pk) is False
+ assert geoip_dict_fallback_team_in_env(self.team.pk) is True
+
+ def test_no_fallback_in_non_hogql_fragments(self) -> None:
+ # Deletion predicates and legacy filters compile via translate_hogql with within_non_hogql_query=True and
+ # splice into DELETE mutations on sharded_events: the matched row set must not depend on env/probe state, and
+ # a dictGet inside a mutation would wedge the sticky mutation queue if the dictionary disappears.
+ context = HogQLContext(team_id=self.team.pk, within_non_hogql_query=True, enable_select_queries=True)
+ with (
+ override_settings(HOGQL_GEOIP_DICT_FALLBACK_TEAMS="*"),
+ patch("posthog.hogql.transforms.geoip_dict_fallback._geoip_dict_exists", return_value=True),
+ ):
+ sql = translate_hogql("properties.$geoip_city_name = 'London'", context)
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_person_properties_on_events_not_wrapped_under_poe(self) -> None:
+ # Under persons-on-events, person properties live on the events table behind a virtual sub-table whose blob
+ # field is also named `properties` — it must not get the fallback. The incident blanked person geo too, but
+ # recovering it is a separate, harder fix (out of scope here); event-time `$ip` recovery doesn't map to it.
+ sql, _ = self._print_select(
+ "SELECT person.properties.$geoip_city_name FROM events",
+ modifiers=HogQLQueryModifiers(
+ personsOnEventsMode=PersonsOnEventsMode.PERSON_ID_OVERRIDE_PROPERTIES_ON_EVENTS
+ ),
+ )
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_no_fallback_for_restricted_target_property(self) -> None:
+ # Property-level access control resolves the restricted read to NULL; the fallback must not reconstruct it
+ # from `$ip`, so it stands down entirely.
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name FROM events",
+ restricted_properties={("$geoip_city_name", PropertyDefinition.Type.EVENT)},
+ )
+ assert "dictGetStringOrDefault" not in sql
+
+ @parameterized.expand(
+ [
+ ("select", "SELECT properties.$geoip_city_name FROM events"),
+ ("where", "SELECT count() FROM events WHERE properties.$geoip_city_name = 'London'"),
+ ("subquery", "SELECT city FROM (SELECT properties.$geoip_city_name AS city FROM events)"),
+ ("cte", "WITH geo AS (SELECT properties.$geoip_city_name AS city FROM events) SELECT city FROM geo"),
+ ]
+ )
+ def test_no_fallback_for_restricted_target_in_any_query_shape(self, _name: str, select: str) -> None:
+ sql, _ = self._print_select(select, restricted_properties={("$geoip_city_name", PropertyDefinition.Type.EVENT)})
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_restriction_guards_apply_per_property(self) -> None:
+ # Restricting one of the two affected properties must not disable recovery of the other: with postal
+ # restricted, the city read is still wrapped (exactly one lookup) and the postal read is not.
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name, properties.$geoip_postal_code FROM events",
+ restricted_properties={("$geoip_postal_code", PropertyDefinition.Type.EVENT)},
+ )
+ assert sql.count("dictGetStringOrDefault") == 1
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', 'city_name'" in sql
+
+ def test_no_fallback_when_both_targets_restricted(self) -> None:
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name, properties.$geoip_postal_code FROM events",
+ restricted_properties={
+ ("$geoip_city_name", PropertyDefinition.Type.EVENT),
+ ("$geoip_postal_code", PropertyDefinition.Type.EVENT),
+ },
+ )
+ assert "dictGetStringOrDefault" not in sql
+
+ def test_restricted_country_source_read_is_scrubbed(self) -> None:
+ # Sibling of the `$ip` pin below: a restricted `$geoip_country_code` guard read resolves to the restricted
+ # constant-NULL substitution (never the real column), so recovery misses rather than probing the value.
+ with (
+ materialized("events", "$geoip_city_name"),
+ materialized("events", "$geoip_country_code"),
+ materialized("events", "$ip"),
+ ):
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name FROM events",
+ restricted_properties={("$geoip_country_code", PropertyDefinition.Type.EVENT)},
+ )
+ assert "dictGetStringOrDefault" in sql
+ assert "mat_$geoip_country_code" not in sql
+
+ @parameterized.expand(
+ [
+ ("ip restricted", "$ip", PropertyDefinition.Type.EVENT),
+ ("country restricted", "$geoip_country_code", PropertyDefinition.Type.EVENT),
+ ("unrelated restricted", "$browser", PropertyDefinition.Type.EVENT),
+ ("person-scoped city", "$geoip_city_name", PropertyDefinition.Type.PERSON),
+ ("group-scoped city", "$geoip_city_name", PropertyDefinition.Type.GROUP),
+ ("session-scoped city", "$geoip_city_name", PropertyDefinition.Type.SESSION),
+ ]
+ )
+ def test_fallback_unaffected_by_non_target_restrictions(
+ self, _name: str, restricted_key: str, property_type: int
+ ) -> None:
+ # Restricted sources don't disable the rewrite: the restriction layer scrubs those reads to NULL, so for such
+ # users recovery quietly misses without exposing them (accepted limitation: restricted `$ip` means no recovery
+ # even though the derived property is readable). Unrelated restrictions change nothing, and neither do
+ # non-event-scoped restrictions on the target name — this is an events-table read.
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name FROM events",
+ restricted_properties={(restricted_key, property_type)},
+ )
+ assert "dictGetStringOrDefault" in sql
+
+ def test_restricted_ip_source_read_is_scrubbed(self) -> None:
+ # The accepted limitation pinned: with `$ip` restricted, the injected source read resolves to the restricted
+ # constant-NULL substitution (never the real column), so recovery misses rather than reading the raw IP.
+ with (
+ materialized("events", "$geoip_city_name"),
+ materialized("events", "$geoip_country_code"),
+ materialized("events", "$ip"),
+ ):
+ sql, _ = self._print_select(
+ "SELECT properties.$geoip_city_name FROM events",
+ restricted_properties={("$ip", PropertyDefinition.Type.EVENT)},
+ )
+ assert "dictGetStringOrDefault" in sql
+ assert "mat_$ip" not in sql
+
+ def test_fallback_applies_in_where_clause(self) -> None:
+ sql, _ = self._print_select("SELECT count() FROM events WHERE properties.$geoip_city_name = 'London'")
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', 'city_name'" in sql
+
+ def test_fallback_reads_materialized_columns(self) -> None:
+ with (
+ materialized("events", "$geoip_city_name"),
+ materialized("events", "$geoip_country_code"),
+ materialized("events", "$ip"),
+ ):
+ sql, _ = self._print_select("SELECT properties.$geoip_city_name FROM events")
+ assert "dictGetStringOrDefault" in sql
+ # All three reads in the fallback expression resolve to their materialized columns, not JSON extracts.
+ assert "mat_$geoip_city_name" in sql
+ assert "mat_$geoip_country_code" in sql
+ assert "mat_$ip" in sql
+ assert "JSONExtract" not in sql
+
+ def test_lookup_functions_render_for_direct_use_when_enabled(self) -> None:
+ sql, _ = self._print_select("SELECT _lookupGeoipCityName('89.160.20.129') FROM events")
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', 'city_name'" in sql
+
+ def test_lookup_functions_rejected_when_fallback_disabled(self) -> None:
+ with pytest.raises(QueryError, match="not available"):
+ self._print_select("SELECT _lookupGeoipCityName('89.160.20.129') FROM events", teams="")
+
+ # The _lookupGeoip* functions are deliberately NOT property-restriction guarded (see the printer): they are pure
+ # functions over GeoLite2, a public IP->geo dataset, so they cannot circumvent property-level access control. The
+ # two tests below pin the two halves of that argument.
+
+ @parameterized.expand(
+ [
+ ("event-scoped target", "$geoip_city_name", PropertyDefinition.Type.EVENT),
+ ("person-scoped target", "$geoip_city_name", PropertyDefinition.Type.PERSON),
+ ]
+ )
+ def test_lookup_functions_render_despite_target_restriction(
+ self, _name: str, restricted_key: str, property_type: int
+ ) -> None:
+ # Deriving geo data from an IP the user can already read circumvents nothing — any external geo service gives
+ # the same answer — and the restricted *stored* property still reads NULL (enforced at the property read and
+ # by the transform's target guard, covered by the end-to-end tests below).
+ sql, _ = self._print_select(
+ "SELECT _lookupGeoipCityName('89.160.20.129') FROM events",
+ restricted_properties={(restricted_key, property_type)},
+ )
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', 'city_name'" in sql
+
+ def test_lookup_functions_cannot_read_restricted_arguments(self) -> None:
+ # The other half of why no guard is needed: a restricted property read in the argument is scrubbed to constant
+ # NULL by the restriction layer before the function sees it, so the lookup misses — the function is no oracle
+ # for restricted values.
+ sql, _ = self._print_select(
+ "SELECT _lookupGeoipPostalCode(properties.$ip) FROM events",
+ restricted_properties={("$ip", PropertyDefinition.Type.EVENT)},
+ )
+ assert f"dictGetStringOrDefault('{get_geoip_city_postal_dict()}', 'postal_code'" in sql
+ assert "toIPv6OrDefault(coalesce(NULL, ''))" in sql
+
+ @parameterized.expand(
+ [
+ (
+ "subquery",
+ "SELECT city FROM (SELECT properties.$geoip_city_name AS city FROM events) GROUP BY city",
+ 1,
+ ),
+ (
+ "cte",
+ "WITH geo AS (SELECT properties.$geoip_city_name AS city FROM events) SELECT city FROM geo",
+ 1,
+ ),
+ (
+ "table alias",
+ "SELECT e.properties.$geoip_city_name FROM events AS e",
+ 1,
+ ),
+ (
+ "group by breakdown",
+ "SELECT properties.$geoip_city_name AS city, count() FROM events GROUP BY city ORDER BY count() DESC",
+ 1,
+ ),
+ (
+ "union all",
+ "SELECT properties.$geoip_city_name FROM events UNION ALL SELECT properties.$geoip_city_name FROM events",
+ 2,
+ ),
+ (
+ "select and where both wrapped",
+ "SELECT properties.$geoip_city_name FROM events WHERE properties.$geoip_city_name != ''",
+ 2,
+ ),
+ ]
+ )
+ def test_fallback_in_complex_query_shapes(self, _name: str, select: str, expected_lookups: int) -> None:
+ sql, _ = self._print_select(select)
+ assert sql.count("dictGetStringOrDefault") == expected_lookups
+
+ def test_fallback_in_join_only_wraps_the_events_side(self) -> None:
+ sql, _ = self._print_select(
+ "SELECT e.properties.$geoip_city_name, p.properties.$geoip_city_name "
+ "FROM events AS e LEFT JOIN persons AS p ON p.id = e.person_id"
+ )
+ # The events-side read gets the fallback; the persons-side read of the same property name is left alone.
+ assert sql.count("dictGetStringOrDefault") == 1
+
+ def test_person_properties_on_events_not_wrapped(self) -> None:
+ # person.properties reads off events resolve to the person_properties blob (or a joined subquery), neither of
+ # which is the events properties blob the incident (https://posthog.slack.com/archives/C0B9DDSCTF1) affected.
+ sql, _ = self._print_select("SELECT person.properties.$geoip_city_name FROM events")
+ assert "dictGetStringOrDefault" not in sql
+
+
+class TestGeoipDictFallbackExecution(ClickhouseTestMixin, BaseTest):
+ """End-to-end: real events, materialized columns, and a real ip_trie dictionary on the test ClickHouse."""
+
+ maxDiff = None
+ SOURCE_TABLE = f"{CLICKHOUSE_DATABASE}.geoip_dict_fallback_test_source"
+
+ def setUp(self) -> None:
+ super().setUp()
+ # Mirror production: city, country code, and IP are materialized; postal code is not.
+ for prop in ("$geoip_city_name", "$geoip_country_code", "$ip"):
+ self.enterContext(materialized("events", prop))
+
+ # Deliberately NOT a ClickHouse migration: the fallback is temporary (reverted once the backfill completes), so
+ # the dictionary was created manually on the cloud clusters rather than rolled out to every install, and this
+ # test creates its own miniature version the same way.
+ sync_execute(
+ f"CREATE TABLE IF NOT EXISTS {self.SOURCE_TABLE} "
+ "(prefix String, city_name String, postal_code String) ENGINE = MergeTree() ORDER BY prefix"
+ )
+ sync_execute(
+ f"INSERT INTO {self.SOURCE_TABLE} VALUES "
+ "('89.160.20.0/24', 'Linkoping', '582 22'), ('2001:db8::/32', 'Stockholm', '111 20')"
+ )
+ sync_execute(
+ f"""
+ CREATE DICTIONARY IF NOT EXISTS {get_geoip_city_postal_dict()} (
+ prefix String,
+ city_name String,
+ postal_code String
+ )
+ PRIMARY KEY prefix
+ SOURCE(CLICKHOUSE(DB '{CLICKHOUSE_DATABASE}' TABLE 'geoip_dict_fallback_test_source' PASSWORD '{CLICKHOUSE_PASSWORD}'))
+ LIFETIME(0)
+ LAYOUT(IP_TRIE())
+ """
+ )
+
+ for event, properties in [
+ # Stored values always win, even with an IP the dictionary knows.
+ (
+ "1_stored",
+ {
+ "$geoip_city_name": "Sydney",
+ "$geoip_postal_code": "2000",
+ "$geoip_country_code": "AU",
+ "$ip": "89.160.20.129",
+ },
+ ),
+ # Blanked by the incident (https://posthog.slack.com/archives/C0B9DDSCTF1; enrichment ran: country is set),
+ # recovered from the IP.
+ (
+ "2_recovered_v4",
+ {"$geoip_city_name": "", "$geoip_postal_code": "", "$geoip_country_code": "SE", "$ip": "89.160.20.129"},
+ ),
+ ("3_recovered_v6", {"$geoip_city_name": "", "$geoip_country_code": "SE", "$ip": "2001:db8::1"}),
+ # Enrichment never ran (no country) — stays blank despite the recoverable IP.
+ ("4_unenriched", {"$ip": "89.160.20.129"}),
+ # Enrichment ran but there is no IP to recover from — stays blank.
+ ("5_no_ip", {"$geoip_city_name": "", "$geoip_postal_code": "", "$geoip_country_code": "SE"}),
+ ]:
+ _create_event(team=self.team, event=event, distinct_id="user1", properties=properties)
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ sync_execute(f"DROP DICTIONARY IF EXISTS {get_geoip_city_postal_dict()}")
+ sync_execute(f"DROP TABLE IF EXISTS {self.SOURCE_TABLE}")
+ super().tearDown()
+
+ def _run(self, teams: str, with_user: bool = False) -> list:
+ with override_settings(HOGQL_GEOIP_DICT_FALLBACK_TEAMS=teams):
+ response = execute_hogql_query(
+ "SELECT event, properties.$geoip_city_name, properties.$geoip_postal_code FROM events ORDER BY event",
+ team=self.team,
+ user=self.user if with_user else None,
+ )
+ return response.results
+
+ def _restrict(self, property_name: str) -> None:
+ # Real property-level access control rows, so restrictions load through the production path (requires the
+ # entitlement and a user on the query).
+ 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=property_name, property_type="String", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=definition, access_level=PropertyAccessLevel.NONE.value
+ )
+
+ def test_enabled_helper_detects_real_dictionary(self) -> None:
+ with override_settings(HOGQL_GEOIP_DICT_FALLBACK_TEAMS="*"):
+ assert geoip_dict_fallback_enabled_for_team(self.team.pk) is True
+
+ # Blank representation differs by read path: the materialized city column scrubs '' to NULL, while the
+ # non-materialized postal code is a raw JSON extract that returns '' for a present-but-empty key and NULL for a
+ # missing one. The fallback must preserve exactly that representation whenever it does not recover a value.
+
+ @snapshot_clickhouse_queries
+ def test_fallback_recovers_blanked_values(self) -> None:
+ assert self._run(teams=str(self.team.pk)) == [
+ ("1_stored", "Sydney", "2000"),
+ ("2_recovered_v4", "Linkoping", "582 22"),
+ ("3_recovered_v6", "Stockholm", "111 20"),
+ ("4_unenriched", None, None),
+ ("5_no_ip", None, ""),
+ ]
+
+ @snapshot_clickhouse_queries
+ def test_env_disabled_leaves_values_blank(self) -> None:
+ assert self._run(teams="") == [
+ ("1_stored", "Sydney", "2000"),
+ ("2_recovered_v4", None, ""),
+ ("3_recovered_v6", None, None),
+ ("4_unenriched", None, None),
+ ("5_no_ip", None, ""),
+ ]
+
+ def test_restricted_target_stays_hidden_end_to_end(self) -> None:
+ # With city restricted and the fallback enabled, every city value reads NULL — the stored "Sydney" stays
+ # hidden, and the recoverable rows must NOT come back as dictionary-derived cities. Postal is unaffected and
+ # still recovers.
+ self._restrict("$geoip_city_name")
+ assert self._run(teams=str(self.team.pk), with_user=True) == [
+ ("1_stored", None, "2000"),
+ ("2_recovered_v4", None, "582 22"),
+ ("3_recovered_v6", None, "111 20"),
+ ("4_unenriched", None, None),
+ ("5_no_ip", None, ""),
+ ]
+
+ def test_restricted_ip_source_means_no_recovery_end_to_end(self) -> None:
+ # The accepted limitation on real data: with `$ip` restricted, stored values stay visible but blanked rows
+ # cannot recover (the source read scrubs to NULL, so the dictionary misses).
+ self._restrict("$ip")
+ assert self._run(teams=str(self.team.pk), with_user=True) == [
+ ("1_stored", "Sydney", "2000"),
+ ("2_recovered_v4", None, ""),
+ ("3_recovered_v6", None, None),
+ ("4_unenriched", None, None),
+ ("5_no_ip", None, ""),
+ ]
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index fcf5ac19a4bf..5caaf8220d44 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -79,6 +79,7 @@ from posthog.hogql.modifiers import create_default_modifiers_for_user
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import create_default_modifiers_for_team
from posthog.hogql.timings import HogQLTimings
+from posthog.hogql.transforms.geoip_dict_fallback import geoip_dict_fallback_team_in_env
from posthog.hogql.warehouse_warnings import accumulator_scope
from posthog import settings
@@ -1852,6 +1853,15 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
if restricted:
payload["restricted_properties"] = restricted
+ # Temporary (June 2026 MaxMind incident): only set while the geoip dict fallback is enabled for the team, so
+ # flipping HOGQL_GEOIP_DICT_FALLBACK_TEAMS invalidates exactly the affected teams' cached results (which hold
+ # blank geo values) and nothing changes for anyone else. Deliberately keyed on env membership alone, NOT the
+ # runtime dictionary probe: cache keys must depend only on operator-controlled config, or a transient probe
+ # failure would flip every enabled team's keys at once and recompute the fleet against an already-degraded
+ # cluster. Remove with the transform.
+ if geoip_dict_fallback_team_in_env(self.team.pk):
+ payload["geoip_dict_fallback"] = True
+
return payload
def _get_property_access_restrictions(self) -> list[tuple[str, int]] | None:
diff --git a/posthog/settings/geoip.py b/posthog/settings/geoip.py
index 911811920af8..0a349e86c16a 100644
--- a/posthog/settings/geoip.py
+++ b/posthog/settings/geoip.py
@@ -1,5 +1,11 @@
import os
from posthog.settings.base_variables import BASE_DIR
+from posthog.settings.utils import get_from_env
GEOIP_PATH = os.path.join(BASE_DIR, "share")
+
+# Temporary (June 2026 MaxMind incident: https://posthog.slack.com/archives/C0B9DDSCTF1): enables the query-time geoip
+# dict fallback for a comma-separated list of team ids, or "*" for all teams. Empty (the default) disables it
+# everywhere. Remove with the fallback.
+HOGQL_GEOIP_DICT_FALLBACK_TEAMS = get_from_env("HOGQL_GEOIP_DICT_FALLBACK_TEAMS", "")
diff --git a/posthog/test/base.py b/posthog/test/base.py
index b8cfce90d5b9..8988981240a3 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -287,6 +287,9 @@ def clean_varying_query_parts(query, replace_all_numbers):
# remove version suffix from funnel UDFs
query = re.sub(r"aggregate_funnel(_(?:array|cohort))?(_trends)?(_json)?_v\d+", r"aggregate_funnel\1\2\3", query)
+ # remove version suffix from the restricted-property blob-strip UDF
+ query = re.sub(r"JSONDropKeys_v\d+", "JSONDropKeys", query)
+
# replace django cursors
query = re.sub(r"_django_curs_[0-9sync_]*\"", r'_django_curs_X"', query)
diff --git a/products/data_warehouse/backend/hogql_fixer_ai.py b/products/data_warehouse/backend/hogql_fixer_ai.py
index 2468b76d8f10..0edb44b7a925 100644
--- a/products/data_warehouse/backend/hogql_fixer_ai.py
+++ b/products/data_warehouse/backend/hogql_fixer_ai.py
@@ -28,7 +28,9 @@ def get_hogql_functions() -> str:
ch_functions = list(HOGQL_CLICKHOUSE_FUNCTIONS.keys())
ch_aggregations = list(HOGQL_AGGREGATIONS.keys())
- ph_functions = list(HOGQL_POSTHOG_FUNCTIONS.keys())
+ # Underscore-prefixed functions are internal/preview (matching ALL_EXPOSED_FUNCTION_NAMES): the fixer must not
+ # write them into user queries — some are env-gated or temporary and would error or break at removal.
+ ph_functions = [name for name in HOGQL_POSTHOG_FUNCTIONS if not name.startswith("_")]
_hogql_functions = f"""HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.
These are the non-aggregated HogQL functions:
diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
index cb1859452047..083cd45384a4 100644
--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
@@ -75,7 +75,7 @@
And lastly these are some HogQL specific functions:
```
- ['matchesAction', 'sparkline', 'recordingButton', 'explainCSPReport', 'sortablesemver', 'embedText', 'lookupDomainType', 'lookupPaidSourceType', 'lookupPaidMediumType', 'lookupOrganicSourceType', 'lookupOrganicMediumType', 'convertCurrency', 'getSurveyResponse', 'uniqueSurveySubmissionsFilter', '__preview_getTrafficType', '__preview_getTrafficCategory', '__preview_isBot', '__preview_getBotType', '__preview_getBotName', '__preview_getBotOperator']
+ ['matchesAction', 'sparkline', 'recordingButton', 'explainCSPReport', 'sortablesemver', 'embedText', 'lookupDomainType', 'lookupPaidSourceType', 'lookupPaidMediumType', 'lookupOrganicSourceType', 'lookupOrganicMediumType', 'convertCurrency', 'getSurveyResponse', 'uniqueSurveySubmissionsFilter']
```
You fix HogQL errors that may come from either HogQL resolver errors or clickhouse execution errors. You don't help with other knowledge.