From 6e7cb19baae7eecc18e2b0dfb79a1ae9e2bf7176 Mon Sep 17 00:00:00 2001 From: daniel Date: Mon, 28 Sep 2026 23:16:54 +0200 Subject: [PATCH] fix: sort from_many? relationships in aggregate joins A duplicate `:sort?` key in the `related_subquery/3` call meant the `from_many?` branch never took effect: `Keyword.get/3` returns the first match, which is the caller's flag, and that is `false` for aggregates. The relationship still received `LIMIT 1` from `limit_from_many/5`, so it resolved to an arbitrary row rather than the sorted one. Loading the same relationship is unaffected, since Ash applies the sort on that path, so a load and an aggregate through it could disagree. --- lib/join.ex | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/join.ex b/lib/join.ex index b797e49..5e7adad 100644 --- a/lib/join.ex +++ b/lib/join.ex @@ -1218,13 +1218,14 @@ defmodule AshSql.Join do current_binding ) do case related_subquery(relationship, query, - sort?: sort?, + sort?: + sort? || Map.get(relationship, :from_many?) || + not is_nil(Map.get(relationship, :sort)), apply_filter: apply_filter, start_bindings_at: 500, refs_at_path: path, require_lateral?: require_lateral?, filter_subquery?: true, - sort?: Map.get(relationship, :from_many?), on_subquery: fn subquery -> if !Map.get(relationship, :from_many?) || Map.get(relationship, :no_attributes?) do subquery