# Bug Fixes - December 9, 2025 ## Bug 1: Unreachable Return Statement in `costOptimization` Resolver ### Issue The `costOptimization` resolver in `api/src/schema/resolvers.ts` had an unreachable return statement at line 407. Lines 397-406 already returned the mapped recommendations, making line 407 dead code that would never execute. ### Root Cause Incomplete refactoring where both the mapped return value and the original return statement were left in place. ### Fix Removed the unreachable `return billingService.getCostOptimization(args.tenantId)` statement at line 407. ### Files Changed - `api/src/schema/resolvers.ts` (line 407) --- ## Bug 2: N+1 Query Problem in `getResources` Function ### Issue The `getResources` function in `api/src/services/resource.ts` executed one query to fetch resources, then called `mapResource` for each row. The `mapResource` function executed an additional database query to fetch site information for every resource (line 293). This created an N+1 query problem: if you fetched 100 resources, you executed 101 queries instead of 1-2 optimized queries. ### Impact - **Performance**: Severely degraded performance with large datasets - **Database Load**: Unnecessary database load and connection overhead - **Scalability**: Does not scale well as the number of resources grows ### Root Cause The original implementation fetched resources first, then made individual queries for each resource's site information. ### Fix 1. **Modified `getResources` function** to use a `LEFT JOIN` query that fetches both resources and sites in a single database query 2. **Created `mapResourceWithSite` function** to map the joined query results without making additional database queries 3. **Preserved `mapResource` function** for single resource lookups (used by `getResource` and other functions) ### Performance Improvement - **Before**: N+1 queries (1 for resources + N for sites) - **After**: 1 query (resources and sites joined) - **Example**: Fetching 100 resources now uses 1 query instead of 101 queries ### Files Changed - `api/src/services/resource.ts`: - Modified `getResources` function (lines 47-92) - Added `mapResourceWithSite` function (lines 303-365) - Preserved `mapResource` function for backward compatibility --- ## Testing Recommendations 1. **Bug 1**: Verify that `costOptimization` resolver returns the correct recommendations without errors 2. **Bug 2**: - Test `getResources` with various filter combinations - Verify that site information is correctly populated - Monitor database query count to confirm N+1 problem is resolved - Test with large datasets (100+ resources) to verify performance improvement --- ## Verification Both bugs have been verified: - ✅ Bug 1: Unreachable code removed - ✅ Bug 2: N+1 query problem fixed with JOIN query - ✅ No linter errors introduced - ✅ Backward compatibility maintained (single resource lookups still work)