Skip to content

fix[next]: named collections as program arguments - #3042

Merged
havogt merged 17 commits into
GridTools:mainfrom
havogt:named-collection-args
Dec 3, 2026
Merged

havogt merged 17 commits into
GridTools:mainfrom
havogt:named-collection-args

Conversation

@havogt

@havogt havogt commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes for named collections and tuples passed as program arguments:

  • Attribute access in a program body (domain={E: (d.edges.lb, d.edges.ub)}) was not lowered: ProgramLowering gets a visit_Attribute, lowering to tuple_get as in foast_to_gtir.
  • Subscripts of tuples in a program body (t[1], t[0][-1], t[1].lb) were typed as the whole tuple, and nested ones were rejected. They are now typed as the element and lowered to tuple_get. Named collections can not be subscripted, as in field operators: their fields are accessed by name.
  • Tuple indices are checked by one helper shared by field operators and programs: a literal integer in [-n, n), so bool and out-of-range indices are a DSLError in both (field operators accepted t[True] and raised a bare IndexError before).
  • Negative tuple indices were passed to tuple_get unchanged in field operators, which the backends do not support. Both lowerings now pass the non-negative position.
  • UnpackedAssignPass typed the temporary of a tuple unpacking as the element instead of the tuple.

FLATTEN_AS_FIELDOP_ARGS named the let variable binding a flattened tuple argument
__ct_flat_remapped_{i}, with a counter restarting at 0 on every application. Flattening a
nested tuple argument inside a let that survived the previous flattening rebound the same
name and captured the outer references.
A program body like domain={E: (d.edges.lb, d.edges.ub)} failed on every compiled backend
because ProgramLowering had no visit_Attribute.
@havogt

havogt commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

🤖 Written by an agent on behalf of @havogt

A subscript on a tuple program argument, e.g. d[1] as a field operator argument or
d[0][1] as a domain bound, was typed as the whole tuple and nested subscripts were
rejected, as program_ast.Subscript only modelled slicing an output field.
@havogt
havogt marked this pull request as ready for review November 25, 2026 09:39
@havogt
havogt requested a review from tehrengruber November 25, 2026 09:44
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
✅ Merge recommendation: Needs review
🔎 Failure modes

What: A program body indexing a tuple or named-collection argument with a negative literal (e.g. `bounds[-1]`) passes type deduction, because `types[slice_.value]` uses Python semantics and resolves to the last element's type. The lowering then emits `tuple_get(-1, ...)` unchanged, which compiled backends (gtfn C++, DaCe) cannot handle; embedded execution may still work, so the breakage only shows up on compiled backends.
Where: src/gt4py/next/ffront/past_passes/type_deduction.py:visit_Subscript (acceptance) and src/gt4py/next/ffront/past_to_itir.py:visit_Subscript (lowering)
Trigger: A program using a negative literal index on a tuple/named-collection program argument, run on a compiled backend (gtfn or dace).
Detected by: Nothing in this PR — no test covers negative indices; it would surface as a generated-code compile error or opaque failure in the gtfn/dace nox sessions.
Covered in this PR: No

What: An out-of-range literal index (e.g. `t[5]` on a 2-element tuple, or `t[-5]`) raises a bare Python IndexError from the tuple-type element lookup instead of a located DSLError, so DSL users get an opaque traceback without a source location or hint.
Where: src/gt4py/next/ffront/past_passes/type_deduction.py:visit_Subscript
Trigger: A program body subscripting a tuple/named-collection argument with a constant index outside the range of the tuple's element list.
Detected by: The new unit tests cover the non-literal-index error but not out-of-range indices; the failure appears as an uncaught IndexError during program parsing.
Covered in this PR: No

🏅 Score: 85
🧪 PR contains tests
🔒 No security concerns identified
🔀 No multiple PR themes

⚙️ Agent run details
  • Model: openai/zai-org/GLM-5.3-Flash
  • Tokens: 12,565 in / 14,716 out / 27,281 total
  • Time cost: 308.2s
  • AI calls: 1

Reject non-literal, out-of-range, negative and bool tuple indices, integer
indexing of dataclass collections and element access on closure variables
with a DSLError, and look up named-collection attributes by key, so that
fields named like attributes of the type spec (e.g. 'keys') resolve.
@havogt havogt added the agent-review Request a sandboxed AI agent review (added by a maintainer) label Nov 25, 2026
@havogt
havogt deployed to agent-review November 25, 2026 10:29 — with GitHub Actions Active
@github-actions

Copy link
Copy Markdown

Note

Advisory review by opencode 2.2.7 (zai-org/GLM-5.3-Flash) of commit 6d2fe14, produced in a sandbox. Later pushes are not reviewed. Not a required check: it may be wrong, and the content of the pull request can steer it. Workflow run.

Summary

This PR makes named collections / tuples usable as program arguments: ProgramLowering gains visit_Attribute/visit_Subscript (lowered to tuple_get), PAST type deduction now types element access (literal integer indices only, with validation for unknown attributes, non-tuple collections, and closure variables), and CollapseTuple.FLATTEN_AS_FIELDOP_ARGS takes its remapped-argument names from uids to avoid capture. The implementation looks correct; I verified the lowering paths (domain bounds go through _construct_itir_initialized_domain_arg → self.visit(bound), args through the new visitors), that closure_var_ids is always set before body visiting, and that the new CollapseTuple test matches the transform's behavior. The remaining issues are error-quality gaps where invalid element access passes type deduction and surfaces as an AssertionError instead of a DSLError. No test coverage gaps found; the new unit and integration tests match the code paths.

