Repository navigation
Description
Current Implementation and Limitations
InstrumentsService.find loads full instrument documents, including the bundle source, for every instrument the user can read (instruments.service.ts#L285). It then calls getInstrumentInstance, which returns the cached evaluated instance when one exists and ignores the bundle (#L470-L483). After the first request, most bundles that find reads are not used. The cache is a Map with no size limit and no eviction.
find runs on:
- each
GET /v1/instruments/infocall (#L378). It runs a second time forkind=SERIES(#L384-L385), butapps/webdoes not send that filter. - each
GET /v1/instruments/listcall (#L491). - each dashboard load, because
count()isfind().length(#L82-L87) andSummaryServicecalls it (summary.service.ts#L39). The dashboard also calls/v1/instruments/info(dashboard.tsx#L28), so one dashboard load runsfindtwice.
The cost scales with the total size of all bundles, not with the number of instruments the request needs. The built-in bundles are about 44 KB in total, but a bundle that inlines media as data URLs can be many megabytes. A projection saves the transfer from MongoDB and the BSON decode. MongoDB still reads each full document from storage.
To measure the size of the bundles on a deployment:
db.InstrumentModel.aggregate([
{ $project: { s: { $bsonSize: "$$ROOT" } } },
{ $group: { _id: null, n: { $sum: 1 }, totalMB: { $sum: { $divide: ["$s", 1048576] } }, maxKB: { $max: { $divide: ["$s", 1024] } } } }
])Also found while checking this code (fix here or in separate issues):
SummaryServicecallscount()with no ability and no group IDs. Thus the dashboard instrument count includes series instruments that belong to other groups.- A cold cache does not merge concurrent loads. Two requests that need the same uncached bundle both evaluate it.
findcan race withdeleteById. Iffindreads a row beforedeleteByIdremoves it,getInstrumentInstancecan put the deleted instance back into the cache afterdeleteByIdclears it (#L262-L266).
Associated Application Components
Server
Proposed Solution
-
Move the
whereclause offindinto a private helper, so thatfindandcountuse the same filter. -
In
find, select onlyidwith thatwhereclause. Then readbundleonly for the IDs that are not invirtualizationService.context.instruments:const rows = await this.instrumentModel.findMany({ select: { id: true }, where }); const cache = this.virtualizationService.context.instruments; const missingIds = rows.map((row) => row.id).filter((id) => !cache.has(id)); if (missingIds.length > 0) { const uncached = await this.instrumentModel.findMany({ select: { bundle: true, id: true }, where: { id: { in: missingIds } } }); await this.instantiate(uncached); } const instances = rows.flatMap((row) => cache.get(row.id) ?? []);
Do not write
cache.get(row.id)!. A concurrentdeleteByIdcan remove a row between the two queries, and the!then hides anundefinedthat fails later. Keep thekindfilter after instantiation, as now (#L310-L314). -
When
count()has nokindfilter, useinstrumentModel.count({ where }). The dashboard calls it without arguments. This changes one behavior: now, one bundle that fails to evaluate makes/v1/summaryreturn 500 (#L472-L478). After the change, it does not. State this in the PR.
Tests.
- Unit tests:
finddoes not selectbundlefor cached IDs;finddrops a row whose instance is not in the cache;count()withoutkindcallsinstrumentModel.countand does not evaluate bundles. - The existing unit test at instruments.service.spec.ts#L511 asserts the exact
findManyarguments. It must change with the new query shape. - e2e: the existing e2e tests for the instrument list and the dashboard do not assert the instrument count. Add an assertion on the dashboard instrument count, so that a wrong
whereincount()fails.
Estimated Difficulty
Low
Priority
Low
Activity
joshunrau commentedon Oct 26, 2026
Still applies on
main(d86740e).findhas more callers than the issue lists,findByIdhas the same problem, and scopingcount()would not make the dashboard card correct.More callers of
findOne dashboard load runs
findthree times, not twice.GET /v1/instrument-records(dashboard.tsx:35) reachesinstrument-records.service.ts:265-267, which callsinstrumentsService.find({ kind })to buildinstrumentKindIds. Withkindunset that is every instrument. The only instrument delete outside setup'sdropDatabaseis indeleteById(instruments.service.ts:263), and it refuses an instrument that has records (:237-241). So the$inat:278filters nothing, and the lookup can be skipped whenkindis unset. That is the no-migration half of #1408 item 5. #1807 changes this method, so make the edit after it lands. #1714 would drop this request from the dashboard, but every datahub records query still pays for it.The admin
GET /v1/instruments/series(d7147b0) runsfindtwice once any series exists (:556-557).Same pattern in
findByIdfindById(:352-375) reads the whole row, but onlyfindBundleById(:332,:338) usesbundle. These callers discard it:instrument-records.service.ts:87,:102and:489(create and upload):199(export, which reads onlyidandinternal):262(the existence check infind; feat: add the instrument hub and record provenance #1807 adds a second one):576-580, which then callsgetInstrumentInstanceagaingateway.synchronizer.ts:118andfiles.service.ts:126Record creation runs for every record the gateway syncs (
gateway.synchronizer.ts:198).deleteById(:210-219) andupdateSeriesArchive(:462-468) also read the full row only to evaluate it. Put the cache-aware load in one private method that all of these use.findByIdthen returnsWithID<AnyInstrument>, andfindBundleByIdreadsbundleitself. The step 1 helper should also replace the series-groupORrepeated at:298-305and:361-365.Cache
eval.Mapoff the vm context (instruments.module.ts:21) into a private field. Bundles read only__resolveImportfrom it (packages/instrument-bundler/src/bundle.ts:14), butvm.createContextmakesinstrumentsa global that every bundle can replace.instruments.module.test.tsandinstruments.service.test.ts:187-191change with it.deleteByIdrace.findcan read a bundle before the delete and cache it after the eviction. Series ids hash only content, group and title (:417-425), so a series re-created with a new description gets the old id and the stale instance. Key the cache onidpluscreatedAt, both read by the id query.The dashboard count
read Instrumentis unconditional for every role (ability.factory.ts:60,:80,manage allfor ADMIN), so passingabilitytocount()changes nothing. Passing group ids only drops other groups' series; the card would still count every edition and every instrument outside the group's access list. The dialog it opens lists/v1/instruments/info(latest edition, current group's series only) filtered tocurrentGroup.accessibleInstrumentIds(dashboard.tsx:42-46).Recommendation: remove
counts.instrumentsfrom$Summary(packages/schemas/src/summary/summary.ts:13). Its only reader isdashboard.tsx:265. Have the card show the length of the dialog's list. That takes afindout of/v1/summaryand leavesInstrumentsService.count()unused, so delete it and drop step 3. State the/v1/summaryresponse change in the PR. The loader prefetches only the summary (:649). Either giveuseInstrumentInfoQueryaqueryOptionsfactory and prefetch it (apps/web/AGENTS.md), or add a loading state to the card (#1757). #1714 also edits$Summaryandsummary.service.test.ts, so land one and rebase the other.Open question: an administrator with no group sees no group-owned series in the dialog, while today's card counts every series on the instance. Which should the admin card show?
Tests
instruments.service.test.ts: the exact-findManytest is now at:764(efa9070 renamed.spec.tsto.test.ts). The test at:1279readsfindMany.mock.lastCall, which becomes the bundle query, so it changes too. Add:findByIdselects no bundle on a cache hit; concurrent coldfindcalls evaluate each bundle once; a rejectedevalis not cached; a re-created series with the same id is evaluated again.summary.service.test.ts: remove the instruments count from:55-62, lowerEXPECTED_QUERIESat:118from 20 to 19, and drop theInstrumentsServicemock.apps/web/src/routes/_app/__tests__/dashboard.test.tsx: the card shows the dialog's row count.testing/src/specs/dashboard.spec.ts: create two groups with a series each, then a group manager in the first, then callauthenticateAs.currentGroupis decoded from the access token (apps/web/src/store/slices/auth.slice.ts:9-12), so the series must exist before sign-in;isolatedGroupManagersigns in too early (testing/src/support/fixtures.ts:156-163). Assert that the dialog lists the first series and not the second, and that the card equals the row count. This needs a row testid indashboard.tsxand a dialog locator indashboard.page.ts. Do not assert an exact value of today'scount(): it is instance-wide, andadmin-instruments.spec.tscreates series in the same database.#1408 is the schema epic. This issue is its item 2 without a migration, and its item 4 goes away if
count()is deleted. Land this first.Triage note written with Claude Code. Code references point at
main@d86740e.perf(api): read instrument bundles only for uncached instances