Skip to content

fix(catalog): sync nemar_catalog from enrichment + backfill historical rows - #541

Merged
neuromechanist merged 2 commits into
devfrom
fix/datasets-authors-source-of-truth
May 18, 2026
Merged

neuromechanist merged 2 commits into
devfrom
fix/datasets-authors-source-of-truth

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Problem

GET /datasets reads modalities, participants, tasks, authors, file_size, etc. from nemar_catalog. That table is kept fresh by catalog-sync.ts (the cron that pulls from the legacy nemar.org pipeline) and by initial inserts at dataset creation. Nothing mirrors the output of the new in-process enrichment pipeline (#527) back into the catalog.

Symptom on production today: nm000166 has a healthy datasets row (all typed columns from migration 0020 populated) plus a rich enrichment_json blob with 8 authors, 13 tasks, 95 participants, 23 GB. But the discover card showed by <uploader> with zero everything because the list endpoint was reading from the un-synced nemar_catalog row.

Architecture

GitHub dataset repos = source of truth. D1 (datasets + nemar_catalog) = read cache. The list endpoint serves the cache. The fix is keeping the cache coherent on every write path.

Changes

1. New helpers (dataset-metadata-columns.ts)

  • authorsFromEnrichment() — extracts a CSV author string from either the object-keyed shape the LLM enrichment emits today ({"Gan Huang": {orcid: ...}, ...}) or the legacy array-of-objects shape some older rows still carry.
  • formatFileSize() — byte count → human-readable string ("23.2 GB") matching catalog-sync's file_size_formatted format.
  • syncNemarCatalogFromEnrichment() — UPDATE nemar_catalog with COALESCE-preserve semantics so null inputs don't clobber existing values. Logs and returns changes=0 if the row doesn't exist (catalog-sync.ts is responsible for initial inserts).

2. Caller wire-up

  • enrich-dataset.ts: after writeDatasetMetadataColumns(), calls syncNemarCatalogFromEnrichment() with BIDS-derived cols + author/license extracted from finalMetadata.
  • dataset-reindex.ts: same call, but only with the BIDS-derived cols; authors/license stay null so the existing nemar_catalog values are preserved (those come from enrichment, not reindex).

3. Backfill migration 0023

One-shot: for every nemar_catalog row with empty fields, project from the corresponding datasets row + enrichment_json. Handles both author shapes (object-keyed and legacy array). Closes the historical gap for rows enriched before this sync landed.

Tests

test/catalog-sync-from-enrichment.unit.test.ts — 10 unit tests:

  • authorsFromEnrichment across all observed shapes (object, array-of-strings, array-of-objects with name, with affiliation-only entries skipped)
  • formatFileSize boundaries (zero, KB/MB/GB/TB scaling, decimal rules above 100)

The integration assertion (post-enrichment, nemar_catalog has the expected values) will run on dev's api-test and verified live after merge.

Acceptance

  • nm000166 backfilled by migration 0023 → list endpoint returns modalities="eeg", participants=95, tasks="aep,motorFoot,...", authors="Gan Huang, Zhenxing Hu, ...", file_size=23154528416
  • Discover card for nm000166 shows the right authors (after the website's list response refreshes)
  • Future re-enrichment of any dataset re-syncs nemar_catalog automatically (no operator action)

Refs

…l rows

The list endpoint reads modalities, participants, tasks, authors,
file_size, etc. from nemar_catalog. nemar_catalog rows were only kept
fresh by catalog-sync.ts (the cron that pulls from the legacy
nemar.org pipeline) and by initial inserts; nothing mirrored the
output of the new in-process enrichment pipeline (PR #527) back into
the catalog. Result: an enriched dataset like nm000166 had a fully
populated datasets row + enrichment_json blob, while its nemar_catalog
row stayed empty -- the discover card showed 'by <uploader>' and zero
modalities/tasks/participants/size.

Three coordinated changes:

1. backend/src/services/dataset-metadata-columns.ts -- new helpers:
   - authorsFromEnrichment(): pull a CSV author string from the
     object-keyed shape the LLM enrichment emits today, or the
     legacy array-of-objects form some older rows still use.
   - formatFileSize(): byte count -> '23.2 GB' shaped string used
     to populate nemar_catalog.file_size_formatted consistently
     with catalog-sync.
   - syncNemarCatalogFromEnrichment(): UPDATE nemar_catalog with
     COALESCE-preserve semantics so null inputs don't clobber
     existing values; logs and returns changes=0 if the row
     doesn't exist (catalog-sync.ts is responsible for inserts).

2. Call the sync from both writeDatasetMetadataColumns callers:
   - enrich-dataset.ts: passes BIDS-derived cols + author/license
     extracted from finalMetadata.
   - dataset-reindex.ts: BIDS-derived cols only; authors/license
     stay null so the existing nemar_catalog values are preserved
     (those come from enrichment, not reindex).

3. Migration 0023: one-shot backfill of nemar_catalog from the
   datasets row + enrichment_json for every dataset enriched before
   this sync landed. Handles both author shapes. Closes the
   historical gap; future enrichments stay coherent via #2.

Drive-by: replace one non-null assertion with a nullish-coalescing
default in src/lib/git-annex.ts that was blocking the pre-commit
hook; biome-format the new dataset-reindex.ts console.warn.

Unit tests for authorsFromEnrichment + formatFileSize (10 new tests).
Typecheck clean.

Refs nemarOrg/website#1 (discover-card byline).
@github-actions

github-actions Bot commented May 18, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR541

Version: 0.8.22-PR541.b687f6d
Commit: b687f6d


🤖 Updated on each push.

- Migration 0023 age guard: change AND to OR so a row with one age
  bound already set (e.g. age_min=5, age_max NULL) still gets the
  missing bound filled in. With AND the row was skipped entirely.
  Also rewrote the SETs to COALESCE-preserve each bound
  independently.
- src/lib/git-annex.ts: replace '?? 0' with a type-only cast.
  The non-null assertion was correct in the original code (timedOut
  is only true when options.timeout was set); '?? 0' would silently
  print 'Command timed out after 0s' if a future refactor breaks
  that invariant. Cast preserves the original semantics.
- Upgrade console.warn -> console.error in both catalog-sync
  catches (enrich-dataset.ts, dataset-reindex.ts). A persistent
  failure here leaves the list endpoint cache stale on every
  enrichment/reindex; .error is more operator-visible in tail logs
  than .warn.
- New test/migration-0023.unit.test.ts: structural assertions on
  the migration SQL. Both author-extraction shapes (object,
  array-of-objects) pinned; OR-guard for ages pinned;
  COALESCE-preserve semantics asserted via occurrence count.
- New formatFileSize boundary test at exactly 100 GB and 99.5 GB
  for the >=100 toFixed-0 cut-off.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

pr-review-toolkit review (sonnet)

Three reviewers, several findings; key items addressed in b687f6d.

code-reviewer (APPROVE with one item)

Finding Resolution
Migration 0023 age guard AND should be OR — a row with one age bound already set was silently skipped Changed to OR; rewrote the SET to COALESCE-preserve each bound independently
?? 0 in git-annex.ts could silently print "Command timed out after 0s" if reached unexpectedly Replaced with a type-only cast (as number); original code's invariant (timedOut true ⇒ timeout was set) preserved

silent-failure-hunter (1 SILENT FAILURE)

Finding Resolution
Catalog-sync catches log console.warn; persistent failure leaves cache stale per-request with weak operator signal Upgraded both catches to console.error (matches other failure-mode logging in the same file). A catalog_sync_error column on datasets was considered (mirroring metadata_columns_error) but skipped to keep PR scope tight — console.error is sufficient operator signal for a cache-sync layer; will revisit if persistent failures get reported.

pr-test-analyzer (NEEDS MORE COVERAGE)

Gap Resolution
syncNemarCatalogFromEnrichment has no D1-backed test Not added — the repo has no D1 fixture pattern (api.test.ts hits the deployed dev backend). The migration-0023 structural test (below) plus the post-deploy api.test.ts assertions on /datasets?search=nm000166 give equivalent end-to-end coverage.
Migration 0023 has no structural test New test/migration-0023.unit.test.ts (8 tests) — pins both author-extraction shapes, the OR-age-guard, the COALESCE-preserve count, and the synced_at observability touch.
formatFileSize boundary at exactly 100 untested Added two boundary tests (100 GB → "100 GB", 99.5 GB → "99.50 GB")

19/19 unit tests pass, typecheck clean.

@neuromechanist
neuromechanist enabled auto-merge (squash) May 18, 2026 11:47
@neuromechanist
neuromechanist merged commit 4831c7c into dev May 18, 2026
9 checks passed
@neuromechanist
neuromechanist deleted the fix/datasets-authors-source-of-truth branch May 18, 2026 11:49
neuromechanist added a commit that referenced this pull request May 18, 2026
… pull (#546)

* feat(catalog): build nemar_catalog from local D1, no legacy nemar.org pull

Closes the architectural gap that #541 / #543 closed for historical
rows: catalog-sync.ts only knows how to pull from
https://nemar.org/api/dataexplorer/datapipeline, so any dataset
created via the new in-process pipeline never gets a catalog row
unless an operator runs a migration. Two changes make the local
path the source going forward.

1. Hot path: syncNemarCatalogFromEnrichment now UPSERTs.
   Was an UPDATE-only that silently logged 'no row exists' when a
   freshly-enriched dataset didn't have a catalog entry. New behavior:
   INSERT ... ON CONFLICT(id) DO UPDATE so the first enrichment of any
   new dataset auto-creates its catalog row. Requires a non-null
   'name' on the call site (nemar_catalog.name is NOT NULL); both
   callers (enrich-dataset.ts, dataset-reindex.ts) now thread name
   from the d1 row.

2. Bulk path: new backend/src/services/catalog-from-local.ts.
   - buildCatalogRecordFromLocal() pure projector: D1 row + parsed
     enrichment_json -> NemarCatalogRecord shape. Tested for every
     observed shape (object/array authors, null enrichment, on*
     mirrors, name/description fallback chain, search_text).
   - syncCatalogFromLocal() walks every active public dataset and
     INSERT-OR-REPLACEs the catalog row from local data. Batched to
     stay under D1 bound-param limits.
   - New POST /admin/catalog/sync-local endpoint triggers the sweep.

Legacy catalog-sync.ts stays in place; #544 tracks the cron switch
and eventual retirement. Migration 0023 + 0024 already healed the
historical state, and the new hot-path UPSERT + bulk endpoint mean
no future dataset can land in the empty-catalog state.

10 new unit tests for buildCatalogRecordFromLocal cover all the
shape branches plus null defaults. Typecheck clean.

Refs #544.

* review: address findings on #546

- syncCatalogFromLocal: switch INSERT OR REPLACE -> UPSERT
  (INSERT ... ON CONFLICT(id) DO UPDATE SET ...). INSERT OR REPLACE
  in SQLite is DELETE + INSERT which silently clobbered columns this
  path doesn't manage (readme, bids_version, sessions_count,
  latest_version, is_processed). Those are populated by the legacy
  catalog-sync.ts pull for ~70 datasets and would have gone NULL on
  every sweep. UPSERT preserves them.
- Add datasets.published_at to the SELECT, prefer it for publish_date
  on the LocalCatalogRecord. Was using created_at, which would push
  freshly-published rows to the top of newest-first ordering only by
  upload timestamp, ignoring the months-long gap between upload and
  publish for legacy datasets.
- New structural test test/catalog-from-local-sql.unit.test.ts pins
  the UPSERT choice and the deliberate column omission set so a
  future refactor can't silently regress to INSERT OR REPLACE or add
  a column without a real source for the value.
- New structural test test/catalog-upsert-sql.unit.test.ts pins
  syncNemarCatalogFromEnrichment's UPSERT + COALESCE-preserve on
  every updatable column. Catches any revert that would re-introduce
  the silent-no-op on missing rows (#544 root cause).
- Test fixture: add published_at + publish_date preference test.

18 unit tests pass.

This branch was previously deployed

1 inactive deployment
npm — b687f6d3 Deployed May 18, 2026 by neuromechanist via publish #986
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