Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(mql): Support groupby parsing for formula join queries #6077

Merged
merged 7 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions snuba/query/mql/parser_supported_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,10 +746,16 @@ def find_all_leaf_nodes(tree: FormulaParameter) -> list[InitialParseResult] | No
if join_nodes is None:
raise InvalidQueryException("Could not parse formula")

# We use the group by for the ON conditions, so make sure they are all the same
# Since the groupby is used in the ON conditions, they should all the same.
# However, we do support onesided groupbys in a formula. This is the time spent percentage use-case.
# Example: sum(`transactions.duration`) by transaction / sum(`transactions.duration`)
groupbys = join_nodes[0].groupby
if not all(node.groupby == groupbys for node in join_nodes):
raise InvalidQueryException("All terms in a formula must have the same groupby")
for node in join_nodes:
if node.groupby is not None:
if node.groupby != groupbys:
raise InvalidQueryException(
"All terms in a formula must have the same groupby"
)

entity_keys = [select_entity(node.mri or "", dataset) for node in join_nodes]
if len(entity_keys) == 1:
Expand Down Expand Up @@ -890,10 +896,16 @@ def extract_expression(param: InitialParseResult | Any) -> Expression:
if leaf_node.groupby:
for group_exp in leaf_node.groupby:
if isinstance(group_exp.expression, Column):
alias: Optional[str]
if alias_wrap(leaf_node.table_alias):
alias = f"{alias_wrap(leaf_node.table_alias)}.{group_exp.expression.alias}"
else:
alias = group_exp.expression.alias
aliased_groupby = replace(
group_exp,
expression=replace(
group_exp.expression,
alias=alias,
table_name=alias_wrap(leaf_node.table_alias),
),
)
Expand All @@ -902,7 +914,6 @@ def extract_expression(param: InitialParseResult | Any) -> Expression:

if groupby:
query.set_ast_groupby(groupby)

query.set_ast_selected_columns(selected_columns)

# Go through all the conditions, populate the conditions with the table alias, add them to the query conditions
Expand Down
224 changes: 224 additions & 0 deletions tests/query/parser/test_formula_mql_query.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import re
from datetime import datetime

import pytest

from snuba.datasets.entities.entity_key import EntityKey
from snuba.datasets.entities.factory import get_entity
from snuba.datasets.factory import get_dataset
Expand Down Expand Up @@ -45,6 +48,18 @@ def time_expression(table_alias: str | None = None) -> FunctionCall:
)


def subscriptable_expression(
tag_key: str, table_alias: str | None = None
) -> SubscriptableReference:
return SubscriptableReference(
alias=f"_snuba_tags_raw[{tag_key}]",
column=Column(
alias="_snuba_tags_raw", table_name=table_alias, column_name="tags_raw"
),
key=Literal(alias=None, value=tag_key),
)


