chore: Add (currently failing) test for aggregates ignoring relationship limit#801
Merged
Merged
Conversation
Contributor
|
This has been fixed in latest ash_sql |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
An aggregate over a
has_manythat declares a limit counts/lists all related rows instead of the limited top-N.count(top_5_posts)should be bounded to 5.Reproduction (failing test on main over the existing
Comment.top_ratings, which islimit: 2, sort: [score: :desc]):Root cause (
ash_sql/lib/aggregate.ex): inget_subquery/…(the relationship-path clause),on_subqueryrunsselect_all_aggregates(theGROUP BY+count/array_agg) beforerelated_subquerycallslimit_from_many(join.ex:397). So any limit is applied after grouping — it caps the number of groups, not rows-per-group. The generated SQL putsLIMITafterGROUP BY resource_idinside the lateral join.What the fix needs: when the source relationship has
limit/offset, the correlated+sorted rows must be wrapped in an inner… ORDER BY <rel.sort> LIMIT nsubquery before the aggregate folds them:Attempt / how far it got: gating on
rel.limit, I passedsort?: trueand split the defaultapply_relationship_subqueryto build the inner correlated+ordered+limited subquery, then group outside. The inner subquery builds correctly (verified:parent_ascorrelation +ORDER BY score DESC + LIMIT). The blocker is composing the grouped outer level into theleft_lateral_join— Ecto raises "invalid query was interpolated in a join"; the added nesting level needs theas/parent_as+start_bindings_at/currentbinding bookkeeping to be rebased, which the single-level aggregate path doesn't currently do.Contributor checklist
Leave anything that you believe does not apply unchecked.