perf(api): group the has-record subject ids in the database#1426
Open
gdevenyi wants to merge 1 commit into
Open
perf(api): group the has-record subject ids in the database#1426gdevenyi wants to merge 1 commit into
gdevenyi wants to merge 1 commit into
Conversation
The "with records only" datahub filter resolved its subject list with
findMany({ distinct: ['subjectId'], select: { subjectId: true }, where })
but prisma applies `distinct` in the query engine rather than pushing it
into mongodb, so the driver receives one row per *record* and collapses
them to one row per subject only after they have arrived. On a group
holding 100k records that is 100k rows transferred to produce a list of
at most a few thousand ids.
`groupBy` asks mongodb for the distinct values directly. Measured over
HTTP against a live instance with 200,300 records, median of 7:
GET /v1/subjects?hasRecord=true 366ms -> 42ms
GET /v1/subjects?groupId=<g>&hasRecord=true 67ms -> 37ms
The unscoped case is where the difference shows, and it widens with the
size of the collection: `groupBy` returns one row per subject regardless
of how many records back it.
The record query also now carries the caller's ability, which it
previously ignored. The outer subject query already constrained the
result, so this was not a data leak, but the inner query read records the
caller had no permission to read.
Note for anyone revisiting this: the issue also floated expressing the
filter as `instrumentRecords: { some: ... }` on Subject. Measured on the
same dataset that takes 26,849ms -- prisma compiles a relation filter on
mongodb into a $lookup over the whole record collection. It is 270x
slower than the code being replaced here, and carries the 100 MiB
per-document ceiling that made the same construct fail outright in #1416.
Refs #1413
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Bfen9VQemZanJLXinJ6MMG
Contributor
There was a problem hiding this comment.
Pull request overview
This PR improves the performance of the API’s “with records only” subject filter by moving subject-id deduplication into MongoDB via Prisma groupBy, avoiding Prisma’s client-side distinct behavior that transfers one row per record over the wire. It also updates the query to respect the caller’s ability when resolving subject ids from instrument records.
Changes:
- Replace
findMany({ distinct: [...] })withinstrumentRecord.groupBy({ by: ['subjectId'] })when resolving “subjects with records”. - Apply
accessibleQuery(ability, 'read', 'InstrumentRecord')to the record-side query for consistency and correctness. - Update and extend unit tests to guard against regressions (ensuring
groupByis used andabilityis threaded through).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| apps/api/src/subjects/subjects.service.ts | Switch subject-id resolution to Prisma groupBy and apply ability to the instrument record query. |
| apps/api/src/subjects/tests/subjects.service.spec.ts | Update existing hasRecord tests for groupBy and add regression tests for groupBy usage and ability propagation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+120
to
+128
| const ability = createAppAbility([ | ||
| { action: 'read', subject: 'InstrumentRecord' }, | ||
| { action: 'read', subject: 'Subject' } | ||
| ]); | ||
| await subjectsService.find({ hasRecord: true }, { ability }); | ||
| const [call] = prismaClient.instrumentRecord.groupBy.mock.lastCall as [{ where: { AND: unknown[] } }]; | ||
| // the ability contributes the first clause; without it the query would be unconstrained | ||
| expect(call.where.AND[0]).not.toStrictEqual({}); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1413.
The "with records only" datahub filter resolved its subject list with:
Prisma applies
distinctin the query engine, not in MongoDB, so the driver receives one row per record and collapses them to one row per subject only after they have arrived. On a group holding 100k records that is 100k rows transferred to produce a list of at most a few thousand ids.groupByasks MongoDB for the distinct values directly.Measured over HTTP, live instance, 200,300 records, median of 7
mainGET /v1/subjects?hasRecord=trueGET /v1/subjects?groupId=<g>&hasRecord=trueGET /v1/subjects?groupId=<g>(filter off, for reference)The unscoped case is where the difference shows, and it widens with the collection:
groupByreturns one row per subject regardless of how many records back it, so its cost is flat in records-per-subject where the old form was linear.Confirmed at the query level too — the same comparison run directly through the Prisma client:
Note
distinctgoing 197 → 1229 ms as the scope widens whilegroupBystays at ~100 ms.The issue's "better still" suggestion is wrong — please don't take it
#1413 floated expressing this as a relation filter on Subject:
and said it was "the version worth trying first". I measured it on the same dataset and it takes 26,849 ms — 270× slower than the code being replaced, let alone the replacement:
Prisma compiles a relation filter on MongoDB into a
$lookupover the whole record collection. That is the same construct that fails outright at scale in #1416 (fixed in #1423 by removing it), and it carries the same 100 MiB per-document ceiling. I've left a comment on the method saying so, and corrected the issue.Also fixed: the record query now respects the caller's ability
querySubjectIdsWithRecordsignoredabilityentirely. The outer subject query already constrained the result, so this was not a data leak — but the inner query read records the caller had no permission to read, and was inconsistent with every other query in the service.Tests
The three existing
hasRecordtests are updated to the new call and still assert the same outcomes. Two added:groupByis used andfindManyis not — a guard against thedistinctform coming back;Checks
tsc --noEmitonapps/api— cleaneslint src— cleanprettier --check— cleanvitest run(whole workspace) — 254 passed, 1 skipped, 1 failedThe one failure is
instrument-records.service.spec.ts > upload > should create records with pending set. This branch is cut frommainso it carries that pre-existing failure; #1422 fixes it.🤖 Generated with Claude Code
https://claude.ai/code/session_01Bfen9VQemZanJLXinJ6MMG