Projects::MergeRequests::DiffsController#show.json has slow SQL queries

image

[
  "app/finders/environments_finder.rb:28:in `execute'",
  "app/models/merge_request.rb:1130:in `block in environments_for'",
  "app/models/merge_request.rb:1140:in `environments_for'",
  "app/controllers/projects/merge_requests/diffs_controller.rb:54:in `render_diffs'",
  "app/controllers/projects/merge_requests/diffs_controller.rb:13:in `show'",
  "ee/lib/gitlab/ip_address_state.rb:10:in `with'",
  "ee/app/controllers/ee/application_controller.rb:43:in `set_current_ip_address'",
  "lib/gitlab/session.rb:11:in `with_session'",
  "app/controllers/application_controller.rb:462:in `set_session_storage'",
  "app/controllers/application_controller.rb:456:in `set_locale'",
  "ee/lib/omni_auth/strategies/group_saml.rb:41:in `other_phase'",
  "ee/lib/gitlab/jira/middleware.rb:19:in `call'"
]

We see that in https://gitlab.com/gitlab-org/gitlab/blob/a68e2b755b30c88061ea8bcf975db6a8fd15938e/app/controllers/projects/merge_requests/diffs_controller.rb#L54 we call:

@environment = @merge_request.environments_for(current_user).last

But in https://gitlab.com/gitlab-org/gitlab/blob/41f3809d8a192910c87bda63b35140be1ba43397/app/finders/environments_finder.rb#L27-28, we call to_a:

    environments = project.environments.available
      .where(id: environment_ids).order_by_last_deployed_at.to_a

It seems like we could pass a limit parameter here.

Edited by Stan Hu