Skip to content

KeyError: 'agg_1' #560

Description

@juankx-bodo

A PyDough expression using IFF with aggregates inside conditional branches raises an 'agg_1' error during SQL generation.

Error message:

Traceback (most recent call last):
  File "/home/juankx/svc/PyDough/pydough_test.py", line 182, in <module>
    sql = pydough.to_sql(unqualified_node, session=tester.session)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/juankx/svc/PyDough/pydough/evaluation/evaluate_unqualified.py", line 169, in to_sql
    return convert_relation_to_sql(relational, session, max_rows)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/juankx/svc/PyDough/pydough/sqlglot/execute_relational.py", line 88, in convert_relation_to_sql
    ).relational_to_sqlglot(relational)
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/juankx/svc/PyDough/pydough/sqlglot/sqlglot_relational_visitor.py", line 595, in relational_to_sqlglot
    root.accept(self)
  File "/home/juankx/svc/PyDough/pydough/relational/relational_nodes/relational_root.py", line 94, in accept
    visitor.visit_root(self)
  File "/home/juankx/svc/PyDough/pydough/sqlglot/sqlglot_relational_visitor.py", line 559, in visit_root
    query = self._merge_selects(
            ^^^^^^^^^^^^^^^^^^^^
  File "/home/juankx/svc/PyDough/pydough/sqlglot/sqlglot_relational_visitor.py", line 234, in _merge_selects
    new_exprs, old_exprs = self._try_merge_columns(
                           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/juankx/svc/PyDough/pydough/sqlglot/sqlglot_relational_visitor.py", line 185, in _try_merge_columns
    expr = set_glot_alias(old_column_map[new_column.this], new_name)
                          ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
KeyError: 'agg_1'

Minimal reproducible example:

## Error msg: 'agg_1'
result = TPCH.CALCULATE(
    res_is_nothing=0
).CALCULATE(
    output=IFF(res_is_nothing == 1, COUNT(customers), COUNT(suppliers)),
    #a=COUNT(customers),
    #b=COUNT(suppliers)
)

Expected result:

PyDough should generate valid SQL selecting from the active branch condition (since res_is_nothing is 0, evaluating the COUNT(suppliers) branch):

SELECT
  COUNT(*) AS output,
FROM main.supplier

Additional Context / Workarounds

The bug can be avoided if:

  • res_is_nothing is set to 1, or
  • Either a or b is explicitly evaluated as a standalone expression alongside output (e.g., uncommenting # a=COUNT(customers) or # b=COUNT(suppliers)).

Schema Context (TPCH Collections Used):

customers
suppliers

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions