Skip to content

[MEDIUM] N+1 queries in context.rs retrieval paths — 30+ DB queries per chat message #32

@matthewod11-stack

Description

@matthewod11-stack

Description

Every employee retrieval path in context.rs first fetches a list of IDs, then calls get_employee_context(pool, &id).await in a sequential loop. get_employee_context itself runs 3 queries per employee (basic info, ratings JOIN cycles, eNPS). At MAX_EMPLOYEES_IN_CONTEXT = 10 that's 30+ sequential DB queries on every chat message. Biggest user-visible latency issue in the backend.

Current State

  • src-tauri/src/context.rs:1198-1206 — by-name retrieval
  • src-tauri/src/context.rs:1620-1626 — by-department
  • src-tauri/src/context.rs:1659-1664 — by-theme
  • src-tauri/src/context.rs:1680-1684 — by-anniversary / termination

All sequentially call get_employee_context in a Rust for loop.

Suggested Fix

  • Add a batch variant: get_employee_contexts(pool, &ids: &[String]) -> Vec<EmployeeContext> that issues 3 SELECT ... WHERE id IN (?, ?, ...) queries (basic + ratings + eNPS), groups results by id in a HashMap<String, _>, and assembles the output vector in order.
  • Replace each loop-of-singles call site with a single batch call.
  • Cap batch IN clause at a reasonable size (SQLite limit is 999 params).

Verification

  • cargo test context passes + add a batch-retrieval test
  • Quick benchmark: time get_employee_context for 10 employees before/after — expect ~3× speedup.

Automation Hints

scope: src-tauri/src/context.rs
do-not-touch: everything else
approach: refactor-to-config
risk: medium
max-files-changed: 1
blocked-by: "#41"
bail-if: batch query results can't be cleanly grouped without breaking existing behavior

Priority

Medium — perceptible latency win, not correctness.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthardeningReliability or defense-in-depth improvementtech-debtEligible for automated overnight fixing

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions