Skip to content

Phase 2: metadata.json sibling endpoint for indexing - #504

Merged
neuromechanist merged 2 commits into
feature/issue-449-epic-data-httpsfrom
feature/issue-496-phase2-metadata
May 15, 2026
Merged

neuromechanist merged 2 commits into
feature/issue-449-epic-data-httpsfrom
feature/issue-496-phase2-metadata

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Phase 2 of epic #449. Adds GET https://data.nemar.org/<datasetId>/metadata.json, a public anonymous endpoint that returns a neuroschema v0.3.0 dataset document combining:

  • The D1 catalog row (name, modalities, subject/task aggregates, sizes).
  • The parsed nemar_metadata.json enrichment payload (authors flattened from Record<name, AuthorEnrichmentV2> to Person[], MeSH keywords, related identifiers, contributors, dates, funding, license, pipeline stage).
  • The full dataset_versions list under extensions.nemar.versions with a cross-link manifest_url to the per-version Phase 1 manifest.json.
  • A derived BIDS subjects -> sessions -> modalities -> tasks -> runs tree from the latest version's S3 manifest under extensions.nemar.bids_index.

This is the contract @bruAristimunha asked for in #449: external indexers / viewers (eegdash-viewer etc.) can resolve dataset -> subjects/tasks/runs -> files in one fetch. The wire format intentionally uses neuroschema (~/Documents/git/nemar/neuroschema/schema/core/dataset.schema.json, example dataset-nm000108.json) so it slots into the existing FAIR ecosystem and the schema is reusable by other consumers.

Same public-only gate as Phase 1 -- private/unknown collapse to 404 with no existence leak. Partial inputs never 500: missing enrichment, no versions yet, or a failed manifest fetch each degrade to null/empty fields rather than aborting.

Closes #496.

Test plan

  • 48 unit tests pass (30 from Phase 1 + 18 new for buildBidsIndex, buildPersonList, deriveSessions, formatBytes, buildDatasetMetadata).
  • tsc --noEmit clean.
  • Adjacent suites (datacite.test.ts, dataset-metadata-columns.test.ts) still pass (148 tests, 0 fail).
  • E2E (test/data-route.test.ts) against a deployed dev backend after merge -- 2 new positive/404 tests added; skip gracefully when nm099999 is unpublished.

Adds GET /<datasetId>/metadata.json on the data.nemar.org sub-app, returning
a neuroschema v0.3.0 dataset document that combines:

- The D1 catalog row (name, modalities, subject/task aggregates, sizes).
- The parsed nemar_metadata.json enrichment payload (authors flattened from
  Record<name, AuthorEnrichmentV2> to Person[], MeSH keywords, related
  identifiers, contributors, dates, funding, license).
- The full dataset_versions list under extensions.nemar.versions with
  cross-link manifest_url to the per-version Phase 1 manifest.json.
- A derived BIDS subjects/sessions/modalities/tasks/runs tree from the
  latest version's S3 manifest under extensions.nemar.bids_index, so
  external viewers (eegdash-viewer, etc.) can resolve dataset shape in one
  fetch.

Same public-only gate and 404-with-no-existence-leak as Phase 1. Partial
inputs never 500: missing enrichment, missing versions, or a failed
manifest fetch each degrade to null/empty fields rather than aborting.

backend/src/services/data-router.ts: adds pure builders
(buildDatasetMetadata, buildBidsIndex, buildPersonList, deriveSessions,
formatBytes) plus exported types (NeuroschemaDataset, BidsIndex,
NemarExtensionBlock, etc.). All synchronous and unit-testable.

backend/src/routes/data.ts: metadataJsonHandler wires D1 + manifest I/O,
registered before /:datasetId/:version so Hono cannot capture
"metadata.json" as a version param.

test/data-route.unit.test.ts: 18 new unit tests for the builders covering
empty manifests, multi-session/multi-modality/multi-run accumulation,
non-BIDS path skipping, sidecar inclusion, v1 and v2 author shapes,
formatBytes edge cases, and the full assembler under no-enrichment /
no-versions / no-manifest combinations.

test/data-route.test.ts: extends the E2E suite (skips when nm099999 is
not currently published) with a positive shape assertion and an unknown-
dataset 404 check.

docs/reference/data-api.md: documents the contract with the canonical
example payload.

Closes #496.
@github-actions

github-actions Bot commented May 15, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR504

Version: 0.8.15-PR504.2407f3c
Commit: 2407f3c


🤖 Updated on each push.

- buildBidsIndex: register subjects whose only files lack a `_task-` token
  (anat, dwi, fmap are valid BIDS and the subject must still appear in
  the index). Modalities entry exists with empty tasks map; subject-level
  sidecars register the subject without a modality entry. Replaces the
  previous "missing task token rejects the row" semantics, which silently
  undercounted neuroimaging subjects.

- formatBytes: switch from a two-tier (>=100 ? 0 : 2) to a three-tier
  precision rule (>=100 -> 0 decimals, >=10 -> 1 decimal, <10 -> 2
  decimals). The previous rule produced "10.10 GB" and "99.50 GB" which
  disagreed with the documented "450 MB" / "150 GB" examples. New rule
  matches the docstring; the docstring is also expanded to spell out the
  tiers explicitly so a future maintainer cannot drift it.

- metadataJsonHandler: log the race-case (row disappears between the
  visibility gate and the second SELECT) at warn level so operators can
  correlate it with deletion events or D1 replica lag. The previous code
  returned 404 silently for this anomaly.

- metadataJsonHandler: corrupt enrichment_json now logs at console.error
  rather than console.warn. Persistent data corruption is not a transient
  warning; routing it to error makes it visible to any future
  exception-aggregation pipeline (Sentry is tracked in #478).

- New unit tests: task-less subject registration (anat + dwi),
  subject-level sidecar (sub-01/sub-01_scans.tsv) registers the subject,
  mixed session/flat layouts under one subject, mid-tier formatBytes
  precision, v1 enrichment has no license -> rights empty,
  D1-description-null falls back to v2 enrichment description.

- Drop stale "phase 1"/"phase 2" qualifiers from the file/section
  headers. The data.nemar.org route is now multi-phase; the per-phase
  label dates the comment without adding information.

52 unit tests pass (up from 48 in the PR's first commit).
@neuromechanist

Copy link
Copy Markdown
Contributor Author

/review-pr summary

Ran the five applicable agents in parallel against this PR. No critical findings. Acted on the high-confidence important findings; deferred the broader ones with rationale.

Acted on (commit 2407f3c)

  • buildBidsIndex undercount (code-reviewer, confidence 87): subjects whose only files lack a _task- token (anat, dwi, fmap valid BIDS) were silently dropped from the index. Refactored to register the subject as soon as a valid sub-X path appears; modality / task / run entries layer on top conditionally. New tests pin task-less subject registration, subject-level sidecars, and mixed session/flat layouts.
  • formatBytes precision inconsistency (code-reviewer, confidence 80): two-tier rule (>=100 ? 0 : 2) produced "10.10 GB" / "99.50 GB", disagreeing with the docstring's "450 MB" example. Switched to three-tier (>=100: 0, >=10: 1, <10: 2). Docstring rewritten to spell the tiers out so it can't drift.
  • Race-case silent return (silent-failure-hunter): the visibility-gate / row-fetch race in metadataJsonHandler returned 404 with no log. Added a structured console.warn so operators can correlate with deletion events / D1 replica lag.
  • console.warn -> console.error for corrupt enrichment_json (silent-failure-hunter): persistent data corruption shouldn't sit at warn level. (No Sentry yet -- tracked under Add Sentry observability for rate-limit cache failures and missing RESEND_API_KEY #478.)
  • Stale phase qualifier in comments (comment-analyzer): dropped phase 1 / phase 2 qualifiers from the file/section banners now that the route is multi-phase. Kept the epic #449 reference -- it's the live spec, not a per-commit annotation.
  • Test gaps (test-analyzer): added v1-enrichment-has-no-license, D1-description-null-falls-back-to-v2-enrichment, mixed session-layout, subject-level sidecar.

Deferred with rationale

  • Tightening RelatedIdentifierEntry.relation_type, ContributorEntry.contributor_type, StructuredDate.date_type from string to literal unions (type-design-analyzer): valid concern, but these types live in shared/datacite-constants.ts and are consumed by ~10 call sites outside this PR. Out of Phase 2 scope; will file a follow-up issue.
  • Expanding DatasetDemographics / DataSummary / Provenance / ExternalLinks to mirror every neuroschema field (type-design-analyzer): the TS interfaces correctly model what the builder populates, not what the schema permits. Adding optional fields the builder never sets would be dead code. The output JSON already passes additionalProperties: false because we don't emit extra fields.
  • Branded DatasetId / tuple-rest recording_modality: [string, ...string[]] (type-design-analyzer): nominal change for marginal safety; not Phase 2 scope.
  • Hono route-ordering integration test (code-reviewer): the E2E suite at test/data-route.test.ts already exercises GET /<id>/metadata.json against a deployed backend. Adding a separate unit-level routing test would duplicate it.
  • E2E test for an existing-but-private dataset returning 404 on metadata.json (code-reviewer): code path is shared with loadPublishedDataset, which the Phase 1 suite already verifies. Adding requires a known-private dataset ID in the test env.

Final state

  • 52 unit tests pass (48 from the first commit + 4 from the fixes).
  • tsc --noEmit clean.
  • E2E suite unchanged and still skip-gracefully against unpublished nm099999.

@neuromechanist
neuromechanist merged commit bd8e59f into feature/issue-449-epic-data-https May 15, 2026
1 check passed
@neuromechanist
neuromechanist deleted the feature/issue-496-phase2-metadata branch May 18, 2026 11:11

This branch was previously deployed

1 inactive deployment
npm — 2407f3c7 Deployed May 15, 2026 by neuromechanist via publish #910
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant