Skip to content

perf!: stream instrument record exports and scope by subject - #1912

Open
gdevenyi wants to merge 1 commit into
mainfrom
fix/export-streaming
Open

gdevenyi wants to merge 1 commit into
mainfrom
fix/export-streaming

Conversation

@gdevenyi

@gdevenyi gdevenyi commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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/export replaces GET /v1/instrument-records/export, accepting optional groupId and subjectIds filters in the request body and streaming uint32BE length-prefixed MessagePack frames (up to 1,000 rows per frame, 1,000 records per DB page) terminated by { done: true, rowCount }.
  • Synchronous exports matching more than 250,000 records reject upfront with 422 Unprocessable Entity before streaming starts; a stored record referencing a SERIES instrument throws 500 Internal Server Error.
  • Exported rows mask joined Session metadata (sessionDate, sessionType, username) and Subject demographics (subjectAge, subjectSex) when the caller holds read InstrumentRecord without read Session or read Subject for that row's group, preserving the record's own sessionId and subjectId.
  • CSV and JSON exports decode each length-prefixed frame once without re-scanning buffered bytes, format each frame into Blob parts without retaining decoded row objects across frames, and abort without triggering a download if the stream ends or errors before { done: true }.
  • Excel exports reject above the .xlsx 1,048,575 data-row limit with ExcelRowLimitExceededError and an explicit error notification instead of failing inside workbook serialization.
  • Filtered exports from the Data Hub subjects table scope by the matching subject IDs on the server instead of downloading every accessible record and filtering client-side.
  • Agent documentation in apps/api/AGENTS.md, packages/subject-utils/AGENTS.md, .agents/docs/architecture/auth-and-permissions.md, and .agents/docs/architecture/runtime-and-vendor.md is updated to reflect the removal of export-worker.js and summarizeRecords replacing queryRecordsRaw.

Decisions

  • Switched /v1/instrument-records/export from GET to POST (200 OK) rather than keeping GET alongside POST or passing subjectIds in query parameters, avoiding URL length limits on large filtered cohorts; marked as a breaking API change (perf!:) per docs/en/5-reference/5.10-versioning.md.
  • Prefixed every MessagePack frame with a 4-byte uint32BE byte length and capped frames at 1,000 rows rather than scanning raw stream chunks with Unpackr.unpackMultiple, guaranteeing $O(1)$-per-byte decoding across arbitrary network chunk boundaries while keeping msgpackr's record-extension key compression.
  • Capped synchronous exports at 250,000 records (422) rather than streaming unbounded collections over one HTTP request, covering #1407's 204,800-record benchmark while bounding request duration and upfront ID-list memory.
  • Expanded measures per 1,000-record page in InstrumentRecordsExportService on the API main thread and removed the node:worker_threads export worker (export-worker.js) rather than round-tripping each page through worker threads, avoiding structured-clone copies for lightweight row projection.
  • Kept .xlsx generation in-memory with an explicit 1,048,575-row guard rather than introducing a new OOXML streaming dependency.

Risks

  • External callers of GET /v1/instrument-records/export must migrate to POST /v1/instrument-records/export and read [uint32BE byteLength][MessagePack frame] frames until { done: true, rowCount }, triggering a major version bump under docs/en/5-reference/5.10-versioning.md item 4; first-party clients are updated in lockstep and odc-cli does not call this endpoint.
  • Unfiltered exports on deployments with more than 250,000 accessible records now return 422 until narrowed by group or subject filters.
  • Browser CSV and JSON exports avoid retaining decoded JS row objects across frames, though the browser still holds the formatted UTF-8 Blob parts 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-server wiredTiger replica set (1,000 subjects, 2,000 sessions):

