Audit events offset optimization never applies because its order is discarded

Summary

The audit events offset optimization never applies. AuditEvents::OffsetOptimization.paginate_with_offset_optimization discards the result of .order:

audit_events.order(id: :desc) # rubocop:disable CodeReuse/ActiveRecord -- needed for offset optimization

Gitlab::Pagination::Offset::PaginationWithIndexOnlyScan.new(
  scope: audit_events,
  ...

https://gitlab.com/gitlab-org/gitlab/-/blob/master/ee/app/finders/audit_events/offset_optimization.rb#L24

ActiveRecord::Relation#order returns a new relation, so the helper receives the finder's unordered scope. PaginationWithIndexOnlyScan only builds its index-only-scan query when the scope has an ORDER BY, so the group and project audit events APIs fall back to plain offset pagination from page 100 on, the case the optimization was added for in 031541b1.

The API's paginate then adds ORDER BY id ASC to the unordered relation, so those pages may also sort differently from earlier pages. Not verified.

The specs in ee/spec/finders/audit_events/{group,project}_audit_event_finder_spec.rb check that the helper is called, not that it optimizes the query or the order of the results, so they pass either way.

Proposal

Pass the ordered relation, scope: audit_events.order(id: :desc), and add a spec that asserts the optimized query (the index_only_scan_pagination_cte CTE) and the result order on a page past the threshold.

Found while reusing the helper in !269175 (merged), which doesn't change this behaviour.

Edited by 🤖 GitLab Bot 🤖