Incorrect result on `group_by` with `sort_by` after order change in agg
Author: kdn36Created Sep 29, 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
import polars as pl
df = pl.DataFrame({"k": [0, 0, 1, 1], "a": [10, 11, 20, 21], "b": [2, 1, 4, 3]})
out = df.group_by("k", maintain_order=True).agg(pl.col("a").reverse().sort_by("b"))
print(out["a"].to_list()) # got [[11, 10], [21, 20]]
assert out["a"].to_list() == [[10, 11], [20, 21]]Log output
[[11, 10], [21, 20]]
Traceback (most recent call last):
File "repro.py", line 7, in <module>
assert out["a"].to_list() == [[10, 11], [20, 21]]
AssertionErrorIssue description
The result is sorted as if reverse() had not been applied. These give the same wrong result, [[11, 10], [21, 20]]:
pl.col("a").sort(descending=True).sort_by("b")pl.col("a").sort_by(pl.col("b").reverse())pl.col("a").sort_by("c", pl.col("b").reverse()), withcconstant
Both engines are affected, and so is over(): pl.col("a").reverse().sort_by("b").over("k") gives [11, 10, 21, 20].
AI notes: inside agg, reverse/sort only reorder each group's row positions. sort_by sorts using the key's row positions and puts them on the input, so the input's own reordering is lost. With several keys, every key is read through the first key's positions. check_groups only compares group lengths. Same root cause as #29583, but not covered by #29612.
Expected behavior
The same result as running the expression on each group separately: [[10, 11], [20, 21]].
Installed versions
Reproduces on 1.44.2 and latest main (2.0 rc).
Source: pola-rs/polars