#29583·polars

Incorrect result on `group_by` with `sort_by` in aggregation

Author: kdn36Created Sep 28, 2026Updated Sep 29, 2026
LabelsbugpythonacceptedP-high

Checks

  • I have checked that this issue has not already been reported.
  • I have confirmed this bug exists on the latest version of Polars.

Reproducible example

python
import polars as pl

df = pl.DataFrame({"k": [0, 0, 0, 1, 1, 1], "a": [10, 11, 12, 20, 21, 22], "b": [1.0] * 6})
out = df.group_by("k", maintain_order=True).agg(pl.col("a").head(1).sort_by(pl.col("b").max()))

print(out["a"].to_list())  # got [[10], [11]]
assert out["a"].to_list() == [[10], [20]]

Log output

bash
[[10], [11]]
Traceback (most recent call last):
  File "/home/koen/my-polars/triage/mre1.py", line 9, in <module>
    assert out["a"].to_list() == [[10], [20]]

Issue description

Incorrect data is returned.

AI notes: sort_by() replaces each group's rows with row i of the frame (i = group ordinal). Affects group_by (both engines) and over().

Expected behavior

See repro.

Installed versions

Reproduces on 1.44.2 and latest main (2.0 rc).