Skip to content

fix: resolve N+1 query in ConfigReport.summarise#10950

Open
raman1236 wants to merge 1 commit into
theforeman:developfrom
raman1236:fix/config-report-n-plus-1-query
Open

fix: resolve N+1 query in ConfigReport.summarise#10950
raman1236 wants to merge 1 commit into
theforeman:developfrom
raman1236:fix/config-report-n-plus-1-query

Conversation

@raman1236
Copy link
Copy Markdown

Description

Resolves the N+1 query in ConfigReport.summarise that has been marked with a TODO comment since the method was written.

Problem

The summarise method performed one SQL query per host to fetch recent reports:

hosts.flatten.each do |host|
  host.reports.recent(time).select(:status).each do |r|
    # ...
  end
end

For a page listing 100 hosts, this generates 100 separate queries.

Fix

Replaced the per-host queries with a single batch query that loads all reports at once:

hosts_by_id = hosts.flatten.index_by(&:id)
reports_by_host = ConfigReport.where(:host_id => hosts_by_id.keys)
                              .recent(time)
                              .select(:host_id, :status)
                              .group_by(&:host_id)

The reports are then grouped by host_id in Ruby, maintaining the same behavior while reducing database round-trips from N+1 to 1.

Copy link
Copy Markdown
Member

@ofedoren ofedoren left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, @raman1236, could you please create a new ticket (https://projects.theforeman.org/projects/foreman/issues/new) and use its number in commit message? Also, small question inline.

Comment thread app/models/config_report.rb Outdated
@raman1236
Copy link
Copy Markdown
Author

Friendly ping — this PR resolves an N+1 query in ConfigReport.summarise by eager loading the associated records. Would appreciate a review when you have a moment. Thanks!

@adamruzicka
Copy link
Copy Markdown
Contributor

Friendly ping

There is an unanswered question from three weeks ago (comment) and the commit message wasn't reworded as requested either (comment). The ball is in your court

@raman1236 raman1236 force-pushed the fix/config-report-n-plus-1-query branch from 1d63bbf to 4da28cd Compare May 30, 2026 18:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants