Skip to content

Instrument queries read every bundle from MongoDB even when the evaluated instance is cached #1537

Closed

Description

@gdevenyi

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/info call (#L378). It runs a second time for kind=SERIES (#L384-L385), but apps/web does not send that filter.
  • each GET /v1/instruments/list call (#L491).
  • each dashboard load, because count() is find().length (#L82-L87) and SummaryService calls it (summary.service.ts#L39). The dashboard also calls /v1/instruments/info (dashboard.tsx#L28), so one dashboard load runs find twice.

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):

  • SummaryService calls count() 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.
  • find can race with deleteById. If find reads a row before deleteById removes it, getInstrumentInstance can put the deleted instance back into the cache after deleteById clears it (#L262-L266).

Associated Application Components

Server

Proposed Solution

  1. Move the where clause of find into a private helper, so that find and count use the same filter.

  2. In find, select only id with that where clause. Then read bundle only for the IDs that are not in virtualizationService.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 concurrent deleteById can remove a row between the two queries, and the ! then hides an undefined that fails later. Keep the kind filter after instantiation, as now (#L310-L314).

  3. When count() has no kind filter, use instrumentModel.count({ where }). The dashboard calls it without arguments. This changes one behavior: now, one bundle that fails to evaluate makes /v1/summary return 500 (#L472-L478). After the change, it does not. State this in the PR.

Tests.

  • Unit tests: find does not select bundle for cached IDs; find drops a row whose instance is not in the cache; count() without kind calls instrumentModel.count and does not evaluate bundles.
  • The existing unit test at instruments.service.spec.ts#L511 asserts the exact findMany arguments. 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 where in count() fails.

Estimated Difficulty

Low

Priority

Low

Activity

  1. added
    Enhancement
    on Sep 11, 2026
  2. added
    Priority: Low
    Difficulty: Medium
    Area: API
    Performance
    on Sep 27, 2026
  3. joshunrau commented on Oct 26, 2026

    @joshunrau
    Collaborator

    Still applies on main (d86740e). find has more callers than the issue lists, findById has the same problem, and scoping count() would not make the dashboard card correct.

    More callers of find

    One dashboard load runs find three times, not twice. GET /v1/instrument-records (dashboard.tsx:35) reaches instrument-records.service.ts:265-267, which calls instrumentsService.find({ kind }) to build instrumentKindIds. With kind unset that is every instrument. The only instrument delete outside setup's dropDatabase is in deleteById (instruments.service.ts:263), and it refuses an instrument that has records (:237-241). So the $in at :278 filters nothing, and the lookup can be skipped when kind is 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) runs find twice once any series exists (:556-557).

    Same pattern in findById

    findById (:352-375) reads the whole row, but only findBundleById (:332, :338) uses bundle. These callers discard it:

    • instrument-records.service.ts:87, :102 and :489 (create and upload)
    • :199 (export, which reads only id and internal)
    • :262 (the existence check in find; feat: add the instrument hub and record provenance #1807 adds a second one)
    • :576-580, which then calls getInstrumentInstance again
    • gateway.synchronizer.ts:118 and files.service.ts:126

    Record creation runs for every record the gateway syncs (gateway.synchronizer.ts:198). deleteById (:210-219) and updateSeriesArchive (: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. findById then returns WithID<AnyInstrument>, and findBundleById reads bundle itself. The step 1 helper should also replace the series-group OR repeated at :298-305 and :361-365.

    Cache

    • Cache the promise rather than the result, and delete the entry when it rejects. Concurrent cold loads then share one eval.
    • Move the Map off the vm context (instruments.module.ts:21) into a private field. Bundles read only __resolveImport from it (packages/instrument-bundler/src/bundle.ts:14), but vm.createContext makes instruments a global that every bundle can replace. instruments.module.test.ts and instruments.service.test.ts:187-191 change with it.
    • Step 2 does not close the deleteById race. find can 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 on id plus createdAt, both read by the id query.

    The dashboard count

    read Instrument is unconditional for every role (ability.factory.ts:60, :80, manage all for ADMIN), so passing ability to count() 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 to currentGroup.accessibleInstrumentIds (dashboard.tsx:42-46).

    Recommendation: remove counts.instruments from $Summary (packages/schemas/src/summary/summary.ts:13). Its only reader is dashboard.tsx:265. Have the card show the length of the dialog's list. That takes a find out of /v1/summary and leaves InstrumentsService.count() unused, so delete it and drop step 3. State the /v1/summary response change in the PR. The loader prefetches only the summary (:649). Either give useInstrumentInfoQuery a queryOptions factory and prefetch it (apps/web/AGENTS.md), or add a loading state to the card (#1757). #1714 also edits $Summary and summary.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-findMany test is now at :764 (efa9070 renamed .spec.ts to .test.ts). The test at :1279 reads findMany.mock.lastCall, which becomes the bundle query, so it changes too. Add: findById selects no bundle on a cache hit; concurrent cold find calls evaluate each bundle once; a rejected eval is not cached; a re-created series with the same id is evaluated again.
    • summary.service.test.ts: remove the instruments count from :55-62, lower EXPECTED_QUERIES at :118 from 20 to 19, and drop the InstrumentsService mock.
    • 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 call authenticateAs. currentGroup is decoded from the access token (apps/web/src/store/slices/auth.slice.ts:9-12), so the series must exist before sign-in; isolatedGroupManager signs 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 in dashboard.tsx and a dialog locator in dashboard.page.ts. Do not assert an exact value of today's count(): it is instance-wide, and admin-instruments.spec.ts creates 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: APIDifficulty: MediumEnhancementPerformancePriority: Low

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions