Pass the ordered scope into audit event offset optimization

What does this MR do and why?

AuditEvents::OffsetOptimization.paginate_with_offset_optimization called audit_events.order(id: :desc) and then passed the original, unordered relation to PaginationWithIndexOnlyScan. That helper only builds its index-only-scan query when the scope has an ORDER BY, so the group and project audit events APIs fell back to plain offset pagination from page 100 on — the case the optimization was added for.

The ordered relation is now passed as scope: audit_events.order_by(params[:sort], use_created_at: true), which is ORDER BY created_at, id (descending by default, ascending when the finder is called with sort: 'created_asc' (the APIs only pass created_at DESC, id DESC)). That is the same order pages 1–99 already use, and it matches the (group_id, created_at, id) index and the created_at partition key. Ordering by id alone is not served by that index.

A regression spec asserts that a page past the threshold uses the index_only_scan_pagination_cte query, returns rows in created_at, id order, and does not match id-only order.

Closes #639234 (closed)

Query plans

@huzaifaiftikhar1 compared plans on the gitlab-org group, page 100, per_page 20 (postgres.ai session):

Order Time Buffers
id DESC (previous revision of this MR) 1,766.8 ms ~16,400
created_at DESC, id DESC (this revision) 2.1 ms ~362

I cannot re-run postgres.ai as a community contributor. With created_at, id, the CTE is expected to scan the (group_id, created_at, id) index backwards and stop after the rows it needs, and the LATERAL lookup filters on both columns so PostgreSQL can prune to a single partition.

How to set up and validate locally

bin/rspec ee/spec/finders/audit_events/offset_optimization_spec.rb

MR acceptance checklist

Evaluate this MR against the MR acceptance checklist.

Edited by Priyanshu Jha

Merge request reports

Loading
Loading