feat[next]: Add support for tuple comprehensions #2833
Comment from @tehrengruber in https://github.com/GridTools/gt4py/pull/2487:
This is for direct access to tracers[0] factor, tracers[1] factor, which I personally think is an anti pattern. I left it here until we take a decision on this. We could also make it an optional feature. One of the disadvantages is that it is not possible to fully type check the field operator at definition time, since the tuple length is only known at call / compile time. The user will then get an error in unroll_map_tuple.
@tehrengruber-ai This is just a functools.partial
# Only homogeneous (fixed-length and variable-length) tuples are supported, e.g.
# `tuple(2.0 * el for el in (a, b))`
# `tuple(2.0 * el for el in (a(V2E), b(V2E)))`
# but not
# `tuple(2.0 * local_el + scalar_el for local_el, scalar_el in ((a(V2E), b), (c(V2E), d)))`.
@tehrengruber-ai Is this true? Isn't this the problematic case
tuple(2.0 el for scalar_el in (a(V2E), b). Additionally what about tuple(2.0 el for el in (a, b)) with a and b different fields.@tehrengruber-ai This looks like a broken merge. Remove if you agree.
@tehrengruber-ai What is this change about?
Done in 374327f31 (pending push): replaced the closure with 'functools.partial(self._bind_tuple_comprehension_target, comprehension_target, element_expr)'.
Confirmed a merge artifact: main dropped the cartesian 'field(Off[i])' subscript syntax in #2695, and the merge resurrected the deprecated special case. Removed in 374327f31 (pending push); the hunk is back to main's version and the now-unused 'warnings' import is gone. No tests use the syntax.
Checked against the implementation: the rule is that all iterable elements must have the same type, and both of your suspected cases are indeed rejected ('tuple(2.0 * el for el in (a(V2E), b))' and 'tuple(... for el in (a, b))' with differently-typed fields both raise 'NotImplementedError: ... require all iterable elements to have the same type' in the type deduction). The multi-target example from the old comment is supported though — '((a(V2E), b), (c(V2E), d))' is homogeneous, each element being an equally-typed pair — so the suggestion's 'but not' would be wrong for that line. Rewrote the comment in 374327f31 (pending push) to state the rule and show both a supported and an unsupported example.
It made 'visit_Name' produce a 'DataSymbol' for names in 'ast.Store' context, which the comprehension-target parsing ('parse_target') relied on when visiting the loop target; everything else only ever visits names in 'Load' context. Since 'parse_target' was the only user, 374327f31 (pending push) builds the 'DataSymbol' directly there and reverts 'visit_Name' to main's version.
Removed from this PR and put into https://github.com/GridTools/gt4py/pull/2838
Wrap `element_expr` in a `let` binding the `comprehension_target` to `iterable_element`.
returns
`let a = iterable_element[0], b = iterable_element[1] in element_expr`.
@tehrengruber-ai Add a comment with short annotation examples for all the 3 cases here.
@tehrengruber-ai What is this about?
Applied in 410f729a5 (pending push).
Applied in 410f729a5 (pending push).
Done in 410f729a5 (pending push): one short example comment per branch — fixed-length 'tuple[int32, float64]', variable-length 'tuple[int32, ...]', and unparametrized 'tuple' / 'tuple[()]'.
It adapts the 'Field' case to the change above in 'canonicalize_type_hint', which now returns 'args=None' for unsubscripted annotations (needed to distinguish 'tuple' from 'tuple[()]'). A bare 'Field' annotation thus arrives here with 'args=None', and main's 'len(args)' would raise a 'TypeError'; the guard preserves the original diagnostic (verified: bare 'Field' still raises ValueError "Field type requires two arguments, got 0"). Added a short comment saying so in 410f729a5 (pending push).
[correctness, verified] Loosening this from equality to is_compatible_type/is_concretizable for all operators silently drops tuple-length validation for VarArg-returning operators: the return type is never specialized to the call-site length, and is_concretizable(VarArg[T], Tuple) ignores length (it even accepts an empty tuple, see type_info.py:555).
Verified: calling a tuple[IField, ...] -> tuple[IField, ...] operator with a 3-element input and a 2-element out passes PAST type deduction; embedded execution then dies with a bare AssertionError in utils.tree_map (utils.py:211), roundtrip with the opaque 'target_domain' cannot be 'NEVER' error. Pre-PR the equality check gave a located "Expected keyword argument out to be of type ..." error.
Suggestion: specialize the VarArg return type against the concrete argument length (available in with_args) instead of weakening the check for every operator. Note foast_to_past.py:121 uses a different predicate (is_concretizable) for the same conceptual check.
[correctness, verified] The new (arg,) = node.args turns wrong-arity builtin constructor calls into raw unpacking errors, regressing the located diagnostic: pre-PR, int32() or int32(1, 2) in a field operator raised a located DSLError: Invalid argument types in call to 'int32'; post-PR both crash with a bare ValueError: not enough/too many values to unpack and no source location. The old if len(node.args) > 0 tolerated non-1 arity and let type deduction report it properly.
Automated review by Fable (posted on behalf of @tehrengruber). Six findings, each verified empirically by comparing pre-PR vs. post-PR behavior. No issues found in the core comprehension typing/lowering itself; everything clusters around the variadic-tuple plumbing at the edges (out= validation, builtin-constructor arity, the DeferredType stand-in for bare tuple, dispatch, and test-harness coverage).
[correctness, verified] This constructor case returns DeferredType(constraint=VarArgType), but no call path can ever concretize it: the genexp path bypasses it in the parser, and the still-permitted literal path trips an internal assert. Verified: tuple(1.0) inside a field operator (accepted by _verify_builtin_type_constructor, whose own error message offers "literal arguments or a generator expression") fails with AssertionError: 'FOAST' expression is not fully typed.
Either reject tuple(<literal>) in the parser alongside other non-genexp forms, or make the constructor produce a concrete type.
[correctness, verified] A bare tuple annotation now maps silently to this DeferredType stand-in instead of being rejected here, so the rejection surfaces downstream as an internal-repr message: a parameter annotated bare tuple fails at decoration with InvalidParameterAnnotationError: ... 'DeferredType(constraint=<class ...TupleType>)' (raw datamodel repr shown to the user), where pre-PR it was the clear ValueError: Tuple annotation 'tuple' requires at least one argument. Any consumer of from_type_hint not guarding against DeferredType inherits the same leak.
[design, verified] Comprehension recognition is ~50 lines inlined in visit_Call, keyed purely on the syntactic name tuple, ahead of and outside the dialect's builtin-constructor dispatch (TYPE_BUILTIN_NAMES below), with no symbol resolution. Aliasing (t = tuple at module scope, then t(x * f for x in tracers)) falls through to the generic UnsupportedPythonFeatureError whose hint says generator expressions "are only supported as the argument of tuple(...)" - exactly what the user semantically wrote; conversely a closure variable that merely happens to be named tuple is rerouted into comprehension parsing. Extracting a _visit_tuple_comprehension (or using the builtin-constructor table) and resolving the name against closure vars would make the dispatch robust.
[test-coverage, verified] The harness hardcodes exactly 3 elements for every VarArgType allocation (and again in get_param_size, both marked TODO), so no integration test can exercise any other variadic length. That makes length-dependent bugs structurally invisible - including the missing out-length check flagged in past_passes/type_deduction.py on this PR. Suggestion: make it an explicit, overridable harness parameter (e.g. a per-case default_varargs_length).
@tehrengruber-ai Fix this.
@tehrengruber-ai What is this branch for then?
@tehrengruber-ai What is this branch for then?
This is a general problem that we want to solve, out-of-scope in this PR. One idea is to introduce a "type of types" like type[int] and use this to propagate type information.
This is a complicated issue that requires in-depth investigation. One solution would be integer type parameters that are resolved later with a proper frontend message or moving type checking to GTIR completely with a way to translate source locations. Skipped for now.
@tehrengruber-ai Write a test that shows this. Maybe pass two var args tuples of different length and conditionally return either one of them.
The user can always allocate a tuple of the size he likes so this doesn't feel like an issue.
Review of the current head (ed23528a). Everything below was checked by running against the branch unless I say otherwise.
Two findings have no anchor in the diff, because the files they concern are not touched by this PR. They are the two most important ones, so they go here.
---
1. Module-level names are unreachable from inside a comprehension body
This is a functional blocker for the feature, not a rough edge.
@gtx.field_operator
def testee(tracers: tuple[EField, ...]) -> tuple[CField, ...]:
return tuple(neighbor_sum(t(C2E), axis=C2EDim) for t in tracers)
# UndefinedSymbolError: Undeclared symbol 'neighbor_sum'
neighbor_sum is imported at module scope and works one line earlier outside a comprehension.
Cause. A generator expression compiles to its own code object, so names referenced only inside it land in that object's co_names, never in the enclosing function's. ffront/source_utils.py:24 get_closure_vars_from_function uses inspect.getclosurevars, which inspects only the enclosing function:
outer co_names : ('tuple',)
nested <genexpr> co_names : ('neighbor_sum', 'C2E', 'C2EDim')
collected closure vars : ['tuple']
Scope. Every module-level name: gt4py builtins (neighbor_sum, where, astype, ...), every FieldOffset, every local Dimension, and module-level @field_operators — so the clean factoring tuple(_inner(t, ...) for t in tracers) does not work either. Free variables are unaffected, because the enclosing code object carries co_freevars for the nested one.
Why CI is green. Every comprehension test in test_tuples.py defines its helpers inside the test function, so they are free variables. test_tuple_comprehension_other_fo passes for that reason alone. The entire suite sits on the working side of the bug.
Two things make this worse than a plain limitation: the diagnostic names a symbol that is plainly imported, and the workaround is to also reference the name outside the comprehension — so whether a stencil compiles depends on an unrelated line elsewhere in the function.
Prototype fix. Offered as a starting point, not a finished patch — it has not been reviewed by anyone but me, and the notes below are things I would want settled before it landed:
def _iter_code_objects(code: types.CodeType) -> Iterator[types.CodeType]:
yield code
for const in code.co_consts:
if isinstance(const, types.CodeType):
yield from _iter_code_objects(const)
def _global_vars_from_nested_code(function: Callable) -> tuple[dict[str, Any], dict[str, Any]]:
global_ns = function.__globals__
builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
if inspect.ismodule(builtin_ns):
builtin_ns = builtin_ns.__dict__
global_vars: dict[str, Any] = {}
builtin_vars: dict[str, Any] = {}
for nested_code in _iter_code_objects(function.__code__):
if nested_code is function.__code__:
continue
for name in nested_code.co_names:
if name in global_ns:
global_vars[name] = global_ns[name]
elif name in builtin_ns:
builtin_vars[name] = builtin_ns[name]
return global_vars, builtin_vars
def get_closure_vars_from_function(function: Callable) -> dict[str, Any]:
(nonlocals, globals, builtins_, _unbound) = inspect.getclosurevars(function)
nested_globals, nested_builtins = _global_vars_from_nested_code(function)
return dict(sorted(
{**nested_builtins, **builtins_, **nested_globals, **globals, **nonlocals}.items()
))
Resolution order mirrors inspect.getclosurevars itself; nonlocals still win. The comprehension target is not collected, because it is in the nested object's co_varnames rather than co_names.
Results on this branch: tests/next_tests/unit_tests/ 2144 passed, 51 skipped, 14 xfailed — no regressions. The comprehension tests in test_tuples.py pass on gtfn CPU including skip_value_mesh. mypy src/ and pre-commit are clean.
Caveats I would want settled: _iter_code_objects yields the root only for its caller to discard it; the merge ordering is defensive rather than meaningful, since both sources resolve from the same namespaces; and I have not checked the bound-method path, where getclosurevars unwraps to __func__ but this helper does not. It also does not address gtx.astype(...) inside a comprehension — but that fails outside a comprehension too, with DSLError: Functions can only be called directly, so it is a separate pre-existing restriction and not part of this bug.
I have not opened a PR for this; it is yours to take or discard.
---
2. Variable-length tuple programs are not treated as generic
CompiledProgramsPool._is_generic (otf/compiled_program.py) tests only ts.DeferredType. A program taking tuple[Field, ...] has VarArgType argument types, so it is classed non-generic and the tuple length never enters the compiled-program cache key — two calls with different tuple lengths reuse one compiled variant. On this head:
program arg types: ['VarArg[Field[[IDim], float64]]', 'float64', 'VarArg[Field[[IDim], float64]]']
any DeferredType (the rule used here): False
#2834 fixes the predicate by recursing into VarArgType. Please do not simply move that fix down here, though: compile() never passes arg_specialization_info, and _compile_variant then raises "Can not precompile generic program or scan operator without argument types." for generic programs. So the #2834 predicate makes ahead-of-time compilation of variadic-tuple programs impossible, and there is no parameter on the public compile() through which to supply the length. That raise pre-exists on main, where it already blocks AOT for scan operators, so this is a gap in the AOT API surface rather than a defect introduced here — but it means fixing the cache key alone converts a silent wrong-result into a hard block. Worth deciding deliberately.
The new test_var_len_tuple_length_mismatch_rejected xfail acknowledges an adjacent symptom; this is the other half.
---
Smaller points inline below.
@tehrengruber-ai Some directions:
1. Let's not do this in this PR, but in case proper error handling for this case disallow it. One can always use a dedicated field operator as a workaround. Introduce a test for the example and propose a text for an issue.
2. Introduce a test that calls a field operator first with a tuple of length X and then the same one with a length of Y. Fix _is_generic. The compile gap will be solved in a different PR.
Both directions addressed: 1. The test for the example already exists — 'test_var_len_tuple_length_mismatch_rejected' in test_tuples.py (ed23528a1) uses exactly the conditional-return construction and asserts the desired located DSLError as xfail(strict). The proposed issue text is drafted in 'submit_vararg_length_issue.sh' in the worktree: it describes the missing length validation, both the plain out-mismatch and the ambiguous conditional-return example, the specialization-in-'with_args' direction with the dedicated-field-operator workaround, and the 'foast_to_past' vs PAST-deduction predicate discrepancy. 2. Done in e449e6982 (pending push): 'test_var_len_tuple_comprehension_different_lengths' calls the same operator with lengths 3 then 2 — before the fix the second call reused the length-3 compiled variant and crashed with 'IndexError: tuple index out of range'. '_is_generic' now treats parameters containing a 'VarArgType' (also nested inside tuples) as generic, so each length gets its own specialized variant; verified across the backend matrix and the otf unit tests. The compile gap for the empty tuple stays out, as decided — xfailed test plus issue draft 'submit_empty_tuple_issue.sh'.
I think you @tehrengruber misunderstand the severity of 1 (or I misunderstood the comment). Also module level field_operators have this problem.
blocked on #2866
SF-N
Adds support for tuple comprehensions, e.g. for usage on tracers.
TODO:
AI disclaimer: This code was to a small degree refactored using AI tools. Code has been reviewed in detail, tests only briefly.