Repository navigation
Conversation
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
|
This is strong, careful work on a hard issue (#1407), but I wouldn't merge it as is. It has one real performance defect in the area the issue is about, one unmarked breaking change, and one product decision that should be made deliberately. I read the full source diff and tests, and ran this PR's decoder and stream construction locally. CI is green (lint, coverage, e2e). I did not run the stack end to end or measure memory on a live instance. What works
Action items1. Client decode is quadratic in frame size
Projected decode time for 100,000 records (the cap), by network chunk size:
Method: frames built with Capping frames by rows instead of by records fixes it. With 0.14 MiB frames, the 30-measure case at 64 KiB chunks dropped from 10.5 s to 0.6 s for the same 6,000 records. A length prefix per frame, so the client decodes each frame once when it is complete, should also work, but I did not test it. The resume-from- 2. The breaking change is unmarked
Either mark the commit breaking ( 3. The 100,000-record cap is a product decisionThe issue left "refuse past N rows, or run an async job" open. This PR picks the cap ( 4. A performance PR needs measurementsThere are no before/after numbers for time or memory. Please add them for the issue's scenario, and for an instrument with 30 or more measures per record; that case is what would have caught item 1. 5. Two
|
gdevenyi
left a comment
There was a problem hiding this comment.
Thanks for tackling #1407 — replacing the buffered export + worker fan-out with paged msgpackr streaming and subject scoping is much cleaner. Before merging, please address these items:
- Handle missing joined
Subject/Sessiondocuments and unsetsubject.sexinqueryExportPage(apps/api/src/instrument-records/instrument-records.service.ts:662-692,apps/api/src/instrument-records/export-records.ts:23-35): Both$unwindstages setpreserveNullAndEmptyArrays: true(sinceSessionsService.deleteByIdand non-force or cross-groupSubjectsService.deleteByIdcan leaveInstrumentRecords whoseSessionorSubjectdocument is gone), yet$projectreadssubject.idfrom'$subject._id'instead of'$subjectId'andsession.idfrom'$session._id'instead of'$sessionId', and leavessubject.sex,session.date, andsession.typewithout$ifNull. When$subjectis absent,record.subject.idisundefinedbehind theas unknown as RawExportRecord[]cast andremoveSubjectIdScope(record.subject.id)throwsTypeError, aborting the export; whensubject.sexis unset on a custom-ID subject,subjectSexisundefinedrather thannull, causingJSON.stringifyinbuildJsonExportBlobto omit the"subjectSex"key. Please projectsubject.id/session.idfrom the foreign keys onInstrumentRecord, normalize the nullable joined fields with$ifNullsoRawExportRecordmatches every row, and add unit test cases for missing$subject/$sessionand unsetsubject.sex. - Rethrow page errors in
generateChunksafter logging (apps/api/src/instrument-records/instrument-records.service.ts:264-281): Swallowing errors ingenerateChunkscauses a Page-1 failure (before Fastify writes headers on the first chunk) to return200 OKwith a 0-byteapplication/x-msgpackbody instead of500, and causes mid-stream failures to emit a clean HTTP chunked terminator so external MessagePack stream decoders see200 OKand clean EOF unless they check the custom{ done: true, rowCount }frame. Rethrowing afterthis.loggingService.error(...)lets Fastify return500pre-headers andres.destroy()post-headers while keeping the{ done: true, rowCount }check on the client. - Guard
reader.cancel()and mid-streamreader.read()rejections inreadExportStream(apps/web/src/utils/export.ts:55, 110-115): Callingreader.cancel()on an already-erroredReadableStreamrejects with the stream's stored error per WHATWG Streams. Whenreader.read()rejects mid-download (e.g. network drop or server socket abort),streamDonestaysfalse, soawait reader.cancel()infinallyrejects beforereader.releaseLock()runs (leaving the stream locked and masking any earlier error fromtry), and the rawfetchTypeErrorescapes instead ofIncompleteExportStreamError(showing generic"Export failed"instead of the interrupted-download message). Please wrap mid-streamreader.read()errors inIncompleteExportStreamError, swallow rejections fromreader.cancel()beforereader.releaseLock(), and add a unit test usingcontroller.error(...). - Use a dedicated error class instead of
RangeErrorfor Excel's row cap (apps/web/src/routes/_app/datahub/subjects/index.tsx:252-259,apps/web/src/utils/export.ts:177-179,apps/web/src/utils/excel.ts:9-11):getExportErrorMessagetreats everyRangeErroras exceeding Excel's1,048,575-row worksheet limit, so anyRangeErrorfrommsgpackrbounds checks,Uint8Arrayallocation, or string length limits during a CSV or JSON export tells the user they hit Excel's row limit and should export as CSV or JSON instead. Please throw and match a dedicated error class (alongsideIncompleteExportStreamError). - Validate unpacked export frame envelopes instead of casting with
as(apps/web/src/utils/export.ts:76-96):unpackr.unpackMultiple(buffer) as InstrumentRecordsExportFrame[]casts untrusted boundary data without checking frame structure (apps/web/AGENTS.mdboundary-parsing rule and rootAGENTS.mdas-assertion rule; e.g.{ done: true }without a numericrowCountsetsterminalRowCount = undefinedand bypassesterminalRowCount === null). Please validate the frame envelope ({ done: false, rows: Array }vs{ done: true, rowCount: number }) without anascast and throwIncompleteExportStreamErroron malformed frames. - Update stale
queryRecordsRawdoc reference (.agents/docs/architecture/auth-and-permissions.md:74-75):queryRecordsRawwas deleted ininstrument-records.service.ts; please update lines 74–75 to referencesummarizeRecordsinstead.
Human review needed (@joshunrau)
- Auth & group scoping (
apps/api/src/instrument-records/instrument-records.service.ts:218-231, 597-693, 704-729): Confirm upfrontaccessibleQuery(ability, 'read', 'InstrumentRecord')ID selection followed by unguarded_id: { $in: pageIds }inqueryExportPage, andresolveSeriesNamesnarrowing series titles tocallerGroupIdsunlessability.can('manage', 'all')(matchingfind()). - HTTP API compatibility & column order (
apps/api/src/instrument-records/instrument-records.controller.ts:71-84,apps/api/src/instrument-records/export-records.ts:79-93):GET /v1/instrument-records/export(listed in/spec.json) becomesPOSTwith framed MessagePack, and{ ...baseRow, measure, value }shiftsmeasurefrom CSV/Excel column 4 to column 14 — confirm whether/exportis treated as web-internal within2.xand whether the previousmeasurecolumn order should be preserved. - Export scale limits (
packages/schemas/src/instrument-records/instrument-records.ts:46-52,apps/web/src/routes/_app/datahub/subjects/index.tsx:296-299): Confirm the100,000-record synchronous cap (422) and whethersubjectIdsshould be omitted when the Data Hub subjects listing has no active filter (so >15,600 subjects in a group do not hit Fastify's 1 MiB JSON body limit). - Build config &
AGENTS.mdedits (apps/api/libnest.config.ts:18-32,knip.ts:10,apps/api/AGENTS.md:283,packages/subject-utils/AGENTS.md:20-21): Confirm removing theexport-worker.jscopy/entry config and the correspondingAGENTS.mdlines.
Reviewed at commit 3a9a21d.
| return records | ||
| .filter((record) => appAbility.can('read', forcedAppSubject('InstrumentRecord', { groupId: record.groupId }))) | ||
| .map((record) => ({ ...record })); | ||
| return (await this.instrumentRecordModel.aggregateRaw({ pipeline })) as unknown as RawExportRecord[]; |
There was a problem hiding this comment.
Both $unwind stages above use preserveNullAndEmptyArrays: true, yet $project reads subject.id from '$subject._id' instead of '$subjectId', reads session.id from '$session._id' instead of '$sessionId', and leaves subject.sex, session.date, and session.type without $ifNull. When $subject was deleted, record.subject.id is undefined behind this as unknown as RawExportRecord[] cast and removeSubjectIdScope(record.subject.id) throws TypeError; when subject.sex is unset (e.g. custom-ID subjects), subjectSex is undefined instead of null, causing JSON.stringify in buildJsonExportBlob to omit "subjectSex". Project subject.id/session.id from the record's foreign keys, normalize nullable joined fields with $ifNull to match RawExportRecord, and add unit tests for missing $subject/$session and unset subject.sex.
| error, | ||
| message: 'Failed to stream instrument records export page' | ||
| }); | ||
| } |
There was a problem hiding this comment.
Rethrow error after logging here: Fastify delays writeHead until the first chunk is yielded, so swallowing a Page-1 error turns a 500 into 200 OK with a 0-byte body, and swallowing a Page-2+ error writes a clean HTTP chunked terminator instead of calling res.destroy() for external MessagePack stream clients.
| } | ||
| } finally { | ||
| if (!streamDone) { | ||
| await reader.cancel(); |
There was a problem hiding this comment.
Calling reader.cancel() on an already-errored ReadableStream rejects with the stream's stored error, skipping reader.releaseLock() and masking any error thrown in try. Also, a mid-stream reader.read() rejection at line 55 currently escapes as a raw fetch TypeError instead of IncompleteExportStreamError. Wrap mid-stream reader.read() rejections in IncompleteExportStreamError, ignore rejections from reader.cancel() before reader.releaseLock(), and add a test with controller.error(...).
| fr: `Échec de l'exportation : plus de ${maxRecords} enregistrements correspondent. Affinez les filtres et réessayez.` | ||
| }); | ||
| } | ||
| if (err instanceof RangeError) { |
There was a problem hiding this comment.
Matching every RangeError misclassifies msgpackr bounds errors, Uint8Array allocation failures, or string-length errors during CSV/JSON exports as hitting Excel's 1,048,575-row limit. Throw and match a dedicated error class in excel.ts / export.ts instead.
|
|
||
| let frames: InstrumentRecordsExportFrame[]; | ||
| try { | ||
| frames = unpackr.unpackMultiple(buffer) as InstrumentRecordsExportFrame[]; |
There was a problem hiding this comment.
Avoid casting untrusted HTTP stream data with as InstrumentRecordsExportFrame[] (apps/web/AGENTS.md boundary-parsing rule and root AGENTS.md as-assertion rule; e.g. { done: true } without a numeric rowCount sets terminalRowCount = undefined and bypasses terminalRowCount === null at line 102). Validate the frame envelope ({ done: false, rows: Array } vs { done: true, rowCount: number }) and throw IncompleteExportStreamError on malformed frames.
| }; | ||
| }; | ||
|
|
||
| export function expandExportRecords( |
There was a problem hiding this comment.
why does this exist as a standalone function in a new file rather than as a service as is the typical pattern in NestJS?
3a9a21d to
0ab3099
Compare
|
Thanks @joshunrau and @gdevenyi for the thorough reviews! Updated the PR and commit to address every item from both reviews: From @joshunrau's review
From @gdevenyi's review
Additional fix from adversarial review
|
joshunrau
left a comment
There was a problem hiding this comment.
Thanks for working through both reviews. This branch now conflicts with main, so I can't review the new commit yet. Please rebase onto the current main (or merge it in) and resolve the conflicts. Once CI is green on the result, I'll review it again.
Reviewed at commit 0ab3099.
BREAKING CHANGE: GET /v1/instrument-records/export is replaced by POST /v1/instrument-records/export, streaming uint32BE length-prefixed MessagePack frames and capping synchronous exports at 250,000 records.
0ab3099 to
6063ec9
Compare
|
Rebased onto current
|
Exporting instrument records streams page-by-page with bounded API memory and per-frame browser formatting instead of materializing the full record array in RAM, and scopes exports to filtered subjects on the server. Closes #1407.
Changes
POST /v1/instrument-records/exportreplacesGET /v1/instrument-records/export, accepting optionalgroupIdandsubjectIdsfilters in the request body and streaminguint32BElength-prefixed MessagePack frames (up to1,000rows per frame,1,000records per DB page) terminated by{ done: true, rowCount }.250,000records reject upfront with422 Unprocessable Entitybefore streaming starts; a stored record referencing aSERIESinstrument throws500 Internal Server Error.Sessionmetadata (sessionDate,sessionType,username) andSubjectdemographics (subjectAge,subjectSex) when the caller holdsread InstrumentRecordwithoutread Sessionorread Subjectfor that row's group, preserving the record's ownsessionIdandsubjectId.Blobparts without retaining decoded row objects across frames, and abort without triggering a download if the stream ends or errors before{ done: true }..xlsx1,048,575data-row limit withExcelRowLimitExceededErrorand an explicit error notification instead of failing inside workbook serialization.apps/api/AGENTS.md,packages/subject-utils/AGENTS.md,.agents/docs/architecture/auth-and-permissions.md, and.agents/docs/architecture/runtime-and-vendor.mdis updated to reflect the removal ofexport-worker.jsandsummarizeRecordsreplacingqueryRecordsRaw.Decisions
/v1/instrument-records/exportfromGETtoPOST(200 OK) rather than keepingGETalongsidePOSTor passingsubjectIdsin query parameters, avoiding URL length limits on large filtered cohorts; marked as a breaking API change (perf!:) perdocs/en/5-reference/5.10-versioning.md.uint32BEbyte length and capped frames at1,000rows rather than scanning raw stream chunks withUnpackr.unpackMultiple, guaranteeingmsgpackr's record-extension key compression.250,000records (422) rather than streaming unbounded collections over one HTTP request, covering#1407's204,800-record benchmark while bounding request duration and upfront ID-list memory.1,000-record page inInstrumentRecordsExportServiceon the API main thread and removed thenode:worker_threadsexport worker (export-worker.js) rather than round-tripping each page through worker threads, avoiding structured-clone copies for lightweight row projection..xlsxgeneration in-memory with an explicit1,048,575-row guard rather than introducing a new OOXML streaming dependency.Risks
GET /v1/instrument-records/exportmust migrate toPOST /v1/instrument-records/exportand read[uint32BE byteLength][MessagePack frame]frames until{ done: true, rowCount }, triggering a major version bump underdocs/en/5-reference/5.10-versioning.mditem 4; first-party clients are updated in lockstep andodc-clidoes not call this endpoint.250,000accessible records now return422until narrowed by group or subject filters.Blobparts until download completes.Filed: #1937
Notes
Server export latency, TTFB, heap, and RSS measured in isolated Node v24.22.3 processes against a
mongodb-memory-serverwiredTiger replica set (1,000subjects,2,000sessions):204,800records ×3measures (614,400rows, unscoped#1407)main)9.24 s9,238 ms81.8 MiB17/89 MiB727 MiB(+710 MiB)1,565 MiB(+1,476 MiB)204,800records ×3measures (614,400rows, unscoped#1407)9.11 s334 ms81.8 MiB17/90 MiB341 MiB(+324 MiB)519 MiB(+429 MiB)200,000records ×30measures (6,000,000rows, unscoped)main)17.32 s17,320 ms810.0 MiB17/90 MiB3,648 MiB(+3,631 MiB)5,554 MiB(+5,464 MiB)200,000records ×30measures (6,000,000rows, unscoped)12.27 s366 ms810.0 MiB17/90 MiB320 MiB(+302 MiB)521 MiB(+431 MiB)25,000records ×30measures (750,000rows, group-scoped out of200k)main)2.13 s2,126 ms101.2 MiB17/89 MiB482 MiB(+465 MiB)1,143 MiB(+1,053 MiB)25,000records ×30measures (750,000rows, group-scoped out of200k)1.60 s122 ms101.3 MiB17/90 MiB143 MiB(+126 MiB)327 MiB(+237 MiB)Client
readExportStreamdecode time across100,000records (16 KiB/64 KiB/512 KiBnetwork chunks, Node v24.22.3):1,000-row cap)3300,000144.1 KiB6 s/1.8 s/0.5 s0.22 s/0.18 s/0.18 s0.20 s303,000,000146.1 KiB685 s/175 s/29 s1.22 s/1.09 s/1.05 s1.58 s505,000,000146.2 KiB1,900 s/470 s/64 s1.81 s/1.79 s/1.76 s2.41 sAdversarial review
Reviewed at commit 26bd88f10acf764357cc201982f0f0bd968e9b37. pnpm check: green.
Follow-up 6063ec9: addresses findings 1, 2; no new code.
Findings
exportRecordsthrowsUnprocessableEntityException(HTTP 422) for a stored record that references aSERIESinstrument, which suppresses server error logging and makes the web client report that the export exceeded the 250,000-record limit. — ThrowInternalServerErrorExceptioninstead ofUnprocessableEntityExceptionatapps/api/src/instrument-records/instrument-records-export.service.ts:99, and updateapps/api/src/instrument-records/__tests__/instrument-records-export.service.test.ts:564-576to expectInternalServerErrorException.EXPORT_SUITE_BUNDLEduplicates the sharedscoreFormBundlehelper and writes an invalid bundle withoutvalidationSchemadirectly into the shared integration database. — RemoveEXPORT_SUITE_BUNDLEinapps/api/test/suites/07-export-records.suite.tsand create the instrument withthis.app.get(InstrumentsService).create({ bundle: scoreFormBundle('EXPORT_SUITE_INSTRUMENT', { measured: true }) }).Fixed
exportRecordsto throwInternalServerErrorException(500) instead ofUnprocessableEntityException(422) when a stored record references aSERIESinstrument, and updated the unit test expectation.EXPORT_SUITE_BUNDLEin07-export-records.suite.tsand created the test instrument throughInstrumentsService.createwithscoreFormBundle('EXPORT_SUITE_INSTRUMENT', { measured: true }).Attestation
I, Gemini 4 Carbon, attest that the review block above reports the adversarial review as it ran on the commit named, with every finding it returned.