def condition(table_alias: str | None = None) -> list[FunctionCall]:
conditions = [
binary_condition(
Expand Down Expand Up @@ -622,3 +637,212 @@ def test_formula_with_scalar() -> None:
query = parse_mql_query_new(str(query_body), mql_context, generic_metrics)
eq, reason = query.equals(expected)
assert eq, reason


def test_groupby() -> None:
query_body = "sum(`d:transactions/duration@millisecond`){status_code:200} by transaction / sum(`d:transactions/duration@millisecond`) by transaction"

expected_selected = SelectedExpression(
"aggregate_value",
divide(
FunctionCall(
None,
"sum",
(Column("_snuba_value", "d0", "value"),),
),
FunctionCall(
None,
"sum",
(Column("_snuba_value", "d1", "value"),),
),
"_snuba_aggregate_value",
),
)

join_clause = JoinClause(
left_node=IndividualNode(
alias="d1",
data_source=from_distributions,
),
right_node=IndividualNode(
alias="d0",
data_source=from_distributions,
),
keys=[
JoinCondition(
left=JoinConditionExpression(table_alias="d1", column="transaction"),
right=JoinConditionExpression(table_alias="d0", column="transaction"),
),
JoinCondition(
left=JoinConditionExpression(table_alias="d1", column="time"),
right=JoinConditionExpression(table_alias="d0", column="time"),
),
],
join_type=JoinType.INNER,
join_modifier=None,
)

tag_condition = binary_condition(
"equals", tag_column("status_code", "d0"), Literal(None, "200")
)
metric_condition1 = metric_id_condition(123456, "d0")
metric_condition2 = metric_id_condition(123456, "d1")
formula_condition = combine_and_conditions(
condition("d0")
+ condition("d1")
+ [tag_condition, metric_condition1, metric_condition2]
)

expected = CompositeQuery(
from_clause=join_clause,
selected_columns=[
expected_selected,
SelectedExpression(
"transaction",
subscriptable_expression("333333", "d0"),
),
SelectedExpression(
"transaction",
subscriptable_expression("333333", "d1"),
),
SelectedExpression(
"time",
time_expression("d1"),
),
SelectedExpression(
"time",
time_expression("d0"),
),
],
groupby=[
subscriptable_expression("333333", "d0"),
subscriptable_expression("333333", "d1"),
time_expression("d1"),
time_expression("d0"),
],
condition=formula_condition,
order_by=[
OrderBy(
direction=OrderByDirection.ASC,
expression=time_expression("d0"),
),
],
limit=1000,
offset=0,
)

generic_metrics = get_dataset(
"generic_metrics",
)
query = parse_mql_query_new(str(query_body), mql_context, generic_metrics)
eq, reason = query.equals(expected)
assert eq, reason


def test_mismatch_groupby() -> None:
query_body = "sum(`d:transactions/duration@millisecond`){status_code:200} by transaction / sum(`d:transactions/duration@millisecond`) by status_code"
generic_metrics = get_dataset(
"generic_metrics",
)
with pytest.raises(
Exception,
match=re.escape("All terms in a formula must have the same groupby"),
):
parse_mql_query_new(str(query_body), mql_context, generic_metrics)


def test_onesided_groupby() -> None:
query_body = "sum(`d:transactions/duration@millisecond`){status_code:200} by transaction / sum(`d:transactions/duration@millisecond`)"
expected_selected = SelectedExpression(
"aggregate_value",
divide(
FunctionCall(
None,
"sum",
(Column("_snuba_value", "d0", "value"),),
),
FunctionCall(
None,
"sum",
(Column("_snuba_value", "d1", "value"),),
),
"_snuba_aggregate_value",
),
)

join_clause = JoinClause(
left_node=IndividualNode(
alias="d1",
data_source=from_distributions,
),
right_node=IndividualNode(
alias="d0",
data_source=from_distributions,
),
keys=[
JoinCondition(
left=JoinConditionExpression(table_alias="d1", column="time"),
right=JoinConditionExpression(table_alias="d0", column="time"),
),
],
join_type=JoinType.INNER,
join_modifier=None,
)

tag_condition = binary_condition(
"equals", tag_column("status_code", "d0"), Literal(None, "200")
)
metric_condition1 = metric_id_condition(123456, "d0")
metric_condition2 = metric_id_condition(123456, "d1")
formula_condition = combine_and_conditions(
condition("d0")
+ condition("d1")
+ [tag_condition, metric_condition1, metric_condition2]
)

expected = CompositeQuery(
from_clause=join_clause,
selected_columns=[
expected_selected,
SelectedExpression(
"transaction",
subscriptable_expression("333333", "d0"),
),
SelectedExpression(
"time",
time_expression("d1"),
),
SelectedExpression(
"time",
time_expression("d0"),
),
],
groupby=[
subscriptable_expression("333333", "d0"),
time_expression("d1"),
time_expression("d0"),
],
condition=formula_condition,
order_by=[
OrderBy(
direction=OrderByDirection.ASC,
expression=time_expression("d0"),
),
],
limit=1000,
offset=0,
)

generic_metrics = get_dataset(
"generic_metrics",
)
query = parse_mql_query_new(str(query_body), mql_context, generic_metrics)
eq, reason = query.equals(expected)
assert eq, reason

generic_metrics = get_dataset(
"generic_metrics",
)
query = parse_mql_query_new(str(query_body), mql_context, generic_metrics)
eq, reason = query.equals(expected)
assert eq, reason
Loading