Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Nov 22, 2025

Addresses N+1 query issue from PR #9 review feedback where Category.find and WorkflowStep.find were called inside loops.

Changes

  • Pre-load categories: Single query loads all required categories, indexed by ID for O(1) lookup
  • Index workflow steps: Build hash of steps by ID to eliminate repeated WorkflowStep.find calls
  • Optimize lane lookups: Replace O(n×m) find_index calls with O(1) hash lookup
  • Add nil safety: Guard against missing category/step references with early returns

Before/After

# Before: N+1 queries in loops
lanes = steps.map do |step|
  category = Category.find(step.category_id)  # Query per step
  { name: category.name, link: "/c/#{step.category_id}" }
end

# After: Single query upfront
category_ids = steps.filter_map(&:category_id).uniq
categories_by_id = Category.where(id: category_ids).index_by(&:id)

lanes = steps.map do |step|
  category = categories_by_id[step.category_id]  # Hash lookup
  next unless category
  { name: category.name, link: "/c/#{step.category_id}" }
end.compact

Query count reduced from 1 + N + M to 3 regardless of workflow size (where N = steps, M = step options).


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 4 commits November 22, 2025 16:05
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Co-authored-by: merefield <35533304+merefield@users.noreply.github.com>
Copilot AI changed the title [WIP] Address feedback on performance improvement in PR #9 Eliminate N+1 queries in workflow visualization controller Nov 22, 2025
Copilot AI requested a review from merefield November 22, 2025 16:10
Copilot finished work on behalf of merefield November 22, 2025 16:10
@merefield merefield changed the base branch from eliminate_n_plus_1 to main November 22, 2025 16:12
@merefield merefield marked this pull request as ready for review November 22, 2025 16:13
@merefield merefield merged commit d7ad34c into main Nov 22, 2025
4 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants