← Back to Pull requests

feat[next]: Add support for tuple comprehensions #2833

Open
SF-N opened this pull request with 2429 lines diff across 38 files
View on GitHub
SF-N SF-N commented on Aug 27, 2026 08:29 UTC
Author

Adds support for tuple comprehensions, e.g. for usage on tracers.

@gtx.field_operator
def testee(
    tracers: tuple[cases.IField, cases.IField], factor: int32
) -> tuple[cases.IField, cases.IField]:
    return tuple(tracer * factor for tracer in tracers)

TODO:

  • document that precompilation is not possible yet and why.

  • document or fix that CollectionTypeSpec should include VarArgType

  • document or fix that all argument descriptors are no compatible with var length tuples.
  • AI disclaimer: This code was to a small degree refactored using AI tools. Code has been reviewed in detail, tests only briefly.

    Diff: 2429 lines (+2191 / -238) across 38 files Reviewer: SF-N Review duration: 137613m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.93) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.93 · 2429 lines diff across 38 files
    0.93
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    37 items
    SF-N SF-N commented on code on Aug 27, 2026 08:37 UTC
    Code Review
    src/gt4py/next/ffront/foast_passes/type_deduction.py:1
    @@ -456,6 +458,10 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri
                             f"Tuples need to be indexed with literal integers, got '{node.index}'.",
                         ) from ex
                     new_type = types[index]
    +            case ts.VarArgType(element_type=element_type):
    +                new_type = (
    +                    element_type  # TODO: we only temporarily allow any index for vararg types
    +                )

    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 tehrengruber commented on code on Aug 27, 2026 09:21 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +261,73 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """Return ``element_expr`` with the comprehension target bound to one element."""
    +        # For `2.0 * local_el + scalar_el for local_el, scalar_el in iterable`:
    +        # - `comprehension_target`: `(local_el, scalar_el)`
    +        # - `element_expr`: `2.0 * local_el + scalar_el`
    +        # - `iterable_element` is the current element from `iterable`
    +        # Returns `let local_el = iterable_element[0], scalar_el = iterable_element[1]
    +        # in element_expr`.
    +        if not isinstance(comprehension_target, tuple):
    +            return im.let(comprehension_target, iterable_element)(element_expr)
    +
    +        flat_targets = utils.flatten_nested_tuple(comprehension_target)
    +        nested_target_values = utils.tree_map(
    +            lambda _, path: functools.reduce(
    +                lambda element, index: im.tuple_get(index, element), path, iterable_element
    +            ),
    +            with_path_arg=True,
    +        )(comprehension_target)
    +
    +        flat_target_values = utils.flatten_nested_tuple(nested_target_values)  # type: ignore[arg-type]
    +
    +        target_bindings = tuple(zip(flat_targets, flat_target_values, strict=True))
    +        return im.let(*target_bindings)(element_expr)  # type: ignore[arg-type]
    +
    +    def visit_TupleComprehension(self, node: foast.TupleComprehension, **kwargs: Any) -> itir.Expr:
    +        # e.g. tuple(2.0 * el for el in (a, a))` or `tuple(2.0 * el for el in (a(V2E), a(V2E)))`
    +        # `tuple(2.0 * local_el + scalar_el for local_el, scalar_el in ((a(V2E), b), (c(V2E), d)))`.
    +        # Only homogeneous (fixed-length and variable-length) tuples are supported.
    +        comprehension_target = self.visit(node.inner.target, **kwargs)
    +        element_expr = self.visit(node.inner.element_expr, **kwargs)
    +        iterable_expr = self.visit(node.iterable, **kwargs)
    +        iterable_type = node.iterable.type
    +
    +        def lower_body_for_iterable_element(iterable_element: itir.Expr | str) -> itir.Expr:

    @tehrengruber-ai This is just a functools.partial

    tehrengruber tehrengruber commented on code on Aug 27, 2026 09:25 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +261,73 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """Return ``element_expr`` with the comprehension target bound to one element."""
    +        # For `2.0 * local_el + scalar_el for local_el, scalar_el in iterable`:
    +        # - `comprehension_target`: `(local_el, scalar_el)`
    +        # - `element_expr`: `2.0 * local_el + scalar_el`
    +        # - `iterable_element` is the current element from `iterable`
    +        # Returns `let local_el = iterable_element[0], scalar_el = iterable_element[1]
    +        # in element_expr`.
    +        if not isinstance(comprehension_target, tuple):
    +            return im.let(comprehension_target, iterable_element)(element_expr)
    +
    +        flat_targets = utils.flatten_nested_tuple(comprehension_target)
    +        nested_target_values = utils.tree_map(
    +            lambda _, path: functools.reduce(
    +                lambda element, index: im.tuple_get(index, element), path, iterable_element
    +            ),
    +            with_path_arg=True,
    +        )(comprehension_target)
    +
    +        flat_target_values = utils.flatten_nested_tuple(nested_target_values)  # type: ignore[arg-type]
    +
    +        target_bindings = tuple(zip(flat_targets, flat_target_values, strict=True))
    +        return im.let(*target_bindings)(element_expr)  # type: ignore[arg-type]
    +
    +    def visit_TupleComprehension(self, node: foast.TupleComprehension, **kwargs: Any) -> itir.Expr:
    +        # e.g. tuple(2.0 * el for el in (a, a))` or `tuple(2.0 * el for el in (a(V2E), a(V2E)))`
    +        # `tuple(2.0 * local_el + scalar_el for local_el, scalar_el in ((a(V2E), b), (c(V2E), d)))`.
    +        # Only homogeneous (fixed-length and variable-length) tuples are supported.

            # 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 tehrengruber commented on code on Aug 27, 2026 09:30 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -301,8 +370,23 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
                         new_index = constant_folding.ConstantFolding.apply(self.visit(index, **kwargs))
                         assert isinstance(new_index, itir.Literal)
                         assert isinstance(offset_name.type, ts.OffsetType)
    +                    if fbuiltins.is_cartesian_offset(offset_name.type):

    @tehrengruber-ai This looks like a broken merge. Remove if you agree.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 09:44 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -401,8 +401,13 @@ def visit_Return(self, node: ast.Return, **kwargs: Any) -> foast.Return:
         def visit_Expr(self, node: ast.Expr) -> foast.Expr:
             return self.visit(node.value)
     
    -    def visit_Name(self, node: ast.Name, **kwargs: Any) -> foast.Name:
    -        return foast.Name(id=node.id, location=self.get_location(node))
    +    def visit_Name(self, node: ast.Name, **kwargs: Any) -> foast.DataSymbol | foast.Name:

    @tehrengruber-ai What is this change about?

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 12:01 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +261,73 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """Return ``element_expr`` with the comprehension target bound to one element."""
    +        # For `2.0 * local_el + scalar_el for local_el, scalar_el in iterable`:
    +        # - `comprehension_target`: `(local_el, scalar_el)`
    +        # - `element_expr`: `2.0 * local_el + scalar_el`
    +        # - `iterable_element` is the current element from `iterable`
    +        # Returns `let local_el = iterable_element[0], scalar_el = iterable_element[1]
    +        # in element_expr`.
    +        if not isinstance(comprehension_target, tuple):
    +            return im.let(comprehension_target, iterable_element)(element_expr)
    +
    +        flat_targets = utils.flatten_nested_tuple(comprehension_target)
    +        nested_target_values = utils.tree_map(
    +            lambda _, path: functools.reduce(
    +                lambda element, index: im.tuple_get(index, element), path, iterable_element
    +            ),
    +            with_path_arg=True,
    +        )(comprehension_target)
    +
    +        flat_target_values = utils.flatten_nested_tuple(nested_target_values)  # type: ignore[arg-type]
    +
    +        target_bindings = tuple(zip(flat_targets, flat_target_values, strict=True))
    +        return im.let(*target_bindings)(element_expr)  # type: ignore[arg-type]
    +
    +    def visit_TupleComprehension(self, node: foast.TupleComprehension, **kwargs: Any) -> itir.Expr:
    +        # e.g. tuple(2.0 * el for el in (a, a))` or `tuple(2.0 * el for el in (a(V2E), a(V2E)))`
    +        # `tuple(2.0 * local_el + scalar_el for local_el, scalar_el in ((a(V2E), b), (c(V2E), d)))`.
    +        # Only homogeneous (fixed-length and variable-length) tuples are supported.
    +        comprehension_target = self.visit(node.inner.target, **kwargs)
    +        element_expr = self.visit(node.inner.element_expr, **kwargs)
    +        iterable_expr = self.visit(node.iterable, **kwargs)
    +        iterable_type = node.iterable.type
    +
    +        def lower_body_for_iterable_element(iterable_element: itir.Expr | str) -> itir.Expr:

    Done in 374327f31 (pending push): replaced the closure with 'functools.partial(self._bind_tuple_comprehension_target, comprehension_target, element_expr)'.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 12:01 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -301,8 +370,23 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr:
                         new_index = constant_folding.ConstantFolding.apply(self.visit(index, **kwargs))
                         assert isinstance(new_index, itir.Literal)
                         assert isinstance(offset_name.type, ts.OffsetType)
    +                    if fbuiltins.is_cartesian_offset(offset_name.type):

    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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 12:02 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +261,73 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """Return ``element_expr`` with the comprehension target bound to one element."""
    +        # For `2.0 * local_el + scalar_el for local_el, scalar_el in iterable`:
    +        # - `comprehension_target`: `(local_el, scalar_el)`
    +        # - `element_expr`: `2.0 * local_el + scalar_el`
    +        # - `iterable_element` is the current element from `iterable`
    +        # Returns `let local_el = iterable_element[0], scalar_el = iterable_element[1]
    +        # in element_expr`.
    +        if not isinstance(comprehension_target, tuple):
    +            return im.let(comprehension_target, iterable_element)(element_expr)
    +
    +        flat_targets = utils.flatten_nested_tuple(comprehension_target)
    +        nested_target_values = utils.tree_map(
    +            lambda _, path: functools.reduce(
    +                lambda element, index: im.tuple_get(index, element), path, iterable_element
    +            ),
    +            with_path_arg=True,
    +        )(comprehension_target)
    +
    +        flat_target_values = utils.flatten_nested_tuple(nested_target_values)  # type: ignore[arg-type]
    +
    +        target_bindings = tuple(zip(flat_targets, flat_target_values, strict=True))
    +        return im.let(*target_bindings)(element_expr)  # type: ignore[arg-type]
    +
    +    def visit_TupleComprehension(self, node: foast.TupleComprehension, **kwargs: Any) -> itir.Expr:
    +        # e.g. tuple(2.0 * el for el in (a, a))` or `tuple(2.0 * el for el in (a(V2E), a(V2E)))`
    +        # `tuple(2.0 * local_el + scalar_el for local_el, scalar_el in ((a(V2E), b), (c(V2E), d)))`.
    +        # Only homogeneous (fixed-length and variable-length) tuples are supported.

    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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 12:02 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -401,8 +401,13 @@ def visit_Return(self, node: ast.Return, **kwargs: Any) -> foast.Return:
         def visit_Expr(self, node: ast.Expr) -> foast.Expr:
             return self.visit(node.value)
     
    -    def visit_Name(self, node: ast.Name, **kwargs: Any) -> foast.Name:
    -        return foast.Name(id=node.id, location=self.get_location(node))
    +    def visit_Name(self, node: ast.Name, **kwargs: Any) -> foast.DataSymbol | foast.Name:

    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.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 16:26 UTC
    Code Review
    src/gt4py/next/ffront/foast_passes/type_deduction.py:1
    @@ -456,6 +458,10 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri
                             f"Tuples need to be indexed with literal integers, got '{node.index}'.",
                         ) from ex
                     new_type = types[index]
    +            case ts.VarArgType(element_type=element_type):
    +                new_type = (
    +                    element_type  # TODO: we only temporarily allow any index for vararg types
    +                )

    Removed from this PR and put into https://github.com/GridTools/gt4py/pull/2838

    tehrengruber tehrengruber commented on code on Aug 27, 2026 17:57 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +260,74 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """
    +        Wrap `element_expr` in a `let` binding the comprehension target to `iterable_element`.

            Wrap `element_expr` in a `let` binding the `comprehension_target` to `iterable_element`.
    

    tehrengruber tehrengruber commented on code on Aug 27, 2026 17:58 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +260,74 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """
    +        Wrap `element_expr` in a `let` binding the comprehension target to `iterable_element`.
    +
    +        For `2.0 * a + b for (a, b) in iterable`:
    +        - `comprehension_target`: `(a, b)`
    +        - `element_expr`: `2.0 * a + b`
    +        - `iterable_element`: the current element of `iterable`
    +
    +        returns `let a = iterable_element[0], b = iterable_element[1] in element_expr`.

            returns
            `let a = iterable_element[0], b = iterable_element[1] in element_expr`.
    

    tehrengruber tehrengruber commented on code on Aug 27, 2026 17:59 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,33 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            if (

    @tehrengruber-ai Add a comment with short annotation examples for all the 3 cases here.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 18:00 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,33 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            if (
    +                isinstance(args, tuple)
    +                and len(args) > 0
    +                and not any(arg is Ellipsis for arg in args)
    +            ):
    +                tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    +                assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    +                return ts.TupleType(types=tuple_types)
    +            elif isinstance(args, tuple) and len(args) == 2 and args[1] is Ellipsis:
    +                return ts.VarArgType(element_type=from_type_hint_same_ns(args[0]))
    +            elif args is None or (isinstance(args, tuple) and len(args) == 0):
    +                # TODO(tehrengruber): We use `DeferredType` until we have an actual representation
    +                #  for a generic type.
    +                return ts.DeferredType(constraint=ts.TupleType)
    +            else:
    +                raise ValueError(
    +                    f"Tuple annotation '{type_hint}' must either "
    +                    f"be a list of concrete arguments (e.g. 'tuple[int]'), "
    +                    f"be a variadic tuple (e.g. 'tuple[int, ...]'), "
    +                    f"or have no arguments (e.g. 'tuple')."
    +                )
     
             case common.Field:
    -            if (n_args := len(args)) != 2:
    -                raise ValueError(f"Field type requires two arguments, got {n_args}: '{type_hint}'.")
    +            if args is None or len(args) != 2:

    @tehrengruber-ai What is this about?

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 18:41 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +260,74 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """
    +        Wrap `element_expr` in a `let` binding the comprehension target to `iterable_element`.

    Applied in 410f729a5 (pending push).

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 18:41 UTC
    Code Review
    src/gt4py/next/ffront/foast_to_gtir.py:1
    @@ -259,6 +260,74 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr:
         def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr:
             return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts])
     
    +    def _bind_tuple_comprehension_target(
    +        self,
    +        comprehension_target: itir.Sym | tuple,
    +        element_expr: itir.Expr,
    +        iterable_element: itir.Expr | str,
    +    ) -> itir.Expr:
    +        """
    +        Wrap `element_expr` in a `let` binding the comprehension target to `iterable_element`.
    +
    +        For `2.0 * a + b for (a, b) in iterable`:
    +        - `comprehension_target`: `(a, b)`
    +        - `element_expr`: `2.0 * a + b`
    +        - `iterable_element`: the current element of `iterable`
    +
    +        returns `let a = iterable_element[0], b = iterable_element[1] in element_expr`.

    Applied in 410f729a5 (pending push).

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 18:41 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,33 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            if (

    Done in 410f729a5 (pending push): one short example comment per branch — fixed-length 'tuple[int32, float64]', variable-length 'tuple[int32, ...]', and unparametrized 'tuple' / 'tuple[()]'.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 18:41 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,33 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            if (
    +                isinstance(args, tuple)
    +                and len(args) > 0
    +                and not any(arg is Ellipsis for arg in args)
    +            ):
    +                tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    +                assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    +                return ts.TupleType(types=tuple_types)
    +            elif isinstance(args, tuple) and len(args) == 2 and args[1] is Ellipsis:
    +                return ts.VarArgType(element_type=from_type_hint_same_ns(args[0]))
    +            elif args is None or (isinstance(args, tuple) and len(args) == 0):
    +                # TODO(tehrengruber): We use `DeferredType` until we have an actual representation
    +                #  for a generic type.
    +                return ts.DeferredType(constraint=ts.TupleType)
    +            else:
    +                raise ValueError(
    +                    f"Tuple annotation '{type_hint}' must either "
    +                    f"be a list of concrete arguments (e.g. 'tuple[int]'), "
    +                    f"be a variadic tuple (e.g. 'tuple[int, ...]'), "
    +                    f"or have no arguments (e.g. 'tuple')."
    +                )
     
             case common.Field:
    -            if (n_args := len(args)) != 2:
    -                raise ValueError(f"Field type requires two arguments, got {n_args}: '{type_hint}'.")
    +            if args is None or len(args) != 2:

    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).

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    src/gt4py/next/ffront/past_passes/type_deduction.py:1
    @@ -248,7 +248,9 @@ def visit_Call(self, node: past.Call, **kwargs: Any) -> past.Call:
                     operator_return_type = type_info.return_type(
                         new_func.type, with_args=arg_types, with_kwargs=kwarg_types
                     )
    -                if operator_return_type != new_kwargs["out"].type:
    +                # Not equality: variadic comprehensions give a `VarArg[...]` return type,
    +                # while 'out' is a concrete tuple.
    +                if not type_info.is_compatible_type(operator_return_type, new_kwargs["out"].type):

    [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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -542,24 +542,76 @@ def visit_NotEq(self, node: ast.NotEq, **kwargs: Any) -> foast.CompareOperator:
             return foast.CompareOperator.NOTEQ
     
         def _verify_builtin_type_constructor(self, node: ast.Call) -> None:
    -        if len(node.args) > 0:
    -            arg = node.args[0]
    -            if not (
    -                isinstance(arg, ast.Constant)
    -                or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    -            ):
    -                raise errors.DSLError(
    -                    self.get_location(node),
    -                    f"'{self._func_name(node)}()' only takes literal arguments.",
    -                )
    +        assert isinstance(node.func, ast.Name)
    +        (arg,) = node.args

    [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.

    tehrengruber-ai tehrengruber-ai commented on Aug 27, 2026 22:30 UTC
    Reviewer

    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).

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -75,6 +75,16 @@ def make_constructor_type(type_spec: ts.TypeSpec) -> ts.ConstructorType:
                     )
                 )
     
    +        case ts.DeferredType(constraint=ts.TupleType):

    [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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,37 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            # Fixed-length tuple, e.g. `tuple[int32, float64]`
    +            if (
    +                isinstance(args, tuple)
    +                and len(args) > 0
    +                and not any(arg is Ellipsis for arg in args)
    +            ):
    +                tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    +                assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    +                return ts.TupleType(types=tuple_types)
    +            # Variable-length tuple, e.g. `tuple[int32, ...]`
    +            elif isinstance(args, tuple) and len(args) == 2 and args[1] is Ellipsis:
    +                return ts.VarArgType(element_type=from_type_hint_same_ns(args[0]))
    +            # Unparametrized annotation, i.e. `tuple` or `tuple[()]`
    +            elif args is None or (isinstance(args, tuple) and len(args) == 0):
    +                # TODO(tehrengruber): We use `DeferredType` until we have an actual representation
    +                #  for a generic type.
    +                return ts.DeferredType(constraint=ts.TupleType)

    [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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -542,24 +542,76 @@ def visit_NotEq(self, node: ast.NotEq, **kwargs: Any) -> foast.CompareOperator:
             return foast.CompareOperator.NOTEQ
     
         def _verify_builtin_type_constructor(self, node: ast.Call) -> None:
    -        if len(node.args) > 0:
    -            arg = node.args[0]
    -            if not (
    -                isinstance(arg, ast.Constant)
    -                or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    -            ):
    -                raise errors.DSLError(
    -                    self.get_location(node),
    -                    f"'{self._func_name(node)}()' only takes literal arguments.",
    -                )
    +        assert isinstance(node.func, ast.Name)
    +        (arg,) = node.args
    +        if not (
    +            isinstance(arg, ast.Constant)
    +            or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    +            or (node.func.id == "tuple" and isinstance(arg, ast.GeneratorExp))
    +        ):
    +            allowed = (
    +                "literal arguments or a generator expression"
    +                if node.func.id == "tuple"
    +                else "literal arguments"
    +            )
    +            raise errors.DSLError(
    +                self.get_location(node),
    +                f"'{self._func_name(node)}()' only takes {allowed}.",
    +            )
     
         def _func_name(self, node: ast.Call) -> str:
             return node.func.id  # type: ignore[attr-defined] # We want this to fail if the attribute does not exist unexpectedly.
     
    -    def visit_Call(self, node: ast.Call, **kwargs: Any) -> foast.Call:
    -        # TODO(tehrengruber): is this still needed or redundant with the checks in type deduction?
    +    def visit_Call(self, node: ast.Call, **kwargs: Any) -> foast.Call | foast.TupleComprehension:
             if isinstance(node.func, ast.Name):
                 func_name = self._func_name(node)
    +
    +            if (

    [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.

    tehrengruber-ai tehrengruber-ai commented on code on Aug 27, 2026 22:30 UTC
    Code Review
    tests/next_tests/integration_tests/cases.py:1
    @@ -616,6 +616,15 @@ def _allocate_from_type(
                         for t in types
                     )
                 )
    +        case ts.VarArgType(element_type=element_type):
    +            return tuple(
    +                (
    +                    _allocate_from_type(
    +                        case=case, arg_type=t, domain=domain, dtype=dtype, strategy=strategy
    +                    )
    +                    for t in [element_type] * 3  # TODO: revisit

    [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 tehrengruber commented on code on Aug 27, 2026 22:32 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -542,24 +542,76 @@ def visit_NotEq(self, node: ast.NotEq, **kwargs: Any) -> foast.CompareOperator:
             return foast.CompareOperator.NOTEQ
     
         def _verify_builtin_type_constructor(self, node: ast.Call) -> None:
    -        if len(node.args) > 0:
    -            arg = node.args[0]
    -            if not (
    -                isinstance(arg, ast.Constant)
    -                or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    -            ):
    -                raise errors.DSLError(
    -                    self.get_location(node),
    -                    f"'{self._func_name(node)}()' only takes literal arguments.",
    -                )
    +        assert isinstance(node.func, ast.Name)
    +        (arg,) = node.args

    @tehrengruber-ai Fix this.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 22:35 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -75,6 +75,16 @@ def make_constructor_type(type_spec: ts.TypeSpec) -> ts.ConstructorType:
                     )
                 )
     
    +        case ts.DeferredType(constraint=ts.TupleType):

    @tehrengruber-ai What is this branch for then?

    tehrengruber tehrengruber commented on code on Aug 27, 2026 22:36 UTC
    Code Review
    src/gt4py/next/type_system/type_translation.py:1
    @@ -199,17 +210,37 @@ def from_type_hint(
     
         match canonical_type:
             case builtins.tuple:
    -            if not args:
    -                raise ValueError(f"Tuple annotation '{type_hint}' requires at least one argument.")
    -            if Ellipsis in args:
    -                raise ValueError(f"Unbound tuples '{type_hint}' are not allowed.")
    -            tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    -            assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    -            return ts.TupleType(types=tuple_types)
    +            # Fixed-length tuple, e.g. `tuple[int32, float64]`
    +            if (
    +                isinstance(args, tuple)
    +                and len(args) > 0
    +                and not any(arg is Ellipsis for arg in args)
    +            ):
    +                tuple_types = [from_type_hint_same_ns(arg) for arg in args]
    +                assert all(isinstance(elem, ts.DataType) for elem in tuple_types)
    +                return ts.TupleType(types=tuple_types)
    +            # Variable-length tuple, e.g. `tuple[int32, ...]`
    +            elif isinstance(args, tuple) and len(args) == 2 and args[1] is Ellipsis:
    +                return ts.VarArgType(element_type=from_type_hint_same_ns(args[0]))
    +            # Unparametrized annotation, i.e. `tuple` or `tuple[()]`
    +            elif args is None or (isinstance(args, tuple) and len(args) == 0):
    +                # TODO(tehrengruber): We use `DeferredType` until we have an actual representation
    +                #  for a generic type.
    +                return ts.DeferredType(constraint=ts.TupleType)

    @tehrengruber-ai What is this branch for then?

    tehrengruber tehrengruber commented on code on Aug 27, 2026 22:38 UTC
    Code Review
    src/gt4py/next/ffront/func_to_foast.py:1
    @@ -542,24 +542,76 @@ def visit_NotEq(self, node: ast.NotEq, **kwargs: Any) -> foast.CompareOperator:
             return foast.CompareOperator.NOTEQ
     
         def _verify_builtin_type_constructor(self, node: ast.Call) -> None:
    -        if len(node.args) > 0:
    -            arg = node.args[0]
    -            if not (
    -                isinstance(arg, ast.Constant)
    -                or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    -            ):
    -                raise errors.DSLError(
    -                    self.get_location(node),
    -                    f"'{self._func_name(node)}()' only takes literal arguments.",
    -                )
    +        assert isinstance(node.func, ast.Name)
    +        (arg,) = node.args
    +        if not (
    +            isinstance(arg, ast.Constant)
    +            or (isinstance(arg, ast.UnaryOp) and isinstance(arg.operand, ast.Constant))
    +            or (node.func.id == "tuple" and isinstance(arg, ast.GeneratorExp))
    +        ):
    +            allowed = (
    +                "literal arguments or a generator expression"
    +                if node.func.id == "tuple"
    +                else "literal arguments"
    +            )
    +            raise errors.DSLError(
    +                self.get_location(node),
    +                f"'{self._func_name(node)}()' only takes {allowed}.",
    +            )
     
         def _func_name(self, node: ast.Call) -> str:
             return node.func.id  # type: ignore[attr-defined] # We want this to fail if the attribute does not exist unexpectedly.
     
    -    def visit_Call(self, node: ast.Call, **kwargs: Any) -> foast.Call:
    -        # TODO(tehrengruber): is this still needed or redundant with the checks in type deduction?
    +    def visit_Call(self, node: ast.Call, **kwargs: Any) -> foast.Call | foast.TupleComprehension:
             if isinstance(node.func, ast.Name):
                 func_name = self._func_name(node)
    +
    +            if (

    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.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 22:40 UTC
    Code Review
    src/gt4py/next/ffront/past_passes/type_deduction.py:1
    @@ -248,7 +248,9 @@ def visit_Call(self, node: past.Call, **kwargs: Any) -> past.Call:
                     operator_return_type = type_info.return_type(
                         new_func.type, with_args=arg_types, with_kwargs=kwarg_types
                     )
    -                if operator_return_type != new_kwargs["out"].type:
    +                # Not equality: variadic comprehensions give a `VarArg[...]` return type,
    +                # while 'out' is a concrete tuple.
    +                if not type_info.is_compatible_type(operator_return_type, new_kwargs["out"].type):

    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.

    tehrengruber tehrengruber commented on code on Aug 27, 2026 22:45 UTC
    Code Review
    tests/next_tests/integration_tests/cases.py:1
    @@ -616,6 +616,15 @@ def _allocate_from_type(
                         for t in types
                     )
                 )
    +        case ts.VarArgType(element_type=element_type):
    +            return tuple(
    +                (
    +                    _allocate_from_type(
    +                        case=case, arg_type=t, domain=domain, dtype=dtype, strategy=strategy
    +                    )
    +                    for t in [element_type] * 3  # TODO: revisit

    The user can always allocate a tuple of the size he likes so this doesn't feel like an issue.

    havogt havogt commented on Aug 28, 2026 07:40 UTC
    Reviewer

    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 tehrengruber commented on Sep 01, 2026 07:10 UTC
    Contributor

    @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.

    tehrengruber-ai tehrengruber-ai commented on Sep 01, 2026 09:47 UTC
    Contributor

    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'.

    havogt havogt commented on Sep 04, 2026 11:16 UTC
    Contributor

    I think you @tehrengruber misunderstand the severity of 1 (or I misunderstood the comment). Also module level field_operators have this problem.

    havogt havogt commented on Sep 09, 2026 08:51 UTC
    Contributor

    blocked on #2866

    Reviewers
    Assignees
    SF-N SF-N
    Labels
    risk: low confidence: 82.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.4% · Lower = rushed or shallow review
    82.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.3% · Safe to merge
    16.3%