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 typeAwareCastSimplification query modifier (#68901)

George Munyoro3d981c5fdf55
diff --git a/docs/internal/hogql-type-system-now-possible.md b/docs/internal/hogql-type-system-now-possible.md
index aa1be94131f1..36dec9ecfdc7 100644
--- a/docs/internal/hogql-type-system-now-possible.md
+++ b/docs/internal/hogql-type-system-now-possible.md
@@ -436,7 +436,7 @@ Unknowns remain printable.
That is intentional until catalog coverage and compatibility baselines are stronger.
No broad AST rewrite is enabled by default.
-The APIs needed for safe rewrites now exist, and the first guarded simplifier is available behind `HogQLContext.enable_type_aware_cast_simplification`.
+The APIs needed for safe rewrites now exist, and the first guarded simplifier is available behind the `typeAwareCastSimplification` query modifier or the `HogQLContext.enable_type_aware_cast_simplification` flag.
It remains disabled by default.
Practical printer payoffs are now live: when generic function inference proves a helper returns a non-null value, comparisons can avoid the nullable `ifNull(...)` wrapper that was previously needed only because the function boundary was unknown.
This now covers typed string/URL helpers and generated aggregate/tuple comparison shapes in person joins.
@@ -466,9 +466,13 @@ When adding an optimizer rule, ask type questions through the new APIs:
`posthog/hogql/transforms/type_aware_simplification.py` adds the first optimizer consumer.
-It runs only when `HogQLContext.enable_type_aware_cast_simplification` is true.
+It runs only when the `typeAwareCastSimplification` query modifier is enabled, or when the `HogQLContext.enable_type_aware_cast_simplification` flag is true.
+The modifier is the production rollout surface, since it can be set per team via `team.modifiers` without a deploy; the context flag stays as the direct opt-in for tests and internal callers.
The default query path does not change.
+While the modifier is enabled, every removal or fold increments `hogql_type_simplification_total{dialect, kind}`.
+That counter is deliberately unsampled, so a single-team pilot stays visible despite the 1% sampling of the other `hogql_*` type metrics.
+
The simplifier currently removes conservative no-op operations:
- `CAST(String AS String)` and equivalent safe string aliases such as `text`, `varchar`, and `char`
diff --git a/docs/internal/hogql-type-system-reviewers-guide.md b/docs/internal/hogql-type-system-reviewers-guide.md
index 14001cea2918..7028f3f33d55 100644
--- a/docs/internal/hogql-type-system-reviewers-guide.md
+++ b/docs/internal/hogql-type-system-reviewers-guide.md
@@ -97,7 +97,7 @@ It is useful for future corpus checks and for reviewers who want to inspect a sp
### Opt-In Type-Aware Simplification
`posthog/hogql/transforms/type_aware_simplification.py` adds an internal simplifier for conservative rewrites.
-It is disabled by default and only runs when `HogQLContext.enable_type_aware_cast_simplification` is true.
+It is disabled by default and only runs when the `typeAwareCastSimplification` query modifier is enabled, or when the `HogQLContext.enable_type_aware_cast_simplification` flag is true.
It can remove redundant casts and nullability wrappers, fold safe constant conversions, fold finite numeric literal arithmetic, simplify literal `NULL` fallbacks in `ifNull(...)`/`coalesce(...)`, fold exact-present literal JSON path reads, and fold day/week interval arithmetic for literal dates.
@@ -283,8 +283,10 @@ ClickHouse-only printer behavior should not leak into Postgres or DuckDB printin
### Opt-In Simplification
-The simplifier is intentionally behind `HogQLContext.enable_type_aware_cast_simplification`.
+The simplifier is intentionally behind the `typeAwareCastSimplification` modifier and the `HogQLContext.enable_type_aware_cast_simplification` flag, both off by default.
Reviewers should reject changes that make those rewrites run globally without a separate rollout decision and stronger corpus coverage.
+`typeAwareCastSimplification` also has no explicit default in `set_default_modifier_values`.
+Query cache payloads serialize modifiers with `exclude_none=True, exclude_defaults=True`, so an explicit `False` would enter every cache key and invalidate the cache on deploy for no behavior change.
### Revenue Snapshot Coverage
diff --git a/docs/internal/hogql-type-system-todo.md b/docs/internal/hogql-type-system-todo.md
index 3c12435f3ccd..6bfb18fbea45 100644
--- a/docs/internal/hogql-type-system-todo.md
+++ b/docs/internal/hogql-type-system-todo.md
@@ -39,6 +39,7 @@ Completed in this branch:
- Added `posthog/hogql/type_diagnostics.py` with a typed-AST diagnostic helper and a function-catalog inventory helper that distinguishes missing legacy signatures from missing type inference.
- Added `posthog/hogql/transforms/type_aware_simplification.py` with an opt-in internal simplifier for conservative redundant casts and nullability wrappers.
- Added `HogQLContext.enable_type_aware_cast_simplification`, which keeps the simplifier disabled by default while letting internal callers exercise it.
+- Added the `typeAwareCastSimplification` query modifier, which makes the simplifier reachable in production per team via `team.modifiers` without a deploy, still off by default, with `hogql_type_simplification_total{dialect, kind}` counting removals during a pilot.
- Added emitted-SQL coverage showing typed string and URL helpers such as `base64Encode(...)` and `protocol(...)` no longer need manual `assumeNotNull(...)` to avoid defensive comparison wrapping.
- Added resolver binding for common higher-order array lambdas, so lambda parameters inherit element types from surrounding array arguments and `arrayMap(...)` can infer its return element type from the lambda body.
- Added parsed return-type inference for `JSONExtract(..., 'Type')`, including typed array results that feed higher-order lambda binding.
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 3e33f88c2a9e..ff02a58de14b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -26480,6 +26480,10 @@
"timings": {
"type": "boolean"
},
+ "typeAwareCastSimplification": {
+ "description": "Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types",
+ "type": "boolean"
+ },
"useMaterializedViews": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 62d33842da77..a9a793612c4a 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -492,6 +492,8 @@ export interface HogQLQueryModifiers {
usePreaggregatedTableTransforms?: boolean
usePreaggregatedIntermediateResults?: boolean
optimizeProjections?: boolean
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean
pushDownPredicates?: boolean
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
diff --git a/posthog/hogql/modifiers.py b/posthog/hogql/modifiers.py
index 8c9af2ce647f..79eec09ef02f 100644
--- a/posthog/hogql/modifiers.py
+++ b/posthog/hogql/modifiers.py
@@ -98,6 +98,12 @@ def set_default_modifier_values(modifiers: "HogQLQueryModifiers", team: "Team"):
if modifiers.optimizeJoinedFilters is None:
modifiers.optimizeJoinedFilters = False
+ # typeAwareCastSimplification deliberately gets no explicit default: None is falsy at the
+ # printer gate, stays out of the serialized cache payload (an explicit False would change every
+ # query's cache key on deploy for zero behavior change), and remains overridable per team via
+ # team.modifiers. Flipping the default on is a deliberate follow-up that carries the emitted-SQL
+ # snapshot churn for review.
+
if modifiers.bounceRatePageViewMode is None:
modifiers.bounceRatePageViewMode = BounceRatePageViewMode.COUNT_PAGEVIEWS
diff --git a/posthog/hogql/observability.py b/posthog/hogql/observability.py
index 95420cca28ce..875f1c99e052 100644
--- a/posthog/hogql/observability.py
+++ b/posthog/hogql/observability.py
@@ -111,6 +111,13 @@ OBSERVABILITY_ERRORS_TOTAL = PromCounter(
"Observability never propagates its own failures into query execution; this counter makes them visible.",
labelnames=["stage"],
)
+TYPE_SIMPLIFICATION_TOTAL = PromCounter(
+ "hogql_type_simplification_total",
+ "Operations removed or folded by the type-aware simplifier, by kind. Deliberately unsampled — "
+ "it only increments when typeAwareCastSimplification is enabled, so per-team pilot activity stays "
+ "visible despite the 1% sampling of the other type metrics.",
+ labelnames=["dialect", "kind"],
+)
def _log_observability_error(stage: str) -> None:
@@ -140,6 +147,20 @@ def _safe(fn: _F) -> _F:
return cast(_F, wrapper)
+_SIMPLIFICATION_KINDS = {
+ "redundant_cast",
+ "nullability_wrapper",
+ "null_fallback",
+ "constant_fold",
+ "json_fold",
+}
+
+
+@_safe
+def record_type_simplification(dialect: str, kind: str) -> None:
+ TYPE_SIMPLIFICATION_TOTAL.labels(dialect=_clean_tag(dialect), kind=_bounded(kind, _SIMPLIFICATION_KINDS)).inc()
+
+
_UNKNOWN_REASONS = {
"missing_function_signature",
"signature_mismatch",
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 6c581b225bc5..9f05c5d6ce8e 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -52,6 +52,7 @@ from posthog.hogql.database.models import DateDatabaseField, StringDatabaseField
from posthog.hogql.errors import ExposedHogQLError, ImpossibleASTError, QueryError
from posthog.hogql.escape_sql import escape_clickhouse_identifier, escape_clickhouse_string
from posthog.hogql.hogqlx import convert_tag_to_hx
+from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_and_print_ast, prepare_ast_for_printing, print_prepared_ast, to_printed_hogql
from posthog.hogql.property import property_to_expr
@@ -836,6 +837,38 @@ class TestPrinter(BaseTest):
),
)
+ @parameterized.expand([(True,), (False,)])
+ def test_type_aware_simplification_modifier_drives_prepare_pipeline(self, modifier_enabled: bool):
+ # The production rollout path: the typeAwareCastSimplification modifier (not the internal
+ # context flag) must reach the simplifier inside prepare_ast_for_printing.
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(typeAwareCastSimplification=modifier_enabled),
+ )
+ sql = self._select("SELECT assumeNotNull(1) AS a, toString('x') AS b FROM events", context)
+
+ if modifier_enabled:
+ assert "assumeNotNull(" not in sql
+ assert "toString(" not in sql
+ else:
+ assert "assumeNotNull(" in sql
+ assert "toString(" in sql
+
+ def test_type_aware_simplification_stays_off_via_production_default_modifiers(self):
+ # Tripwire for the default flip: this exercises the real default path
+ # (create_default_modifiers_for_team), so turning the simplifier on by default is forced to
+ # be a deliberate, reviewed change that updates this test.
+ context = HogQLContext(
+ team_id=self.team.pk,
+ enable_select_queries=True,
+ modifiers=create_default_modifiers_for_team(self.team),
+ )
+ sql = self._select("SELECT assumeNotNull(1) AS a, toString('x') AS b FROM events", context)
+
+ assert "assumeNotNull(" in sql
+ assert "toString(" in sql
+
def test_hogql_properties(self):
self.assertEqual(
self._expr("event", HogQLContext(team_id=self.team.pk), "hogql"),
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index fa61a57c4de7..6636ea9ed0a5 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -198,7 +198,9 @@ def prepare_ast_for_printing(
resolver_factory=resolver_factory,
)
- if context.enable_type_aware_cast_simplification:
+ # Modifier drives the production rollout (per-team override / staged default); the context flag
+ # remains as the direct opt-in for tests and internal callers.
+ if context.enable_type_aware_cast_simplification or context.modifiers.typeAwareCastSimplification:
with context.timings.measure("type_aware_cast_simplification"):
node = simplify_redundant_type_operations(node, context, dialect)
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.py
index 4e94ef0adb96..2739644c2960 100644
--- a/posthog/hogql/test/test_type_system.py
+++ b/posthog/hogql/test/test_type_system.py
@@ -1044,6 +1044,30 @@ class TestHogQLTypeSystem:
assert "1 AS d" in sql
assert "1 AS e" in sql
+ def test_type_aware_simplification_records_removal_metrics(self) -> None:
+ # The pilot rollout relies on hogql_type_simplification_total to see whether the simplifier
+ # fires at all; catch the instrumentation silently going dark while removals still happen.
+ from posthog.hogql.observability import TYPE_SIMPLIFICATION_TOTAL
+
+ def counter_value(kind: str) -> float:
+ return TYPE_SIMPLIFICATION_TOTAL.labels(dialect="clickhouse", kind=kind)._value.get()
+
+ kinds = ["redundant_cast", "nullability_wrapper", "null_fallback", "constant_fold"]
+ before = {kind: counter_value(kind) for kind in kinds}
+
+ resolved = cast(
+ ast.SelectQuery,
+ resolve_types(
+ self._select("SELECT toString('y') AS a, assumeNotNull(1) AS b, ifNull(1, 2) AS c, 1 + 2 AS d"),
+ self.context,
+ dialect="clickhouse",
+ ),
+ )
+ simplify_redundant_type_operations(resolved, self.context, dialect="clickhouse")
+
+ for kind in kinds:
+ assert counter_value(kind) == before[kind] + 1, kind
+
def test_type_aware_simplification_folds_safe_literal_arithmetic(self) -> None:
resolved = cast(
ast.SelectQuery,
diff --git a/posthog/hogql/transforms/type_aware_simplification.py b/posthog/hogql/transforms/type_aware_simplification.py
index 90adc7024d9e..45793681b330 100644
--- a/posthog/hogql/transforms/type_aware_simplification.py
+++ b/posthog/hogql/transforms/type_aware_simplification.py
@@ -10,6 +10,7 @@ from posthog.hogql import ast
from posthog.hogql.base import _T_AST
from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
+from posthog.hogql.observability import record_type_simplification
from posthog.hogql.type_system import (
RuntimeType,
constant_type_from_runtime_type,
@@ -93,36 +94,48 @@ class TypeAwareSimplifier(CloningVisitor):
source_type = runtime_type_from_constant_type(expr_type)
target_type = parse_sql_runtime_type(node.type_name, dialect=self.dialect)
if _is_redundant_cast(source_type=source_type, target_type=target_type):
+ self._record("redundant_cast")
return node.expr
folded_constant = _fold_constant_cast(node.expr, target_type, allow_numeric=False)
if folded_constant is not None:
+ self._record("constant_fold")
return folded_constant
return node
def visit_arithmetic_operation(self, node: ast.ArithmeticOperation) -> ast.Expr:
node = cast(ast.ArithmeticOperation, super().visit_arithmetic_operation(node))
- return (
- _fold_numeric_arithmetic_operation(node, self.context)
- or _fold_temporal_interval_arithmetic_operation(node)
- or node
+ folded = _fold_numeric_arithmetic_operation(node, self.context) or _fold_temporal_interval_arithmetic_operation(
+ node
)
+ if folded is not None:
+ self._record("constant_fold")
+ return folded
+ return node
def visit_call(self, node: ast.Call) -> ast.Expr:
node = cast(ast.Call, super().visit_call(node))
normalized_name = node.name.lower()
if normalized_name in {"assumenotnull", "tonullable"}:
- return self._simplify_nullability_call(node, normalized_name)
+ simplified = self._simplify_nullability_call(node, normalized_name)
+ if simplified is not node:
+ self._record("nullability_wrapper")
+ return simplified
if normalized_name in {"ifnull", "coalesce"}:
- return self._simplify_null_fallback_call(node, normalized_name)
+ simplified = self._simplify_null_fallback_call(node, normalized_name)
+ if simplified is not node:
+ self._record("null_fallback")
+ return simplified
folded_json = _fold_literal_json_call(node, self.dialect)
if folded_json is not None:
+ self._record("json_fold")
return folded_json
folded_conversion = _fold_constant_conversion_call(node, self.dialect)
if folded_conversion is not None:
+ self._record("constant_fold")
return folded_conversion
if len(node.args) != 1:
@@ -135,10 +148,14 @@ class TypeAwareSimplifier(CloningVisitor):
source_type = runtime_type_from_constant_type(arg_type)
target_type = _conversion_call_target_type(normalized_name, source_type)
if target_type is not None and _is_redundant_cast(source_type=source_type, target_type=target_type):
+ self._record("redundant_cast")
return node.args[0]
return node
+ def _record(self, kind: str) -> None:
+ record_type_simplification(self.dialect, kind)
+
def _simplify_nullability_call(self, node: ast.Call, normalized_name: str) -> ast.Expr:
if len(node.args) != 1:
return node
diff --git a/posthog/schema.py b/posthog/schema.py
index c1c2857c2a87..f1e980caedf0 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5137,6 +5137,14 @@ class HogQLQueryModifiers(BaseModel):
sessionTableVersion: SessionTableVersion | None = None
sessionsV2JoinMode: SessionsV2JoinMode | None = None
timings: bool | None = None
+ typeAwareCastSimplification: bool | None = Field(
+ default=None,
+ description=(
+ "Remove provably redundant casts and nullability wrappers (e.g."
+ " `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull`"
+ " fallbacks) using inferred expression types"
+ ),
+ )
useMaterializedViews: bool | None = None
usePreaggregatedIntermediateResults: bool | None = None
usePreaggregatedTableTransforms: bool | None = Field(
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 48902479d908..f095b2f170c8 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1219,6 +1219,8 @@ export interface HogQLQueryModifiersApi {
sessionTableVersion?: SessionTableVersionApi | null
sessionsV2JoinMode?: SessionsV2JoinModeApi | null
timings?: boolean | null
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 801c5ff1c9f9..819ee803af0a 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -512,6 +512,8 @@ export interface HogQLQueryModifiersApi {
sessionTableVersion?: SessionTableVersionApi | null
sessionsV2JoinMode?: SessionsV2JoinModeApi | null
timings?: boolean | null
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean | null
useMaterializedViews?: boolean | null
usePreaggregatedIntermediateResults?: boolean | null
/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ab66dee2a1e9..2c41fbf072b0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -666,6 +666,8 @@ export namespace Schemas {
sessionTableVersion?: SessionTableVersion | null;
sessionsV2JoinMode?: SessionsV2JoinMode | null;
timings?: boolean | null;
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean | null;
useMaterializedViews?: boolean | null;
usePreaggregatedIntermediateResults?: boolean | null;
/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */