diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 00000000..4e071d60 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-05-18 - Distinct Counting with Prisma in Node +**Learning:** Found O(N) operation measuring distinct array elements retrieved from DB (`new Set(rows.map(row => row.projectId)).size`) after a `findMany` query. This consumes extra JS memory and compute time as array sizes grow. +**Action:** Replace `findMany` followed by JS `Set` operations with Prisma `findMany({ distinct: ["projectId"], select: { projectId: true } }).length` for better performance at the DB layer, as Prisma `count` doesn`t support distinct in this project version. diff --git a/src/server/api/routers/judging.ts b/src/server/api/routers/judging.ts index f206af8e..0568b510 100644 --- a/src/server/api/routers/judging.ts +++ b/src/server/api/routers/judging.ts @@ -2126,9 +2126,12 @@ export const judgingRouter = createTRPCRouter({ }); if (duplicate) throw new TRPCError({ code: "CONFLICT", message: "This judge already has that scoring scope." }); + // ⚡ Bolt: Push deduplication to the DB using `distinct` and `.length` instead of fetching everything and making a JS Set. + // Why: `findMany` + mapping to JS arrays and Sets takes more memory and compute time for large sets. + // Impact: Avoids fetching duplicate rows, avoids Set allocations, and lowers latency (O(1) JS side with smaller arrays). const projectCount = await ctx.prisma.judgingAssignment - .findMany({ where: { judgeId: judge.id }, select: { projectId: true } }) - .then(rows => new Set(rows.map(row => row.projectId)).size); + .findMany({ where: { judgeId: judge.id }, distinct: ["projectId"], select: { projectId: true } }) + .then(rows => rows.length); const alreadyVisits = await ctx.prisma.judgingAssignment.count({ where: { judgeId: judge.id, projectId: assignment.projectId }, });