Scenario Pipeline Wall time TTFB Body Baseline heap / RSS Peak heap (Δ) Peak RSS (Δ)
204,800 records × 3 measures (614,400 rows, unscoped #1407) Before (main) 9.24 s 9,238 ms 81.8 MiB 17 / 89 MiB 727 MiB (+710 MiB) 1,565 MiB (+1,476 MiB)
204,800 records × 3 measures (614,400 rows, unscoped #1407) After (PR) 9.11 s 334 ms 81.8 MiB 17 / 90 MiB 341 MiB (+324 MiB) 519 MiB (+429 MiB)
200,000 records × 30 measures (6,000,000 rows, unscoped) Before (main) 17.32 s 17,320 ms 810.0 MiB 17 / 90 MiB 3,648 MiB (+3,631 MiB) 5,554 MiB (+5,464 MiB)
200,000 records × 30 measures (6,000,000 rows, unscoped) After (PR) 12.27 s 366 ms 810.0 MiB 17 / 90 MiB 320 MiB (+302 MiB) 521 MiB (+431 MiB)
25,000 records × 30 measures (750,000 rows, group-scoped out of 200k) Before (main) 2.13 s 2,126 ms 101.2 MiB 17 / 89 MiB 482 MiB (+465 MiB) 1,143 MiB (+1,053 MiB)
25,000 records × 30 measures (750,000 rows, group-scoped out of 200k) After (PR) 1.60 s 122 ms 101.3 MiB 17 / 90 MiB 143 MiB (+126 MiB) 327 MiB (+237 MiB)

Client readExportStream decode time across 100,000 records (16 KiB / 64 KiB / 512 KiB network chunks, Node v24.22.3):

Measures / record Rows Avg frame Previous rescanning loop Length-prefixed frames (1,000-row cap) Single-pass baseline
3 300,000 144.1 KiB 6 s / 1.8 s / 0.5 s 0.22 s / 0.18 s / 0.18 s 0.20 s
30 3,000,000 146.1 KiB 685 s / 175 s / 29 s 1.22 s / 1.09 s / 1.05 s 1.58 s
50 5,000,000 146.2 KiB 1,900 s / 470 s / 64 s 1.81 s / 1.79 s / 1.76 s 2.41 s

Adversarial review

Reviewed at commit 26bd88f10acf764357cc201982f0f0bd968e9b37. pnpm check: green.
Follow-up 6063ec9: addresses findings 1, 2; no new code.

Findings

  1. apps/api/src/instrument-records/instrument-records-export.service.ts:99 — exportRecords throws UnprocessableEntityException (HTTP 422) for a stored record that references a SERIES instrument, which suppresses server error logging and makes the web client report that the export exceeded the 250,000-record limit. — Throw InternalServerErrorException instead of UnprocessableEntityException at apps/api/src/instrument-records/instrument-records-export.service.ts:99, and update apps/api/src/instrument-records/__tests__/instrument-records-export.service.test.ts:564-576 to expect InternalServerErrorException.
  2. apps/api/test/suites/07-export-records.suite.ts:11 — EXPORT_SUITE_BUNDLE duplicates the shared scoreFormBundle helper and writes an invalid bundle without validationSchema directly into the shared integration database. — Remove EXPORT_SUITE_BUNDLE in apps/api/test/suites/07-export-records.suite.ts and create the instrument with this.app.get(InstrumentsService).create({ bundle: scoreFormBundle('EXPORT_SUITE_INSTRUMENT', { measured: true }) }).

Fixed

    1. Changed exportRecords to throw InternalServerErrorException (500) instead of UnprocessableEntityException (422) when a stored record references a SERIES instrument, and updated the unit test expectation.
    1. Removed EXPORT_SUITE_BUNDLE in 07-export-records.suite.ts and created the test instrument through InstrumentsService.create with scoreFormBundle('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.

@gdevenyi
gdevenyi requested a review from joshunrau as a code owner November 12, 2026 01:09
Copilot AI balanced review requested due to automatic review settings November 12, 2026 01:09

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@joshunrau

Copy link
Copy Markdown
Collaborator

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

  • The rewrite is complete and clean. The API streams page frames with working backpressure: with the same Readable.from(..., { highWaterMark: 1 }) construction, the generator never ran more than 2 pages ahead of a slow consumer. Authorization moved into the query, and the worker is gone with no leftover references.
  • The decoder is correct. 200 fuzz rounds over random chunk boundaries, with record structures shared across frames, decoded identically to the source rows.
  • The tests are behavioural, including a multi-page e2e export and a check that a filtered-out subject never leaves the server.

Action items

1. Client decode is quadratic in frame size

readExportStream (apps/web/src/utils/export.ts:64-84) concatenates the pending bytes with each new chunk and calls unpackMultiple on the whole buffer, so a frame that spans many network chunks is re-decoded from its first byte once per chunk. A frame is 1,000 records, so its size grows with measures per record. This is invisible with the demo instruments (3 measures) and severe at the 30–50 the issue calls typical.

Projected decode time for 100,000 records (the cap), by network chunk size:

Measures per record Frame size 16 KiB chunks 64 KiB chunks 512 KiB chunks Single pass
3 0.7 MiB 6 s 1.8 s 0.5 s 0.1 s
30 6.8 MiB 685 s 175 s 29 s 1.4 s
50 11.3 MiB 1,900 s 470 s 64 s 3 s

Method: frames built with Packr({ sequential: true, useRecords: true }) from 1,000 records × N measures of export-shaped rows, concatenated, cut into fixed-size chunks and fed to this PR's readExportStream in Node 24. Single pass is one unpackMultiple over the whole buffer. Figures are extrapolated linearly from 6–20 pages to 100. The chunk size a browser delivers varies, so the table gives a range rather than one number.

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-lastPosition approach comes from the triage note on the issue, which did not flag this cost, so the flaw is inherited from the plan rather than introduced here.

2. The breaking change is unmarked

docs/en/5-reference/5.10-versioning.md:17 promises that removing or changing anything in the documented HTTP API is a breaking change. This PR removes GET /v1/instrument-records/export and changes the response format, and the commit is a plain perf:. The Risks section says external scripts must switch, but does not connect that to the policy.

Either mark the commit breaking (perf!: with a BREAKING CHANGE: footer, which forces a major), or keep GET beside the new POST so the change is an addition.

3. The 100,000-record cap is a product decision

The issue left "refuse past N rows, or run an async job" open. This PR picks the cap (instrument-records.service.ts:233-237), so the issue's own 204,800-record benchmark export would now return 422. It is disclosed under Decisions and Risks, which is right; flagging it so it is accepted on purpose rather than by merge.

4. A performance PR needs measurements

There 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 AGENTS.md files are edited

apps/api/AGENTS.md and packages/subject-utils/AGENTS.md both change. The edits are minimal and accurate, but the root hard rule requires express approval, and the PR body does not mention them. Please list them under Changes so they are approved knowingly.

6. PR body corrections

  • It says it removed a "piscina export worker". The old worker used node:worker_threads directly; piscina was never in the repo.
  • "Bounded browser memory" is overstated. Row objects are no longer accumulated, but the CSV and JSON text is all held in memory until the Blob is built, and the Excel path collects every row.

Review written with Claude Code.

Reviewed at commit 3a9a21d.

@gdevenyi gdevenyi left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Handle missing joined Subject/Session documents and unset subject.sex in queryExportPage (apps/api/src/instrument-records/instrument-records.service.ts:662-692, apps/api/src/instrument-records/export-records.ts:23-35): Both $unwind stages set preserveNullAndEmptyArrays: true (since SessionsService.deleteById and non-force or cross-group SubjectsService.deleteById can leave InstrumentRecords whose Session or Subject document is gone), yet $project reads subject.id from '$subject._id' instead of '$subjectId' and session.id from '$session._id' instead of '$sessionId', and leaves subject.sex, session.date, and session.type without $ifNull. When $subject is absent, record.subject.id is undefined behind the as unknown as RawExportRecord[] cast and removeSubjectIdScope(record.subject.id) throws TypeError, aborting the export; when subject.sex is unset on a custom-ID subject, subjectSex is undefined rather than null, causing JSON.stringify in buildJsonExportBlob to omit the "subjectSex" key. Please project subject.id / session.id from the foreign keys on InstrumentRecord, normalize the nullable joined fields with $ifNull so RawExportRecord matches every row, and add unit test cases for missing $subject/$session and unset subject.sex.
  2. Rethrow page errors in generateChunks after logging (apps/api/src/instrument-records/instrument-records.service.ts:264-281): Swallowing errors in generateChunks causes a Page-1 failure (before Fastify writes headers on the first chunk) to return 200 OK with a 0-byte application/x-msgpack body instead of 500, and causes mid-stream failures to emit a clean HTTP chunked terminator so external MessagePack stream decoders see 200 OK and clean EOF unless they check the custom { done: true, rowCount } frame. Rethrowing after this.loggingService.error(...) lets Fastify return 500 pre-headers and res.destroy() post-headers while keeping the { done: true, rowCount } check on the client.
  3. Guard reader.cancel() and mid-stream reader.read() rejections in readExportStream (apps/web/src/utils/export.ts:55, 110-115): Calling reader.cancel() on an already-errored ReadableStream rejects with the stream's stored error per WHATWG Streams. When reader.read() rejects mid-download (e.g. network drop or server socket abort), streamDone stays false, so await reader.cancel() in finally rejects before reader.releaseLock() runs (leaving the stream locked and masking any earlier error from try), and the raw fetch TypeError escapes instead of IncompleteExportStreamError (showing generic "Export failed" instead of the interrupted-download message). Please wrap mid-stream reader.read() errors in IncompleteExportStreamError, swallow rejections from reader.cancel() before reader.releaseLock(), and add a unit test using controller.error(...).
  4. Use a dedicated error class instead of RangeError for 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): getExportErrorMessage treats every RangeError as exceeding Excel's 1,048,575-row worksheet limit, so any RangeError from msgpackr bounds checks, Uint8Array allocation, 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 (alongside IncompleteExportStreamError).
  5. 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.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). Please validate the frame envelope ({ done: false, rows: Array } vs { done: true, rowCount: number }) without an as cast and throw IncompleteExportStreamError on malformed frames.
  6. Update stale queryRecordsRaw doc reference (.agents/docs/architecture/auth-and-permissions.md:74-75): queryRecordsRaw was deleted in instrument-records.service.ts; please update lines 74–75 to reference summarizeRecords instead.

Human review needed (@joshunrau)

  1. Auth & group scoping (apps/api/src/instrument-records/instrument-records.service.ts:218-231, 597-693, 704-729): Confirm upfront accessibleQuery(ability, 'read', 'InstrumentRecord') ID selection followed by unguarded _id: { $in: pageIds } in queryExportPage, and resolveSeriesNames narrowing series titles to callerGroupIds unless ability.can('manage', 'all') (matching find()).
  2. 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) becomes POST with framed MessagePack, and { ...baseRow, measure, value } shifts measure from CSV/Excel column 4 to column 14 — confirm whether /export is treated as web-internal within 2.x and whether the previous measure column order should be preserved.
  3. 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 the 100,000-record synchronous cap (422) and whether subjectIds should 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).
  4. Build config & AGENTS.md edits (apps/api/libnest.config.ts:18-32, knip.ts:10, apps/api/AGENTS.md:283, packages/subject-utils/AGENTS.md:20-21): Confirm removing the export-worker.js copy/entry config and the corresponding AGENTS.md lines.

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[];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'
});
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread apps/web/src/utils/export.ts Outdated
}
} finally {
if (!streamDone) {
await reader.cancel();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread apps/web/src/utils/export.ts Outdated

let frames: InstrumentRecordsExportFrame[];
try {
frames = unpackr.unpackMultiple(buffer) as InstrumentRecordsExportFrame[];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why does this exist as a standalone function in a new file rather than as a service as is the typical pattern in NestJS?

@gdevenyi gdevenyi changed the title perf: stream instrument record exports and scope by subject perf!: stream instrument record exports and scope by subject Nov 12, 2026
@gdevenyi
gdevenyi force-pushed the fix/export-streaming branch from 3a9a21d to 0ab3099 Compare November 12, 2026 19:30
@gdevenyi

Copy link
Copy Markdown
Contributor Author

Thanks @joshunrau and @gdevenyi for the thorough reviews! Updated the PR and commit to address every item from both reviews:

From @joshunrau's review

  1. $O(1)$-per-byte length-prefixed frame decoding & row-bounded frames

    • InstrumentRecordsExportService now slices expanded rows into frames of at most INSTRUMENT_RECORDS_EXPORT_MAX_FRAME_ROWS = 1_000 rows and prefixes every MessagePack frame with a 4-byte uint32BE payload byte length ([u32be payload.byteLength][payload]).
    • readExportStream accumulates incoming Uint8Array chunks without copying until 4 + expectedFrameLength bytes arrive, slices out that exact payload, and calls unpackr.unpackMultiple(payload) strictly once per frame (needed rather than unpack() because Packr({ sequential: true, useRecords: true }) prepends structure-definition extension values into the same frame payload). Added a unit test spying on Unpackr.prototype.unpackMultiple across 2-byte chunks to guard against re-decode regressions.
  2. NestJS service pattern (export-records.ts inline comment)

    • Removed the standalone export-records.ts helper file and extracted the export pipeline into @Injectable() InstrumentRecordsExportService (apps/api/src/instrument-records/instrument-records-export.service.ts), registered in InstrumentRecordsModule alongside InstrumentMeasuresService and FilesService and injected into InstrumentRecordsController.
  3. Breaking API change marked perf!: (BREAKING CHANGE:)

    • Kept GET /v1/instrument-records/export removed in favor of POST /v1/instrument-records/export, amended the commit and PR title to perf!: stream instrument record exports and scope by subject with a BREAKING CHANGE: footer per docs/en/5-reference/5.10-versioning.md item 4, and connected ## Risks directly to the versioning policy.
  4. Synchronous export cap raised to 250,000 records

    • Raised INSTRUMENT_RECORDS_EXPORT_MAX_RECORDS from 100_000 to 250_000 so #1407's 204,800-record benchmark scenario succeeds instead of returning 422.
  5. Before/after latency & memory measurements (added to ## Notes)

    • Server (mongodb-memory-server wiredTiger replica set, isolated Node v24.22.3 processes, 1,000 subjects, 2,000 sessions):

      Scenario Pipeline Wall time TTFB Body Baseline heap / RSS Peak heap (Δ) Peak RSS (Δ)
      204,800 records × 3 measures (614,400 rows, unscoped #1407) Before (main) 9.24 s 9,238 ms 81.8 MiB 17 / 89 MiB 727 MiB (+710 MiB) 1,565 MiB (+1,476 MiB)
      204,800 records × 3 measures (614,400 rows, unscoped #1407) After (PR) 9.11 s 334 ms 81.8 MiB 17 / 90 MiB 341 MiB (+324 MiB) 519 MiB (+429 MiB)
      200,000 records × 30 measures (6,000,000 rows, unscoped) Before (main) 17.32 s 17,320 ms 810.0 MiB 17 / 90 MiB 3,648 MiB (+3,631 MiB) 5,554 MiB (+5,464 MiB)
      200,000 records × 30 measures (6,000,000 rows, unscoped) After (PR) 12.27 s 366 ms 810.0 MiB 17 / 90 MiB 320 MiB (+302 MiB) 521 MiB (+431 MiB)
      25,000 records × 30 measures (750,000 rows, group-scoped out of 200k) Before (main) 2.13 s 2,126 ms 101.2 MiB 17 / 89 MiB 482 MiB (+465 MiB) 1,143 MiB (+1,053 MiB)
      25,000 records × 30 measures (750,000 rows, group-scoped out of 200k) After (PR) 1.60 s 122 ms 101.3 MiB 17 / 90 MiB 143 MiB (+126 MiB) 327 MiB (+237 MiB)
    • Client frame decode (100,000 records, Node v24.22.3, 16 KiB / 64 KiB / 512 KiB stream chunks):

      Measures / record Rows Avg frame Previous rescanning loop Length-prefixed frames (1,000-row cap) Single-pass baseline
      3 300,000 144.1 KiB 6 s / 1.8 s / 0.5 s 0.22 s / 0.18 s / 0.18 s 0.20 s
      30 3,000,000 146.1 KiB 685 s / 175 s / 29 s 1.22 s / 1.09 s / 1.05 s 1.58 s
      50 5,000,000 146.2 KiB 1,900 s / 470 s / 64 s 1.81 s / 1.79 s / 1.76 s 2.41 s
  6. AGENTS.md updates, browser memory phrasing, and why piscina was claimed

    • Explicitly listed the apps/api/AGENTS.md and packages/subject-utils/AGENTS.md updates under ## Changes, and corrected the browser memory description (CSV/JSON format per frame into Blob parts whose UTF-8 text stays in memory until download, while Excel collects up to 1,048,575 row objects).
    • Why piscina appeared in the original PR body: that was a post-compaction hallucination while drafting the PR body. Earlier in the session I read and deleted apps/api/src/instrument-records/export-worker.js (which used new Worker(...) from node:worker_threads) and thread-types.ts. Context compaction then summarized that step as "deleting export-worker.js and thread-types.ts" without retaining the implementation detail. When drafting ## Decisions afterward, instead of re-reading git diff upstream/main to verify how the deleted worker was spawned, I wrote from memory and conflated #1407's "Reconsider the worker pool" bullet with piscina (which this repo has never depended on). Updated ## Decisions to say node:worker_threads.

From @gdevenyi's review

  1. Missing joined Subject/Session documents, unset subject.sex, and CSV/Excel column order

    • queryExportPage now projects subject.id from '$subjectId' and session.id from { $toString: '$sessionId' }, and normalizes computedMeasures, session.date, session.type, session.user.username, subject.age, and subject.sex with $ifNull (sessionDate and sessionType in InstrumentRecordsExport updated to nullable). Added both unit tests (instrument-records-export.service.test.ts) and an integration test (apps/api/test/suites/07-export-records.suite.ts) against real MongoDB covering deleted Subject/Session documents and custom-ID subjects with unset sex.
    • Also restored the exact property insertion order on exported rows (measure at column 4, matching main).
  2. Rethrow page errors in generateChunks after logging

    • generateChunks now rethrows after this.loggingService.error(...) so pre-header failures return 500 and mid-stream failures destroy the response socket (res.destroy()) rather than emitting a clean HTTP chunked EOF.
  3. Guard mid-stream reader.read() and reader.cancel() rejections in readExportStream

    • Wrapped reader.read() rejections in IncompleteExportStreamError and guarded await reader.cancel() in finally with try / catch before reader.releaseLock(). Added a controller.error(...) unit test verifying both the wrapped error and stream unlock.
  4. Dedicated ExcelRowLimitExceededError instead of RangeError

    • Added ExcelRowLimitExceededError in apps/web/src/utils/excel.ts, threw it from downloadSubjectTableExcel and collectExcelExportRows, and matched err instanceof ExcelRowLimitExceededError in Data Hub so generic RangeErrors during CSV/JSON exports no longer misreport hitting Excel's row limit.
  5. Validate unpacked frame envelopes without as casts

    • Replaced as InstrumentRecordsExportFrame[] in decodeFramePayload with a runtime frame-envelope type guard (isExportFrame) that rejects malformed frames with IncompleteExportStreamError, plus unit tests across invalid envelope shapes.
  6. Stale queryRecordsRaw doc reference

    • Updated .agents/docs/architecture/auth-and-permissions.md line 74 to reference summarizeRecords.
  7. Notes on the Human review needed items

    • Raised INSTRUMENT_RECORDS_EXPORT_MAX_RECORDS to 250,000 (item 3) and marked the route/format change perf!: (item 2). Kept subjectIds: [...listedSubjects] in Data Hub even when no column filter is active so unfiltered Data Hub exports preserve main's listedSubjects.has(entry.subjectId) semantics (excluding orphaned records for deleted subjects or subjects removed from the group that are not shown in the Data Hub table).

Additional fix from adversarial review

  • Joined Session and Subject permission masking: queryExportPage and expandRecords now check ability.can('read', forcedAppSubject('Session', ...)) and ability.can('read', forcedAppSubject('Subject', ...)) per exported record so callers holding read InstrumentRecord without read Session or read Subject for that row's group have sessionDate/sessionType/username and subjectAge/subjectSex masked while preserving sessionId and subjectId.

@github-actions github-actions Bot added Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested Status: Needs Rebase Automated: conflicts with main; the author rebases and removed Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested Status: Needs Rebase Automated: conflicts with main; the author rebases labels Nov 13, 2026
@github-actions github-actions Bot added Status: Needs Rebase Automated: conflicts with main; the author rebases Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested and removed Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested Status: Needs Rebase Automated: conflicts with main; the author rebases labels Nov 18, 2026

@joshunrau joshunrau left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@gdevenyi
gdevenyi force-pushed the fix/export-streaming branch from 0ab3099 to 6063ec9 Compare November 23, 2026 02:23
@github-actions github-actions Bot added Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested and removed Status: Needs Rebase Automated: conflicts with main; the author rebases labels Nov 23, 2026
@gdevenyi

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (e03df0ef5) at 6063ec9a2:

  • Resolved conflicts in apps/api/src/instrument-records/instrument-records.service.ts, testing/src/specs/authorization.spec.ts, and testing/src/specs/datahub.spec.ts, and updated the moved export group-scoping test in apps/api/test/suites/08-authorization.suite.ts for POST /v1/instrument-records/export.
  • Switched exportRecords to throw InternalServerErrorException (500) rather than 422 when a stored record references a SERIES instrument, and replaced the inline bundle in 07-export-records.suite.ts with scoreFormBundle('EXPORT_SUITE_INSTRUMENT', { measured: true }).

This branch has not been deployed

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

Labels

Status: Waiting on Review Automated: unreviewed, pushed since the last review, or review re-requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance: /instrument-records/export buffers the whole dataset in memory (12.8s, +2.9 GiB RSS, 122 MiB body at 200k records)

3 participants