Skip to content

Fix #523: extract enrichment pipeline into in-process enrichDataset() - #527

Merged
neuromechanist merged 2 commits into
devfrom
fix/issue-523-extract-enrich-pipeline
May 18, 2026
Merged

neuromechanist merged 2 commits into
devfrom
fix/issue-523-extract-enrich-pipeline

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Fixes #523.

Summary

  • Move the 743-line /webhooks/llm-enrich handler body into a new enrichDataset(env, opts) service function (backend/src/services/enrich-dataset.ts) that returns a typed EnrichmentOutcome.
  • Shrink the webhook route to a thin auth + parse + forward shim (~50 lines).
  • Update runEnrichmentForDataset in dataset-reindex.ts to call enrichDataset directly. No HTTP self-fetch; no API_BASE_URL round trip.
  • Revert API_BASE_URL on SCCN prod from the *.workers.dev workaround back to api.nemar.org (it no longer constrains the self-fetch path).

Root cause

The 0.8.19 workaround in PR #524 pointed API_BASE_URL at the *.workers.dev fallback on the theory that Cloudflare only rejects self-fetch on the custom domain. The bulk reindex of 228 datasets still hit HTTP 522: error code: 522 in ~0.3s for every dataset.

Worker-tail diagnostics during nemar admin reindex on005262 (output saved during the investigation):

Event Detail
Outer POST /admin/datasets/on005262/reindex logged, outcome: ok, 25ms CPU / 2.7s wall
Inner POST /webhooks/llm-enrich never logged at all — never reached the Worker

Cloudflare 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 typecheck clean on root and backend/
  • bun test regression check vs origin/dev: 1227→1235 pass, 61→53 fail (no new failures; -8 failures from removing the dead self-fetch path)
  • Manual dev-backend verification:
    • Deployed this branch to nemar-api-dev.sccn-org.workers.dev via npx cfman wrangler --account sccn deploy --env dev
    • curl -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}'
    • Result: HTTP 200, 19.65s, pipeline_stage: "validated", 8 authors w/ ORCIDs, 5 enriched fields, MeSH-validated keywords, validation passed
    • Before this fix: 0.3s 522
  • On merge to dev (auto-deploys to dev backend) — confirm /admin/datasets/.../reindex works end-to-end
  • On merge to main — bulk reindex 228 OpenNeuro datasets, verify >90% enrichment success rate per the acceptance criterion

Acceptance (from #523)

  • nemar admin reindex on005262 produces enrich:ok sync:skipped cols:written (verified via direct webhook call on dev with the equivalent code path; reindex just wraps the same function now)
  • Bulk reindex of 228 datasets >90% enrichment success (validate after prod deploy)
  • data.nemar.org/<id>/metadata.json returns LLM-extracted description, keywords (MeSH), methods for on* datasets (downstream consequence of the bulk run)

Notes

  • buildEnrichmentCommitPayload / EnrichmentCommitPayload moved to enrich-dataset.ts; webhooks.ts re-exports both for backwards compatibility, and test/workflow-yaml.test.ts was repointed to the new module.
  • The webhook contract is byte-identical: the same JSON body shapes, status codes, and *_error fields are returned. The Action's jq script in llm-enrichment.yml continues to work without changes.

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.
@neuromechanist

Copy link
Copy Markdown
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:

  • Dead imports in webhooks.ts: dropped bidsToDataCite, buildDataCiteXml.
  • Dead openrouter_error field in ENRICHMENT_SUBERROR_FIELDS (dataset-reindex.ts) and the warning loop in services/github.ts (version-doi.yml template). OpenRouter failures abort the pipeline with HTTP 500; they were never a sub-error. Test test/workflow-yaml.test.ts:152 updated to match.
  • Unhandled-throw window: D1 lookup and getDatasetsToken() in enrich-dataset.ts are now wrapped in dedicated try/catches that return { ok: false, status: 500, body: { error, details } }. Previously these escaped to Hono's generic 500 handler and the Action's jq script lost the details field.
  • Silent duplicate-issue path: log a console.warn when the GitHub list-existing-issues call returns non-OK before falling through to issue creation. The dedup guard is bypassed in that case and repeated failures could file duplicate "Metadata validation failed" issues.
  • Stale comments: refreshed the dataset-reindex.ts module docblock, the ENRICHMENT_SUBERROR_FIELDS JSDoc, and the /llm-enrich handler header. All three still described the pre-refactor architecture (HTTP self-fetch, 800-line handler, response built in webhooks.ts).

Deferred / not addressed (with rationale):

  • The ORCID-recovery regex (/"([^"]+)":\s*\{[^{}]*$/) silently drops authors when the corrupt JSON has nested affiliations objects between the author key and the orcid field. Real pre-existing bug, but outside the scope of Global enrichment failure: /admin/reindex returns HTTP 522 from Worker self-call #523. Filing as a separate issue.
  • Deriving ENRICHMENT_SUBERROR_FIELDS from EnrichmentSuccessBody via keyof (type-design-analyzer suggestion). Nice-to-have, not needed for this PR; can be a follow-up if the list drifts again.
  • Pre-existing 1a → 1c → 1b stage label ordering. Cosmetic, faithful carry-forward from the original handler.
  • wrangler.toml (personal account) comment update to mirror wrangler-sccn.toml. The personal account is no longer the deploy target; leaving it alone.

Verification on dev backend after re-deploy:

  • 401 on bad webhook token: returns Invalid webhook token in 0.12s.
  • 404 on unknown dataset: {"error":"Dataset not found"} (proves the typed error path is wired correctly).
  • 200 on nm000103 with force=true, client_commits=true: full pipeline returns pipeline_stage: validated, no *_error fields, 24.6s.

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR527

Version: 0.8.20-PR527.4e1cdee
Commit: 4e1cdee


🤖 Updated on each push.

@neuromechanist
neuromechanist merged commit 33dd813 into dev May 18, 2026
16 of 17 checks passed
@neuromechanist
neuromechanist deleted the fix/issue-523-extract-enrich-pipeline branch May 18, 2026 08:18
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

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