: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
chore(devex): use match statements where dispatch reads clearer (#83663)
Arno Hillendbebffacb300
diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.pyindex 0ba511667090..4987867e27d8 100644--- a/posthog/hogql/resolver_utils.py+++ b/posthog/hogql/resolver_utils.py@@ -209,26 +209,28 @@ def lookup_cte_by_name(global_scopes: list[ast.SelectQueryType], name: str) -> Odef get_long_table_name(select: ast.SelectQueryType, type: ast.Type) -> str:- if isinstance(type, ast.TableType):- return select.get_alias_for_table_type(type) or ""- elif isinstance(type, ast.LazyTableType):- return type.table.to_printed_hogql()- elif isinstance(type, (ast.TableAliasType, ast.ColumnAliasedTableType)):- return type.alias- elif isinstance(type, ast.SelectQueryAliasType):- return type.alias- elif isinstance(type, ast.SelectViewType):- return type.alias- elif isinstance(type, ast.CTETableType):- return type.name- elif isinstance(type, ast.CTETableAliasType):- return type.alias- elif isinstance(type, ast.LazyJoinType):- return f"{get_long_table_name(select, type.table_type)}__{type.field}"- elif isinstance(type, ast.VirtualTableType):- return f"{get_long_table_name(select, type.table_type)}__{type.field}"- else:- raise ResolutionError(f"Unknown table type in LazyTableResolver: {type.__class__.__name__}")+ match type:+ case ast.TableType():+ return select.get_alias_for_table_type(type) or ""+ case ast.LazyTableType(table=table):+ return table.to_printed_hogql()+ case (+ ast.TableAliasType(alias=alias)+ | ast.ColumnAliasedTableType(alias=alias)+ | ast.SelectQueryAliasType(alias=alias)+ | ast.SelectViewType(alias=alias)+ | ast.CTETableAliasType(alias=alias)+ ):+ return alias+ case ast.CTETableType(name=name):+ return name+ case (+ ast.LazyJoinType(table_type=table_type, field=field)+ | ast.VirtualTableType(table_type=table_type, field=field)+ ):+ return f"{get_long_table_name(select, table_type)}__{field}"+ case _:+ raise ResolutionError(f"Unknown table type in LazyTableResolver: {type.__class__.__name__}")def ast_to_query_node(expr: ast.Expr | ast.HogQLXTag):diff --git a/posthog/hogql/transforms/preaggregated_table_transformation.py b/posthog/hogql/transforms/preaggregated_table_transformation.pyindex 3503c7773b67..d935819225e6 100644--- a/posthog/hogql/transforms/preaggregated_table_transformation.py+++ b/posthog/hogql/transforms/preaggregated_table_transformation.py@@ -273,47 +273,42 @@ def _get_supported_field(field: ast.Field) -> tuple[str, ast.Field] | None:"""Check if a field represents a supported property and return (property_name, field) if valid."""- # Handle properties.x pattern- if len(field.chain) == 2 and field.chain[0] == "properties":- property_name = field.chain[1]- if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))-- # Handle properties.metadata.x pattern (for nested properties like metadata.loggedIn)- elif len(field.chain) == 3 and field.chain[0] == "properties":- property_name = f"{field.chain[1]}.{field.chain[2]}"- if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))-- # Handle events.properties.x pattern- elif len(field.chain) == 3 and field.chain[0] == "events" and field.chain[1] == "properties":- property_name = field.chain[2]- if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))-- # Handle events.properties.metadata.x pattern (for nested properties like metadata.loggedIn)- elif len(field.chain) == 4 and field.chain[0] == "events" and field.chain[1] == "properties":- property_name = f"{field.chain[2]}.{field.chain[3]}"- if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))-- # Handle session.x pattern- elif len(field.chain) == 2 and field.chain[0] == "session":- property_name = field.chain[1]- if isinstance(property_name, str) and property_name in SESSION_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[SESSION_PROPERTY_TO_FIELD[property_name]]))-- # Handle events.session.x pattern- elif len(field.chain) == 3 and field.chain[0] == "events" and field.chain[1] == "session":- property_name = field.chain[2]- if isinstance(property_name, str) and property_name in SESSION_PROPERTY_TO_FIELD:- return (property_name, ast.Field(chain=[SESSION_PROPERTY_TO_FIELD[property_name]]))-- # Handle team_id and events.team_id- elif (len(field.chain) == 1 and field.chain[0] == "team_id") or (- len(field.chain) == 2 and field.chain[1] == "team_id"- ):- return ("team_id", ast.Field(chain=["team_id"]))+ match field.chain:+ # Handle properties.x pattern+ case ["properties", property_name]:+ if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))++ # Handle properties.metadata.x pattern (for nested properties like metadata.loggedIn)+ case ["properties", parent, child]:+ property_name = f"{parent}.{child}"+ if property_name in EVENT_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))++ # Handle events.properties.x pattern+ case ["events", "properties", property_name]:+ if isinstance(property_name, str) and property_name in EVENT_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))++ # Handle events.properties.metadata.x pattern (for nested properties like metadata.loggedIn)+ case ["events", "properties", parent, child]:+ property_name = f"{parent}.{child}"+ if property_name in EVENT_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[EVENT_PROPERTY_TO_FIELD[property_name]]))++ # Handle session.x pattern+ case ["session", property_name]:+ if isinstance(property_name, str) and property_name in SESSION_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[SESSION_PROPERTY_TO_FIELD[property_name]]))++ # Handle events.session.x pattern+ case ["events", "session", property_name]:+ if isinstance(property_name, str) and property_name in SESSION_PROPERTY_TO_FIELD:+ return (property_name, ast.Field(chain=[SESSION_PROPERTY_TO_FIELD[property_name]]))++ # Handle team_id and events.team_id+ case ["team_id"] | [_, "team_id"]:+ return ("team_id", ast.Field(chain=["team_id"]))return Nonediff --git a/posthog/hogql_queries/utils/formula_ast.py b/posthog/hogql_queries/utils/formula_ast.pyindex 8f71ae2b9055..2faeee4322b5 100644--- a/posthog/hogql_queries/utils/formula_ast.py+++ b/posthog/hogql_queries/utils/formula_ast.py@@ -30,76 +30,76 @@ class FormulaAST:return resdef _evaluate(self, node, const_map: dict[str, Any]):- if isinstance(node, list | tuple):- return [self._evaluate(sub_node, const_map) for sub_node in node]+ match node:+ case list() | tuple():+ return [self._evaluate(sub_node, const_map) for sub_node in node]- elif isinstance(node, str):- return self._evaluate(ast.parse(node), const_map)+ case str():+ return self._evaluate(ast.parse(node), const_map)- elif isinstance(node, ast.Module):- values = []- for body in node.body:- values.append(self._evaluate(body, const_map))- if len(values) == 1:- values = values[0]- return values+ case ast.Module(body=body):+ values = []+ for sub_node in body:+ values.append(self._evaluate(sub_node, const_map))+ if len(values) == 1:+ values = values[0]+ return values- elif isinstance(node, ast.Expr):- return self._evaluate(node.value, const_map)+ case ast.Expr(value=value):+ return self._evaluate(value, const_map)- elif isinstance(node, ast.BinOp):- left = self._evaluate(node.left, const_map)- op = node.op- right = self._evaluate(node.right, const_map)- # Handle None values that may come from empty query results- if left is None:- left = 0- if right is None:- right = 0- try:- return self.op_map[type(op)](left, right)- except ZeroDivisionError:- return 0- except KeyError:+ case ast.BinOp(left=left_node, op=op, right=right_node):+ left = self._evaluate(left_node, const_map)+ right = self._evaluate(right_node, const_map)+ # Handle None values that may come from empty query results+ if left is None:+ left = 0+ if right is None:+ right = 0+ try:+ return self.op_map[type(op)](left, right)+ except ZeroDivisionError:+ return 0+ except KeyError:+ raise ExposedHogQLError(+ f"Formulas only support arithmetic ( + - * / % ** ) between series, not {op.__class__.__name__}"+ )++ case ast.UnaryOp(op=unary_op, operand=operand_node):+ operand = self._evaluate(operand_node, const_map)+ # Handle None values that may come from empty query results+ if operand is None:+ operand = 0+ if isinstance(unary_op, ast.USub):+ return -operand+ elif isinstance(unary_op, ast.UAdd):+ return operandraise ExposedHogQLError(- f"Formulas only support arithmetic ( + - * / % ** ) between series, not {op.__class__.__name__}"+ f"Formulas only support arithmetic ( + - * / % ** ) between series, not {unary_op.__class__.__name__}")- elif isinstance(node, ast.UnaryOp):- operand = self._evaluate(node.operand, const_map)- # Handle None values that may come from empty query results- if operand is None:- operand = 0- unary_op = node.op- if isinstance(unary_op, ast.USub):- return -operand- elif isinstance(unary_op, ast.UAdd):- return operand- raise ExposedHogQLError(- f"Formulas only support arithmetic ( + - * / % ** ) between series, not {unary_op.__class__.__name__}"- )+ case ast.Constant(value=int() | float() as value) if not isinstance(value, bool):+ return value- elif (- isinstance(node, ast.Constant) and isinstance(node.value, int | float) and not isinstance(node.value, bool)- ):- return node.value+ case ast.Name(id=name):+ try:+ return const_map[name]+ except KeyError:+ available = sorted(k.upper() for k in const_map if k.isalpha() and len(k) == 1)+ series_word = "series is" if len(available) == 1 else "series are"+ raise ExposedHogQLError(+ f"Formula references series {name.upper()}, "+ f"but only {len(available)} {series_word} defined ({', '.join(available) or 'none'})"+ )- elif isinstance(node, ast.Name):- try:- return const_map[node.id]- except KeyError:- available = sorted(k.upper() for k in const_map if k.isalpha() and len(k) == 1)- series_word = "series is" if len(available) == 1 else "series are"+ case ast.Call(func=func):+ called = f"{func.id.upper()}()" if isinstance(func, ast.Name) else "function calls"raise ExposedHogQLError(- f"Formula references series {node.id.upper()}, "- f"but only {len(available)} {series_word} defined ({', '.join(available) or 'none'})"+ f"Formulas only support arithmetic between series (like (A + B) / 2), not {called}. "+ f"To aggregate a series, set its measurement (for example median or p95) on the series itself.")- elif isinstance(node, ast.Call):- called = f"{node.func.id.upper()}()" if isinstance(node.func, ast.Name) else "function calls"- raise ExposedHogQLError(- f"Formulas only support arithmetic between series (like (A + B) / 2), not {called}. "- f"To aggregate a series, set its measurement (for example median or p95) on the series itself."- )-- raise ExposedHogQLError(f"Formulas only support arithmetic between series, not {node.__class__.__name__}")+ case _:+ raise ExposedHogQLError(+ f"Formulas only support arithmetic between series, not {node.__class__.__name__}"+ )diff --git a/posthog/hogql_queries/utils/timestamp_utils.py b/posthog/hogql_queries/utils/timestamp_utils.pyindex c2f9ab3e50ae..78ebfb98fbe7 100644--- a/posthog/hogql_queries/utils/timestamp_utils.py+++ b/posthog/hogql_queries/utils/timestamp_utils.py@@ -111,26 +111,27 @@ def _get_earliest_timestamp_cache_key(:param node: The series node (optional). If None, returns team-level global cache key.:return: A string representing the cache key."""- if node is None:- # Global team-level earliest timestamp (for "all time" date filter)- # Use the same cache key as EventsNode(event=None) since they return the same result- return f"earliest_timestamp_event_{team.pk}"- elif isinstance(node, DataWarehouseNode):- return f"earliest_timestamp_data_warehouse_{team.pk}_{node.table_name}_{node.timestamp_field}"- elif isinstance(node, FunnelsDataWarehouseNode):- return f"earliest_timestamp_funnels_data_warehouse_{team.pk}_{node.table_name}_{node.timestamp_field}"- elif isinstance(node, LifecycleDataWarehouseNode):- return f"earliest_timestamp_lifecycle_data_warehouse_{team.pk}_{node.table_name}_{node.timestamp_field}"- elif isinstance(node, ActionsNode):- return f"earliest_timestamp_action_{team.pk}_{node.id}"- elif isinstance(node, EventsNode):- # node.event can be None, meaning "any event" (no event filter in WHERE clause)- # This is the same as the global team earliest- if node.event is not None:- return f"earliest_timestamp_event_{team.pk}_{node.event}"- return f"earliest_timestamp_event_{team.pk}"- else:- raise ValueError(f"Unsupported node type: {type(node)}")+ match node:+ case None:+ # Global team-level earliest timestamp (for "all time" date filter)+ # Use the same cache key as EventsNode(event=None) since they return the same result+ return f"earliest_timestamp_event_{team.pk}"+ case DataWarehouseNode(table_name=table_name, timestamp_field=timestamp_field):+ return f"earliest_timestamp_data_warehouse_{team.pk}_{table_name}_{timestamp_field}"+ case FunnelsDataWarehouseNode(table_name=table_name, timestamp_field=timestamp_field):+ return f"earliest_timestamp_funnels_data_warehouse_{team.pk}_{table_name}_{timestamp_field}"+ case LifecycleDataWarehouseNode(table_name=table_name, timestamp_field=timestamp_field):+ return f"earliest_timestamp_lifecycle_data_warehouse_{team.pk}_{table_name}_{timestamp_field}"+ case ActionsNode(id=action_id):+ return f"earliest_timestamp_action_{team.pk}_{action_id}"+ case EventsNode(event=None):+ # node.event can be None, meaning "any event" (no event filter in WHERE clause)+ # This is the same as the global team earliest+ return f"earliest_timestamp_event_{team.pk}"+ case EventsNode(event=event):+ return f"earliest_timestamp_event_{team.pk}_{event}"+ case _:+ raise ValueError(f"Unsupported node type: {type(node)}")def _coerce_to_datetime(value: Any, tz: tzinfo) -> datetime:diff --git a/products/ai_observability/backend/text_repr/formatters/message_formatter.py b/products/ai_observability/backend/text_repr/formatters/message_formatter.pyindex 7262be50b4e2..bfc09f7a0773 100644--- a/products/ai_observability/backend/text_repr/formatters/message_formatter.py+++ b/products/ai_observability/backend/text_repr/formatters/message_formatter.py@@ -256,15 +256,11 @@ def extract_tool_calls_from_content(content: Any) -> list[ToolCall]:tool_calls: list[ToolCall] = []for block in content:- if isinstance(block, dict):+ match block:# Handle tool-call format: { type: "tool-call", function: {...} }- if block.get("type") == "tool-call" and "function" in block:- if isinstance(block["function"], dict):- tool_calls.append({"function": block["function"]})- # Handle Anthropic function format: { type: "function", function: {...} }- elif block.get("type") == "function" and "function" in block:- if isinstance(block["function"], dict):- tool_calls.append({"function": block["function"]})+ # and Anthropic function format: { type: "function", function: {...} }+ case {"type": "tool-call" | "function", "function": dict() as function}:+ tool_calls.append({"function": function})return tool_calls