: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(hogql): add toIntOrDefault conversion function (#69745)
George Munyoro68fa5cbb7c0c
diff --git a/posthog/hogql/functions/clickhouse/conversions.py b/posthog/hogql/functions/clickhouse/conversions.pyindex eb54f72998af..b99b18777a17 100644--- a/posthog/hogql/functions/clickhouse/conversions.py+++ b/posthog/hogql/functions/clickhouse/conversions.py@@ -41,6 +41,29 @@ TYPE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"accurateCastOrNull": HogQLFunctionMeta("accurateCastOrNull", 2, 2),"toInt": HogQLFunctionMeta("accurateCastOrNull", 1, 1, suffix_args=[ast.Constant(value="Int64")]),"toIntOrZero": HogQLFunctionMeta("toInt64OrZero", 1, 1, signatures=[((StringType(),), IntegerType())]),+ "toIntOrDefault": HogQLFunctionMeta(+ # Mirror of toFloatOrDefault: ClickHouse's toInt64OrDefault requires the default value to+ # already be Int64, so cast it (any numeric/string literal then works). The 1-arg form is+ # degenerate (equivalent to toIntOrZero) and is rewritten in the printer before the+ # placeholder template renders.+ # Defaults are Integer only: accurateCast of a fractional float (e.g. 0.5) to Int64 throws+ # at runtime, so unlike toFloatOrDefault we don't accept Float-typed defaults.+ "toInt64OrDefault({0}, accurateCast({1}, 'Int64'))",+ 1,+ 2,+ using_placeholder_arguments=True,+ using_positional_arguments=True,+ signatures=[+ ((DecimalType(),), IntegerType()),+ ((IntegerType(),), IntegerType()),+ ((FloatType(),), IntegerType()),+ ((StringType(),), IntegerType()),+ ((DecimalType(), IntegerType()), IntegerType()),+ ((IntegerType(), IntegerType()), IntegerType()),+ ((FloatType(), IntegerType()), IntegerType()),+ ((StringType(), IntegerType()), IntegerType()),+ ],+ ),"_toInt8": HogQLFunctionMeta("toInt8", 1, 1),"_toInt16": HogQLFunctionMeta("toInt16", 1, 1),"_toInt32": HogQLFunctionMeta("toInt32", 1, 1),diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.pyindex 6aea40f6c614..887439ab0576 100644--- a/posthog/hogql/printer/base.py+++ b/posthog/hogql/printer/base.py@@ -991,10 +991,12 @@ class BasePrinter(Visitor[str]):# Handle format strings in function names before checking function type# HogQL preserves the macro in its original shape; SQL dialects expand it.if func_meta.using_placeholder_arguments and self._expands_placeholder_macros():- # Pre-#58714 behavior: single-arg toFloatOrDefault was degenerate and- # equivalent to toFloatOrZero. Rewrite here so saved queries still work.- if node.name == "toFloatOrDefault" and len(node.args) == 1:- return self.visit(ast.Call(name="toFloatOrZero", args=node.args))+ # The single-arg form of these is degenerate (equivalent to toFloatOrZero/toIntOrZero).+ # For toFloatOrDefault this is pre-#58714 behavior kept so old saved queries still print;+ # toIntOrDefault is new but made degenerate the same way for parity.+ if len(node.args) == 1 and node.name in ("toFloatOrDefault", "toIntOrDefault"):+ zero_fn = "toFloatOrZero" if node.name == "toFloatOrDefault" else "toIntOrZero"+ return self.visit(ast.Call(name=zero_fn, args=node.args))return self._render_placeholder_macro(node=node,clickhouse_name=func_meta.clickhouse_name,diff --git a/posthog/hogql/printer/mysql_functions.py b/posthog/hogql/printer/mysql_functions.pyindex 778a969b6d31..1e358f18689a 100644--- a/posthog/hogql/printer/mysql_functions.py+++ b/posthog/hogql/printer/mysql_functions.py@@ -225,6 +225,7 @@ MYSQL_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"toString": _make_cast_handler("CHAR"),"toInt": _make_cast_handler("SIGNED"),"toIntOrZero": _make_cast_handler("SIGNED"),+ "toIntOrDefault": _make_cast_handler("SIGNED"),"toFloat": _make_cast_handler("DOUBLE"),"toFloatOrZero": _make_cast_handler("DOUBLE"),# MySQL backend intentionally drops the default arg — the handler only uses args[0],diff --git a/posthog/hogql/printer/postgres_functions.py b/posthog/hogql/printer/postgres_functions.pyindex 08193c31da48..8984bb745ae7 100644--- a/posthog/hogql/printer/postgres_functions.py+++ b/posthog/hogql/printer/postgres_functions.py@@ -209,6 +209,7 @@ POSTGRES_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"toFloat": _make_cast_handler("DOUBLE PRECISION"),"toFloatOrZero": _make_cast_handler("DOUBLE PRECISION"),"toIntOrZero": _make_cast_handler("BIGINT"),+ "toIntOrDefault": _make_cast_handler("BIGINT"),"toBool": _make_cast_handler("BOOLEAN"),"toUUID": _make_cast_handler("UUID"),# Date extractiondiff --git a/posthog/hogql/printer/snowflake_functions.py b/posthog/hogql/printer/snowflake_functions.pyindex d0d8f7c4e280..396ab6ec3ccf 100644--- a/posthog/hogql/printer/snowflake_functions.py+++ b/posthog/hogql/printer/snowflake_functions.py@@ -180,6 +180,7 @@ SNOWFLAKE_FUNCTION_HANDLERS: dict[str, Callable[[list[str]], str]] = {"toString": _make_cast_handler("VARCHAR"),"toInt": _make_cast_handler("BIGINT"),"toIntOrZero": _make_cast_handler("BIGINT"),+ "toIntOrDefault": _make_cast_handler("BIGINT"),"toFloat": _make_cast_handler("DOUBLE"),"toFloatOrZero": _make_cast_handler("DOUBLE"),"toFloatOrDefault": _make_cast_handler("DOUBLE"),diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 6319778f9f41..c95f9025511e 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -1075,34 +1075,39 @@ class TestPrinter(BaseTest):self._test_property_group_comparison("properties.key in (lower('a'), lower('b'))", None)def test_event_property_groups_optimized_in_query_results(self):+ # Unique event name so the query below sees only this test's events. Postgres teams roll back+ # between tests but ClickHouse events don't, so a reused team_id can carry foreign events from+ # another test class into an un-scoped `FROM events` query (a null-valued one polluted the+ # `value IN (NULL)` case in CI).+ event_name = "property_groups_result_test"_create_event(team=self.team,distinct_id="distinct_id",- event="event",+ event=event_name,properties={"label": "string", "value": "s"},)_create_event(team=self.team,distinct_id="distinct_id",- event="event",+ event=event_name,properties={"label": "empty_string", "value": ""},)_create_event(team=self.team,distinct_id="distinct_id",- event="event",+ event=event_name,properties={"label": "null", "value": None},)_create_event(team=self.team,distinct_id="distinct_id",- event="event",+ event=event_name,properties={"label": "not_set"},)_create_event(team=self.team,distinct_id="distinct_id",- event="event",+ event=event_name,properties={"label": "int", "value": 1},)@@ -1117,8 +1122,8 @@ class TestPrinter(BaseTest):hogql_expr = parse_expr(expr)query = parse_select(- "select properties.label as label from events where properties.value in {expr} order by label asc",- placeholders={"expr": hogql_expr},+ "select properties.label as label from events where event = {event} and properties.value in {expr} order by label asc",+ placeholders={"expr": hogql_expr, "event": ast.Constant(value=event_name)},)disabled_context = HogQLContext(@@ -6620,6 +6625,7 @@ class TestPostgresPrinter(BaseTest):("toFloatOrZero", "toFloatOrZero('1.5')", "CAST(%(hogql_val_0)s AS DOUBLE PRECISION)"),("toFloatOrDefault", "toFloatOrDefault('1.5', 0)", "CAST(%(hogql_val_0)s AS DOUBLE PRECISION)"),("toIntOrZero", "toIntOrZero('42')", "CAST(%(hogql_val_0)s AS BIGINT)"),+ ("toIntOrDefault", "toIntOrDefault('42', 0)", "CAST(%(hogql_val_0)s AS BIGINT)"),("toBool", "toBool(1)", "CAST(1 AS BOOLEAN)"),("toUUID", "toUUID('abc')", "CAST(%(hogql_val_0)s AS UUID)"),("toDecimal", "toDecimal(1, 2)", "CAST(1 AS DECIMAL)"),diff --git a/posthog/hogql/test/test_mapping.py b/posthog/hogql/test/test_mapping.pyindex bc9efcbf33dc..d78600f10ff6 100644--- a/posthog/hogql/test/test_mapping.py+++ b/posthog/hogql/test/test_mapping.py@@ -326,6 +326,35 @@ class TestMappings(ClickhouseTestMixin, BaseTest):assert response.results is not Noneassert response.results[0] == (2.5, 0.0, None)+ def test_to_int_or_default_function_mapping(self):+ # Mirror of toFloatOrDefault for integers. Proves toIntOrDefault exists and executes on+ # ClickHouse: the Int64 default cast lets an integer default literal work, and empty /+ # unparseable / NULL inputs fall back to the default. The wrapping coalesce confirms the+ # call resolves to a known Integer type (an UnknownType would break nesting).+ response = execute_hogql_query(+ """+ SELECT+ toIntOrDefault(3, 7),+ toIntOrDefault('42', 7),+ toIntOrDefault('', 7),+ toIntOrDefault('bla', 7),+ toIntOrDefault(NULL, 7),+ coalesce(toIntOrDefault('bla', 0), 1)+ """,+ self.team,+ )+ assert response.results is not None+ assert response.results[0] == (3, 42, 7, 7, 7, 0)++ def test_to_int_or_default_single_arg(self):+ # Single-arg form is degenerate (equivalent to toIntOrZero), rewritten in the printer.+ response = execute_hogql_query(+ "SELECT toIntOrDefault('42'), toIntOrDefault('bla'), toIntOrDefault(NULL)",+ self.team,+ )+ assert response.results is not None+ assert response.results[0] == (42, 0, None)+def test_map_function_with_multiple_key_value_pairs(self):"""Test that the map function accepts multiple key-value pairs."""response = execute_hogql_query(diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex 90e81ef3f8bc..b7f75256b3d8 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -210,11 +210,11 @@ class PropertySwapper(CloningVisitor):}# ClickHouse string-parsing conversions (toFloat64OrZero, toInt64OrZero,- # toFloat64OrDefault) require a String first argument and raise+ # toFloat64OrDefault, toInt64OrDefault) require a String first argument and raise# ILLEGAL_TYPE_OF_ARGUMENT on numeric input. When a user explicitly wraps a# Numeric-typed property in one of these, we must not auto-convert the property- # to Float — the raw String value has to flow through for the parser to work.- _STRING_INPUT_CONVERSIONS: set[str] = {"toFloatOrZero", "toIntOrZero", "toFloatOrDefault"}+ # to Float, the raw String value has to flow through for the parser to work.+ _STRING_INPUT_CONVERSIONS: set[str] = {"toFloatOrZero", "toIntOrZero", "toFloatOrDefault", "toIntOrDefault"}def __init__(self,diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 2d7ca582578d..07b1f6fd40e8 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -444,6 +444,7 @@ class TestPropertyTypes(BaseTest):("to_float_or_zero", "toFloatOrZero(properties.$screen_width)", "toFloat64OrZero"),("to_int_or_zero", "toIntOrZero(properties.$screen_width)", "toInt64OrZero"),("to_float_or_default", "toFloatOrDefault(properties.$screen_width, 0)", "toFloat64OrDefault"),+ ("to_int_or_default", "toIntOrDefault(properties.$screen_width, 0)", "toInt64OrDefault"),])def test_numeric_property_not_double_cast_inside_string_parser(self, _name: str, expr: str, ch_fn: str):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.ambrindex 556458b4f365..cc6c9a7ec1b9 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@@ -65,7 +65,7 @@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:```- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'toTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'toTypeName', 'cityHash64', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']```These are the aggregated HogQL functions:diff --git a/products/signals/skills/signals-scout-ai-observability/references/lenses.md b/products/signals/skills/signals-scout-ai-observability/references/lenses.mdindex b2158731dea8..402afc5926fe 100644--- a/products/signals/skills/signals-scout-ai-observability/references/lenses.md+++ b/products/signals/skills/signals-scout-ai-observability/references/lenses.md@@ -25,7 +25,7 @@ queries for anything more):- The `$ai_*` numeric properties sit in a **typed property group**, so guard themnumerically — filter `properties.$ai_latency > 0` (a `!= ''` guard triggers a float-casterror) and aggregate them directly: `quantile(0.9)(properties.$ai_latency)`, no `toFloat`.-- HogQL has `toFloatOrDefault` / `toIntOrDefault`, **not** `toFloatOrNull`.+- Parse the numeric properties with a fallback via `toFloatOrDefault` / `toIntOrDefault`.- `$ai_tools_called` is a **comma-joined string**, not a JSON array —`arrayJoin(splitByChar(',', properties.$ai_tools_called))` to tally tool usage.- Not every team emits `$ai_embedding` (the dogfood project doesn't); including it in cost