Findings

  1. Element access on non-collection types passes type deduction, then crashes in lowering (src/gt4py/next/ffront/past_passes/type_deduction.py:162): in visit_Subscript, when value.type is neither TupleType nor NamedCollectionType the Subscript is silently typed as value.type (new_type = value.type) and accepted. For example, passing a sliced input field (my_op(in_field[0:2], out=out) — _ensure_no_sliced_field only guards out= when a domain is present) or subscripting a scalar reaches ProgramLowering.visit_Subscript (src/gt4py/next/ffront/past_to_itir.py:520), where assert isinstance(node.value.type, (ts.TupleType, ts.NamedCollectionType)) turns it into an AssertionError instead of a DSLError. I confirmed the call path by reading both visitors and _validate_operator_call. Suggested fix: in type deduction, raise a DSLError when the value is not a collection and the subscript is an element access (i.e. slice_ is not a past.Slice, which must keep flowing through for out= field slicing).
  2. out= element access on collections type-checks but fails with an assert or a misleading error (src/gt4py/next/ffront/past_to_itir.py:448): with the new element typing, out=tup[0] now passes the is_type_or_tuple_of_type(..., ts.FieldType) check in _visit_field_operator_call, but _split_field_and_slice/_compute_field_slice raises AssertionError("Unexpected 'out' argument, must be tuple of slices or slice expression.") for the Constant index; out=coll.field fails the assert isinstance(out_arg, (past.Subscript, past.Name, past.TupleExpr)) in _visit_stencil_call_out_arg (line 458); with a domain, _ensure_no_sliced_field raises the misleading "Either only domain or slicing allowed." This was unsupported before too, but since the PR's purpose is exactly element access on collection arguments, it now type-checks and fails late/ugly. Either support it (apply tuple_get in the out-arg path) or reject it at type-deduction time with a clear message.
  3. Unresolved original_python_type gives a non-DSL error (src/gt4py/next/ffront/past_passes/type_deduction.py:165): a program parameter annotated with a NamedTuple defined in a local scope gets original_python_type = "mod:fn.<​locals>.T" (set in type_translation.make_type), and pkgutil.resolve_name then raises a raw AttributeError during subscript type deduction instead of a DSLError. The same resolve pattern pre-exists in type_translation.py:79/named_collections.py:282, so this is an error-quality edge case; wrapping the resolve in a try/except that raises a DSLError would keep diagnostics consistent.

Nits

  • src/gt4py/next/ffront/past_passes/type_deduction.py:197: new_value.type.types[new_value.type.keys.index(node.attr)] (and the same keys.index in ProgramLowering.visit_Attribute, past_to_itir.py:516) duplicates the lookup logic already implemented in NamedCollectionType.__getattr__ (type_specifications.py:184); a small helper on the type (e.g. index_of(key)) would keep it in one place.
  • src/gt4py/next/ffront/past_to_itir.py:189: out_field_name is no longer annotated and now holds a past.Expr, not a name; the variable name is slightly misleading after the Subscript.value widening.

Questions

  • Is element access on collections for out= arguments (out=tup[0], out=coll.field) planned to be supported as a follow-up, or should it be rejected explicitly (see finding 2)?
  • Is the restriction to literal integer indices intended to be permanent, or is dynamic indexing (e.g. t[i] with a scalar parameter) on the roadmap? The error message currently points users at literals only.

…programs

Subscripting a scalar or slicing a field passed as a field operator input got
through type deduction and failed on an assert in lowering. Also resolve the
NamedTuple/dataclass distinction for classes defined in a function, which
pkgutil can not resolve by name.
Attribute access on an enum or FrozenNamespace closure variable in a program
body is folded to a constant, as in field operators. It previously worked
only in embedded execution.
@havogt
havogt removed the request for review from tehrengruber November 25, 2026 12:19
…llow-up

Keep only the index checks for tuple subscripts and the rejection of
subscripted scalars here. Key-based attribute lookup, folding of enum
attributes, rejecting dataclass indexing, closure-variable element access
and sliced inputs move to a separate PR.
@havogt
havogt requested a review from tehrengruber November 26, 2026 10:42
…wn PR

This reverts commit 3969b84. The fix now
lives on tehrengruber/collapse-tuple-remapped-arg-capture, which names the
remapped arguments with unique_symbol instead of uids.
@tehrengruber-ai

Copy link
Copy Markdown

I pushed some changes on top of this PR to a separate branch (tehrengruber/align-foast-past-element-access, commit tehrengruber/gt4py@d5c6d4974). They make programs and field operators handle tuple subscripts and attribute access the same way, using one shared check:

  • Tuples: literal integer indices, negative indices allowed (like in field operators). Bool indices are rejected.
  • Named collections: access by name only (nc.u). nc[0] is rejected in both, with a hint. This drops positional access on named collections from this PR.
  • Out-of-range indices and unknown attributes now give proper errors instead of crashes.

The CollapseTuple naming fix is now its own PR.

This still needs work:

  • out=t[1] is accepted by type checking but fails later with an internal error. It should be rejected with a proper error.
  • The PR title and description still mention indexing named collections.
  • Only tested on the Python backends so far.

…ices

Named collections are accessed by field name, as in field operators. Negative
tuple indices count from the end and are lowered to the non-negative position.
Field operators accepted t[-1] but passed the negative index to tuple_get,
which the compiled backends do not handle for tuples that reach them.
…ograms

Field operators accepted bool tuple indices and raised a bare IndexError for
out-of-range ones. Both frontends now use one check: literal integers in
[-n, n), bool rejected, with a DSLError otherwise.
@havogt
havogt merged commit 890c833 into GridTools:main Dec 3, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-review Request a sandboxed AI agent review (added by a maintainer)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants