Skip to content

[Data] Add missing output_field in aggregations - #68455

Merged
owenowenisme merged 2 commits into
ray-project:masterfrom
owenowenisme:owenowenisme/Add-output-field-for-some-aggregations
Nov 23, 2026
Merged

owenowenisme merged 2 commits into
ray-project:masterfrom
owenowenisme:owenowenisme/Add-output-field-for-some-aggregations

Conversation

@owenowenisme

Copy link
Copy Markdown
Member

Description

As title, some agg's output_field are missing, and this pr implements them.

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

Signed-off-by: You-Cheng Lin <[email protected]>
@owenowenisme
owenowenisme requested a review from a team as a code owner November 22, 2026 09:15
@owenowenisme owenowenisme added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Nov 22, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements output_field methods for several aggregation classes in python/ray/data/aggregate.py to support static schema inference, along with corresponding unit tests in python/ray/data/tests/test_infer_schema.py. The review identified a potential runtime crash in the AsList.output_field implementation where a TypeError could occur if _target_col_name is not a string, and suggested adding an explicit type check to ensure robust fallback behavior.

Comment on lines +584 to +589
def output_field(self, input_schema: "pa.Schema") -> Optional["pa.Field"]:
try:
in_type = input_schema.field(self._target_col_name).type
except (KeyError, ValueError):
return None
return pa.field(self.name, pa.list_(in_type), nullable=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If self._target_col_name is not a string (for example, if it is None), calling input_schema.field(self._target_col_name) will raise a TypeError because PyArrow's Schema.field expects a string or integer. This TypeError is not caught by the except (KeyError, ValueError): block, which will cause schema inference to crash during planning instead of returning None to trigger the fallback mechanism.

We should check if self._target_col_name is a string before attempting to look it up, matching the pattern used in Unique.output_field.

Suggested change
def output_field(self, input_schema: "pa.Schema") -> Optional["pa.Field"]:
try:
in_type = input_schema.field(self._target_col_name).type
except (KeyError, ValueError):
return None
return pa.field(self.name, pa.list_(in_type), nullable=True)
def output_field(self, input_schema: "pa.Schema") -> Optional["pa.Field"]:
if not isinstance(self._target_col_name, str):
return None
try:
in_type = input_schema.field(self._target_col_name).type
except (KeyError, ValueError):
return None
return pa.field(self.name, pa.list_(in_type), nullable=True)

pa.Schema.field(None) raises TypeError, which the except clause did not
catch, so schema inference crashed at plan time instead of falling back.

Signed-off-by: You-Cheng Lin <[email protected]>

@rayo5o rayo5o left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I compared ds.schema(fetch_if_missing=False) with ds.materialize().schema() for each of the six aggs in a groupby, over 20 Arrow input types (int8 to int64, uint8, uint64, float32, float64, decimal128, bool, string, large_string, binary, date32, timestamp with and without tz, dictionary, null, list<int16>, tensor), under SHUFFLE_V2, HASH_SHUFFLE and SORT_SHUFFLE_PULL_BASED. Wherever both sides resolve, the types match, including AsList on list and tensor columns and Unique on string and dictionary columns.

Besides the comment above, two small differences: CountDistinct declares not null while the materialized field is nullable (Count does the same on master), and on the two non-default strategies ZeroPercentage on a pa.null() column materializes as null rather than double. Pandas blocks from from_pandas have no static schema and always fall back, so they aren't covered.

The two new tests that check declared schemas fail on the merge base 13b350d, and test_infer_schema.py passes on head 226ae20 (29 passed), with the CI lock versions (pyarrow 25.0.1, pandas 2.3.3).

return (accumulator[0] / accumulator[1]) * 100.0

def output_field(self, input_schema: "pa.Schema") -> Optional["pa.Field"]:
return pa.field(self.name, pa.float64(), nullable=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This declares float64 for any input type, but the aggregation itself only works on numeric/bool columns (the docstring says "Must be a numeric column"). With a string column, ds.groupby("k").aggregate(ZeroPercentage("v")).schema() now returns zero_pct(v): double, and the ArrowNotImplementedError (equal has no kernel for (string, int64)) only shows up when the dataset runs. On the merge base, schema() raises that error right away, since it falls back to limit(1). Same for binary, date32, timestamp, dictionary, list and tensor columns.

CountDistinct.output_field has the same gap for tensor columns (Keys of type extension<...ArrowTensorTypeV2> at execution), which Unique already guards against.

_agg_output_field and the new test_quantile_on_string_falls_back both return None when the kernel can't take the type. Would it make sense to do the same here, e.g. ZeroPercentage returns None unless the column is integer/floating/decimal/boolean, and CountDistinct skips extension types?

@owenowenisme
owenowenisme merged commit 95c08de into ray-project:master Nov 23, 2026
5 checks passed
sainimal1ba-hue added a commit to sainimal1ba-hue/ray that referenced this pull request Nov 24, 2026
…put fields

Two master changes landed after these expectations were written: ray-project#68329
enabled the Top-N rewrite by default, so sort("a").limit(10) optimizes
to one TopN instead of a Sort under a Limit, and ray-project#68455 added
output_field to the remaining aggregations, so Unique over a scalar
column now declares its output type.

Update the two tests to the current plans while keeping their intent:
the requirements assertions move to the fused TopN operator, and the
unknown-output case aggregates over a nested column, which still cannot
declare its type (test_unique_on_list_column_falls_back in
test_infer_schema.py pins the fallback at the schema level).

Signed-off-by: sainimal1ba-hue <[email protected]>
owenowenisme added a commit that referenced this pull request Nov 24, 2026
## Description
With #68158 we dont have to hand-prune unused columns anymore, it
automatically push projection down. So we don't have to manually write
projection in test scripts
Can be merged after #68455 

## Related issues
> Link related issues: "Fixes #1234", "Closes #1234", or "Related to
#1234".

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: You-Cheng Lin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

3 participants