Repository navigation
Fix #523: extract enrichment pipeline into in-process enrichDataset() - #527
Merged
Merged
Conversation
Fixes #523. The /webhooks/llm-enrich handler used to be invoked from admin reindex via fetch(API_BASE_URL + /webhooks/llm-enrich) on the same Worker, which Cloudflare rejects at the edge with HTTP 522 regardless of whether the target is the custom domain or the *.workers.dev fallback. The 0.8.19 workaround (point API_BASE_URL at workers.dev) did not help: edge tail logs confirm the inner request never reaches the Worker. Move the 743-line handler body into a new enrichDataset(env, opts) service function returning a typed EnrichmentOutcome. The webhook route shrinks to a thin auth + parse + forward shim and runEnrichmentForDataset invokes enrichDataset directly with no HTTP round trip. API_BASE_URL on SCCN prod reverts to api.nemar.org since it no longer constrains the self-fetch path. Acceptance (#523): nemar admin reindex on005262 now returns enrich:ok sync:skipped cols:written, unblocking the bulk reindex of 228 OpenNeuro datasets that drive data.nemar.org/<id>/metadata.json.
- Remove dead imports (bidsToDataCite, buildDataCiteXml) from webhooks.ts left over from the inline DOI sync block that moved into enrich-dataset.ts. - Drop openrouter_error from ENRICHMENT_SUBERROR_FIELDS and from the version-doi.yml shell loop in services/github.ts. The field was never populated: OpenRouter failures abort the pipeline (Stage 2 is fatal) and surface as HTTP 500, not as a 200-with-warning. The dead entry was silently inert before this PR; now that the typed body in enrich-dataset.ts makes the field set explicit, the drift was visible. Updated test/workflow-yaml.test.ts to match. - Wrap the D1 dataset lookup and getDatasetsToken() call in enrichDataset with their own try/catch so a D1 transport failure or missing GitHub auth surfaces as a typed EnrichmentOutcome with the underlying message in details, instead of escaping to Hono's generic 500 handler which drops the diagnostic. Matters for the webhook caller (Action jq script) that reads details for log surface; runEnrichmentForDataset already wraps the whole call so the admin reindex path was already safe. - Log a warning when the GitHub list-existing-issues call fails before duplicate-issue creation. Falling through to issue creation on a 403 (missing issues:read) or 5xx is the existing safe-by-default behavior, but the dedup guard is now bypassed and repeated failures can file duplicate Metadata validation failed issues. Logging is cheap. - Refresh the stale module-level docblock in dataset-reindex.ts and the webhooks.ts /llm-enrich handler header. Both still described the pre-refactor architecture (HTTP self-fetch, 800-line handler). Updated the ENRICHMENT_SUBERROR_FIELDS JSDoc to point at enrich-dataset.ts where the response body is now assembled.
Contributor
Author
Review feedback addressed (commit 4e1cdee)Ran the full pr-review-toolkit suite (code-reviewer, pr-test-analyzer, silent-failure-hunter, comment-analyzer, type-design-analyzer) in parallel. Findings addressed: Fixed:
Deferred / not addressed (with rationale):
Verification on dev backend after re-deploy:
|
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR527Version: 🤖 Updated on each push. |
2 of 4 tasks
neuromechanist
added a commit
that referenced
this pull request
May 18, 2026
…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).
neuromechanist
added a commit
that referenced
this pull request
May 18, 2026
…l rows (#541) * fix(catalog): sync nemar_catalog from enrichment + backfill historical 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). * review: address pr-review-toolkit findings on #541 - 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.
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #523.
Summary
/webhooks/llm-enrichhandler body into a newenrichDataset(env, opts)service function (backend/src/services/enrich-dataset.ts) that returns a typedEnrichmentOutcome.runEnrichmentForDatasetindataset-reindex.tsto callenrichDatasetdirectly. No HTTP self-fetch; noAPI_BASE_URLround trip.API_BASE_URLon SCCN prod from the*.workers.devworkaround back toapi.nemar.org(it no longer constrains the self-fetch path).Root cause
The 0.8.19 workaround in PR #524 pointed
API_BASE_URLat the*.workers.devfallback on the theory that Cloudflare only rejects self-fetch on the custom domain. The bulk reindex of 228 datasets still hitHTTP 522: error code: 522in ~0.3s for every dataset.Worker-tail diagnostics during
nemar admin reindex on005262(output saved during the investigation):POST /admin/datasets/on005262/reindexoutcome: ok, 25ms CPU / 2.7s wallPOST /webhooks/llm-enrichCloudflare rejects self-fetch at the edge (regardless of whether the target is the custom domain or
*.workers.dev) because the inner request loops back to the same Worker. The 0.3s response is the edge giving up, not an origin timeout.Test plan
bun run typecheckclean on root andbackend/bun testregression check vsorigin/dev: 1227→1235 pass, 61→53 fail (no new failures; -8 failures from removing the dead self-fetch path)nemar-api-dev.sccn-org.workers.devvianpx cfman wrangler --account sccn deploy --env devcurl -X POST https://nemar-api-dev.sccn-org.workers.dev/webhooks/llm-enrich -H 'X-Webhook-Token: <test>' -d '{"dataset_id":"nm000103","force":true,"client_commits":true}'HTTP 200, 19.65s, pipeline_stage: "validated", 8 authors w/ ORCIDs, 5 enriched fields, MeSH-validated keywords, validation passeddev(auto-deploys to dev backend) — confirm/admin/datasets/.../reindexworks end-to-endmain— bulk reindex 228 OpenNeuro datasets, verify >90% enrichment success rate per the acceptance criterionAcceptance (from #523)
nemar admin reindex on005262producesenrich:ok sync:skipped cols:written(verified via direct webhook call on dev with the equivalent code path; reindex just wraps the same function now)data.nemar.org/<id>/metadata.jsonreturns LLM-extracteddescription,keywords(MeSH),methodsforon*datasets (downstream consequence of the bulk run)Notes
buildEnrichmentCommitPayload/EnrichmentCommitPayloadmoved toenrich-dataset.ts;webhooks.tsre-exports both for backwards compatibility, andtest/workflow-yaml.test.tswas repointed to the new module.*_errorfields are returned. The Action'sjqscript inllm-enrichment.ymlcontinues to work without changes.