DEV Community

Cover image for The order that got thrown away: fixing GitLab's audit event offset optimization
Priyanshu Jha
Priyanshu Jha

Posted on

The order that got thrown away: fixing GitLab's audit event offset optimization

GitLab has an optimization for deep pages of audit events. On the group and project APIs, from page 100 on, it was never used. The order the helper needs was computed, then thrown away.

This is the story of gitlab-org/gitlab!269899. The first version put the order back, but ordered by id alone, and a page that should have been cheap still took about 1.8 seconds. A database review changed the order to match the index and the partition key. I'll cover the discarded order, the query plans, and the spec review that made the page contents explicit.

The issue: an optimization that could not see its ORDER BY

The issue was gitlab-org/gitlab#639234, opened by Leaminn Ma. It is a short report, and the bug is in three lines:

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

Gitlab::Pagination::Offset::PaginationWithIndexOnlyScan.new(
  scope: audit_events,
  ...
Enter fullscreen mode Exit fullscreen mode

.order returns a new relation. The original, unordered audit_events was what got passed in. PaginationWithIndexOnlyScan only builds its index-only-scan query when the scope already has an ORDER BY. Without one, the group and project audit event APIs fell back to plain offset pagination from page 100 on — the case the optimization was added for.

Pages 1 to 99 were already ordered by created_at, id (descending by default). Page 100 was supposed to keep that order and change how the offset was planned. Instead, it lost the optimization, and if a later change had passed a different order through, it could also have lost consistency at the page 99/100 boundary.

Version 1: pass the order, but order by id

The first commit (365ab0beb7) did what the issue asked: stop discarding the order, and pass the ordered relation into the helper.

Gitlab::Pagination::Offset::PaginationWithIndexOnlyScan.new(
  scope: audit_events.order(id: :desc), # rubocop:disable CodeReuse/ActiveRecord -- needed for offset optimization
  page: params[:page],
  per_page: params[:per_page]
).paginate_with_kaminari
Enter fullscreen mode Exit fullscreen mode

That is enough to turn the optimization on. It is not enough to make it cheap. Nate Rosandich asked Huzaifa Iftikhar to review, and Huzaifa came back with a blocker and plans from postgres.ai, against the gitlab-org group, page 100, 20 rows per page:

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

The numbers have a concrete cause. There is a (group_id, created_at, id) index, and the table is partitioned by created_at. There is no index on (group_id, id). With id DESC, the CTE had to read about 176k index entries across partitions and sort them, and the LATERAL lookup could not skip partitions because it filtered on id only. With created_at, id, the CTE can scan the index backwards and stop after the rows it needs, and the lookup hits a single partition.

Huzaifa also noted that created_at, id is already the order of pages 1 to 99, so the page 99/100 boundary does not repeat or skip rows.

Version 2: the same order the rest of the API uses

The second commit (37e3f23083) stopped inventing an id-only order and reused the finder's order_by:

# Same order as pages 1-99; created_at, id matches the
# (group_id|project_id, created_at, id) indexes and the partition key.
Gitlab::Pagination::Offset::PaginationWithIndexOnlyScan.new(
  scope: audit_events.order_by(params[:sort], use_created_at: true),
  page: params[:page],
  per_page: params[:per_page]
).paginate_with_kaminari
Enter fullscreen mode Exit fullscreen mode

order_by(..., use_created_at: true) is created_at, id, descending by default, and ascending when sort is created_asc. That also covers project audit events, which use a (project_id, created_at, id) index.

Huzaifa re-ran the plans, including a project case and a filtered author_id path, and asked Adam Hegyi for a database maintainer review and Harsimar Sandhu for a backend maintainer review. Adam approved the database side. The author_id path still needs a sort; that is pre-existing and was left out of scope. Planning time of 85 to 108 ms, from 151 partitions, is also paid by the existing queries.

The spec review: assert the row, and hit the tie-break

The regression spec records the SQL, asserts that a page past the threshold uses index_only_scan_pagination_cte, and checks which event comes back. The six events are created so that insertion order (and therefore id) is the opposite of created_at, except for the last two, which share a timestamp:

# created_at is assigned opposite to insertion order so ordering by id
# alone would return a different page than created_at, id.
let_it_be(:events) do
  [
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time + 4.days),
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time + 3.days),
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time + 2.days),
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time + 1.day),
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time),
    create(:audit_events_group_audit_event, group_id: group.id, created_at: base_time)
  ]
end
Enter fullscreen mode Exit fullscreen mode

Harsimar left four comments, all of which I applied.

The comment above the call talked about group events and about the old id-only line. He asked to mention project events too, and to drop the reference to code that would soon be gone. The three-line comment now in the snippet above is his wording.

The first version of the spec built expected_rows with the same order_by(..., use_created_at: true) call as the code under test. If order_by drifted, the expectation would drift with it. He asked for a literal instead: with per_page: 1 and page: 3, descending should return events[2], ascending events[3].

it 'uses the index-only-scan query and preserves created_at, id descending order on a later page' do
  results, recorder = paginate

  expect(recorder.log).to include(a_string_matching(/index_only_scan_pagination_cte/))
  expect(results).to eq([events[2]])
end
Enter fullscreen mode Exit fullscreen mode

He also noticed that page: 3 never lands on the two events that share base_time, so the spec did not prove that id breaks a created_at tie on the CTE plus LATERAL path. For descending order, page: 5 returns events[5]; a plain id ascending order would have returned events[4]. That example is in the final spec.

One more note, which only changed the MR description: the group and project APIs never pass sort, so created_asc is not reachable from them. Handling it is still right, because it matches BaseAuditEventFinder#sort. The description now says so, instead of implying the API takes that parameter.

Harsimar approved it after those changes. The MR merged on 25 November 2026.

What I took away

1. A discarded return value can disable a whole optimization. .order does not mutate the relation. If a comment says the order is "needed for offset optimization," the next line has to use the object that comment just built.

2. Turning the optimization on is not the same as making it use an index. Version 1 was correct in the narrow sense: the helper saw an ORDER BY and built the CTE. The plan still sorted about 176k rows. The reviewer's plans were the difference between "it works" and "it is usable."

3. Paginate in the same order on both sides of the threshold. Pages 1–99 already used created_at, id. An id-only order from page 100 would have been a second bug at the boundary, even if it had been fast.

4. Do not let the expectation call the same method as the code under test. A literal row is a bit drier to write. It is also the only way the example fails if order_by changes.

5. If you created a tie so you could test a tie-break, land a page on that tie. Data that is never selected does not protect the path you cared about.

Links

Thanks to Leaminn Ma for a bug report that already named the discarded order, to Huzaifa Iftikhar for the plans and the blocker that changed the sort, to Adam Hegyi for the database maintainer review, and to Harsimar Sandhu for the comment and spec review.

If you've been thinking about contributing to GitLab, the community issues are a great place to start: contributors.gitlab.com.

Top comments (0)