Skip to content

Context does not contain expression BACK(1).expr_1. #555

Closed

Description

@juankx-bodo

PyDough code succeeds with pydough.explain_llm(), but fails with pydough.to_sql().

Error generating SQL:

Context does not contain expression BACK(1).expr_1. Available expressions: [BACK(1).clerk, BACK(1).comment, BACK(1).customer_key, BACK(1).key, BACK(1).order_date, BACK(1).order_priority, BACK(1).order_status, BACK(1).order_year, BACK(1).ship_priority, BACK(1).total_price, comment, commit_date, discount, expr_1, extended_price, line_number, order_key, part_key, quantity, receipt_date, return_flag, ship_date, ship_instruct, ship_mode, status, supplier_key, tax]

Minimal reproducible example:

# Get order years
distinct_years = orders.CALCULATE(
    order_year=YEAR(order_date)
).PARTITION(
    name="years", by=order_year
).CALCULATE(
    year=order_year
)

# Get customer base
cust_base = customers.CALCULATE(
    c_id=key,
)

# CROSS join customer base with distinct years to get all combinations of customers and years
cust_years = cust_base.CROSS(distinct_years)

# Reproduce issue
result = cust_years.CALCULATE(
    year=year,
    bug=SUM(orders.WHERE(YEAR(order_date) == year).lines.extended_price),
    #opt1=SUM(orders.WHERE(YEAR(order_date) == order_year).lines.extended_price),
    #opt2=SUM(orders.WHERE(YEAR(order_date) == year).total_price)
).ORDER_BY(year.ASC())

Additional Context

In the final CALCULATE call, opt1 and opt2 work fine, but bug raises the context error.

  • opt1 vs bug: opt1 is identical to bug, but uses order_year (calculated in distinct_years) instead of the remapped year.
  • opt2 vs bug: opt2 uses year, but references a direct property (total_price) instead of navigating down into a subcollection value (lines.extended_price).

Side Effect:
Including opt2 alongside bug in the query prevents the error from occurring. The issue only manifests when bug is evaluated without opt2 present.

TPCH collections:

  orders
  ├── order_date
  ├── customer [one member of customers]
  └── lines [multiple lines]

  lines
  ├── extended_price
  └── order [one member of orders]

  customers
  ├── key
  └── orders [multiple orders]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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