Skip to content

Fix import README stub and enrichment self-loop (#642, #643) - #644

Merged
neuromechanist merged 2 commits into
devfrom
feature/issue-642-import-readme-handling
May 28, 2026
Merged

neuromechanist merged 2 commits into
devfrom
feature/issue-642-import-readme-handling

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Fixes two bugs that compounded on nemarDatasets/on007827, causing a 60-runs/hr enrichment loop that burned through Actions minutes and OpenRouter calls until manually disabled.

Bug 1: Import wrote a stub README that hid the upstream one (#642)

appendOpenNeuroProvenance in src/lib/import-openneuro.ts checked for README.md only. OpenNeuro ships README (no extension, BIDS-compliant), so existsSync returned false and the importer wrote a fresh 7-line stub to README.md, leaving the upstream README orphaned. The LLM enricher (enrich-dataset.ts:281) looks at README.md first, so it has been enriching against the stub — explaining the generic, content-free description fields on imported datasets.

Confirmed on on007827: source had 6515-byte README, mirror got a 366-byte stub.

Fix (renamed function to ensureReadmeMd):

  • README exists, no extension → git mv README README.md. Content untouched.
  • README.md / README.rst / README.txt / any suffix → leave alone. Provenance is captured in .nemar/metadata.json (IsDescribedBy / IsIdenticalTo) and the website surfaces it from there.
  • No README upstream → fall back to writing a small provenance-only stub.

Matches the user's stated rule: "README change only is to add the DOI tag up top and add .md to it, no content should be changed."

Bug 2: Enrichment self-triggered until manually stopped (#643)

Two issues composed into an infinite loop:

  1. ENRICHMENT_TRIGGER_PATHS (backend/src/routes/webhooks.ts:1438) included .nemar/metadata.json — but that file IS the enrichment output, not an input. Each enrichment commit re-triggered enrichment.
  2. The source-hash skip in enrich-dataset.ts:419 only fired at pipeline_stage === "validated". For on007827 Stage 3 never reached validated (cascaded from Bug 1 — the stub didn't substantiate the LLM's description claims), so the skip never engaged. Haiku 4.5's non-deterministic prose ensured .nemar/metadata.json looked "changed" on every cycle.

Fix:

  • Drop .nemar/metadata.json from ENRICHMENT_TRIGGER_PATHS. Manual recovery is still available via workflow_dispatch on nemarDatasets/.github/run-enrichment.yml.
  • Extend the source-hash skip to also short-circuit at pipeline_stage === "enriched" when sources are unchanged. Belt-and-suspenders against any future trigger that gets through.

Stop-the-bleeding action

Run Enrichment workflow on nemarDatasets/.github has been disabled manually while this PR is in flight. After merge + deploy, I'll re-enable and queue a manual workflow_dispatch for on007827 once its README has been restored from OpenNeuroDatasets/ds007827/README.

Affected datasets

Only on007827 is currently in an active loop (51 commits in 1.5h before the workflow was disabled). The README-stub bug was introduced in b5b75c3 (2026-05-18); on005261 (imported same day) was unaffected because the bug had not yet shipped to npm. All earlier on* imports predate the bug.

Test plan

  • bun test test/import-openneuro.test.ts — 32 pass (added 7 new tests for ensureReadmeMd covering README-no-ext, README.md, README.rst, README.txt, no-README, no-DOI, and idempotency)
  • bun test test/webhook-github-push.test.ts — 40 pass (updated the test that asserted the buggy .nemar/metadata.json dispatch; added new positive case for "README + metadata.json together still dispatches")
  • bun test (full suite) — 1619 pass, 41 skip, 0 fail across 88 files
  • After merge + deploy: re-enable Run Enrichment workflow and confirm a single workflow_dispatch on on007827 with force=true (a) restores rich metadata from the real README, (b) commits exactly once, (c) does not re-fire.

Follow-ups

  • Restore on007827's README content from OpenNeuroDatasets/ds007827/README before re-enrichment.
  • Audit other on* datasets for stub READMEs that should be restored from upstream.
  • Optional: add an attempt counter to .nemar/metadata.json so a dataset that fails Stage 3 repeatedly surfaces in the dashboard rather than silently re-firing on the next source change.

Two bugs that compounded on on007827:

(1) Import wrote a 7-line README.md stub when upstream shipped README (no
extension), leaving the real upstream README orphaned. The downstream
LLM enricher reads README.md first, so it has been seeing only the stub.
ensureReadmeMd now: rename README -> README.md if needed, keep any
suffixed variant (.md, .rst, .txt) untouched, fall back to a stub only
when no README exists upstream. Content is never modified.

(2) Enrichment self-triggered: .nemar/metadata.json was on the push
trigger paths AND the source-hash skip only fired at pipeline_stage
== "validated". Datasets stuck at "enriched" (Stage 3 fails) looped
every minute as Haiku's non-deterministic prose changed the file each
run. Drop .nemar/metadata.json from triggers; extend the skip to
short-circuit at "enriched" too when source_hash matches.

Fixes #642, #643
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Multi-agent review summary

Ran 5 specialized reviewers in parallel. Aggregated findings below.

Verdict

Code review: Ship it. No critical or important blockers.

Critical findings to address before merge

  1. Case-sensitivity bug in ensureReadmeMd regex (test-coverage HIGH, silent-failure MEDIUM) — src/lib/import-openneuro.ts:396

    • /^README(\.[A-Za-z0-9]+)?$/ is case-sensitive but case-insensitive filesystems (macOS APFS, Windows NTFS, the GitHub Actions ubuntu runner has case-sensitive ext4 so this is fine for CI but still wrong for local dev) report filenames with their authored case. An upstream Readme.md would miss the regex, fall through to the "no README" fallback, and writeFileSync(join(datasetPath, "README.md"), block) would OVERWRITE it on case-insensitive FS.
    • Fix: add /i flag OR document the case-sensitive intent and add a fallback existsSync check before the write.
  2. Skip-guard extension has zero tests (test-coverage CRITICAL) — backend/src/services/enrich-dataset.ts:419

  3. README collision is silently first-match-wins (silent-failure MEDIUM) — src/lib/import-openneuro.ts:411-419

    • If upstream ships BOTH README and README.md, entries.find(...) order is OS-dependent. On Linux this can renameSync(README, README.md) and clobber the existing markdown.
    • Fix: check existsSync('README.md') before renaming, OR scan all matches and detect collision explicitly.

Important findings (worth addressing)

  1. Type design: kept.path: string too loose (type-design 6/10 invariant) — tighten to path: \README${ReadmeExt}`and consider attachingpathsToStage` to each variant so the caller drops the switch.

  2. Partial filesystem state on metadata-step failure (silent-failure HIGH) — src/lib/import-openneuro.ts:741. If seedMetadata succeeds and ensureReadmeMd throws, .nemar/metadata.json is written but README isn't renamed and no commit is made. Error message at line 745 doesn't surface the temp path for forensics.

  3. shouldDispatchEnrichment multi-commit loop pin (test-coverage MEDIUM) — add a test where the push has multi-commit history (commits[0] touches README.md, commits[1] touches only metadata.json) → asserts dispatch still fires.

Minor (skip if time-pressed)

Positive observations

  • Discriminated union (ReadmeOutcome) with literal tags is compiler-checked.
  • Tests cover happy paths solidly (rename, kept .md/.rst/.txt, fallback, idempotency).
  • Comment-removal of #535 reference is consistent with the design (provenance still avoids dataset_description.json; lives only in .nemar/metadata.json and the optional fallback stub).
  • Error paths in webhooks.ts handler are not silent — shouldDispatchEnrichment returns structured {dispatch: false, reason} and the response carries the reason.

Stop-the-bleeding action (separate from PR)

Force-pushed nemarDatasets/on007827/main from bf284d9 back to bfe910f (last commit before the first enrichment loop iteration). Original 6515-byte README is intact. After this PR deploys, re-enable Run Enrichment on nemarDatasets/.github and the next enrichment cycle will (a) read the real README, not the stub, and (b) skip on unchanged source_hash instead of looping.

1. Case-sensitive regex bug (review crit #1): /^README(\.[A-Za-z0-9]+)?$/
   is now /i so `Readme.md`, `readme`, and other case variants are
   detected. On case-insensitive filesystems (macOS APFS, Windows NTFS)
   the prior regex would miss `Readme.md`, fall through to the stub
   branch, and writeFileSync('README.md', stub) would silently overwrite
   the upstream-authored file.

2. README collision: when upstream ships BOTH `README` and `README.md`,
   the new preference rule picks the suffixed variant first. Renaming
   the bare `README` over an existing `.md` would have destroyed
   upstream content; the suffixed-first order is now explicit and
   deterministic regardless of OS listing order.

3. Skip-guard untested (review crit #2): extracted decideSkipEnrichment
   as a pure helper and pinned the full 5-arm decision table:
   - validated + matching hash → skip
   - enriched + matching hash → skip  (the #643 fix)
   - validated/enriched + mismatch → proceed
   - source_hash undefined (migration arm) → proceed
   - seeded / unknown stages → proceed
   - forceReenrich=true → always proceed
   Plus edge cases for empty-string source_hash. 14 new test cases.

Test counts: import-openneuro.test.ts 32→38, new enrich-skip-guard
suite 14, full suite 1639/41 skip/0 fail.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review crits addressed (cc5b137)

1. Case-sensitive regex bug — fixed

README_FILENAME_REGEX now uses /i. On case-insensitive filesystems an upstream Readme.md would have been missed by the scan and silently clobbered by the fallback writeFileSync('README.md', stub). New tests pin: Readme.md (mixed-case) is kept, readme (lowercase bare) is renamed, README.MD (uppercase ext) is kept.

2. README collision — fixed

Added an explicit preference rule: when multiple README variants exist, suffixed files (*.md, *.rst, *.txt) win over bare README. Removes OS-listing-order non-determinism and prevents the bare-README rename from clobbering an existing .md. New test asserts: with both README and README.md present, outcome is kept: README.md and both files end with their original content.

3. Skip-guard untested — fixed

Extracted decideSkipEnrichment as a pure helper in backend/src/services/enrich-dataset.ts and added test/enrich-skip-guard.test.ts (14 tests) pinning the full decision table:

Stage source_hash match force Result
validated match false skip
enriched match false skip (the #643 fix)
validated mismatch false proceed: "sources changed"
enriched mismatch false proceed: "sources changed"
validated/enriched undefined false proceed: "migration"
seeded match false proceed (cache must not silently expand)
unknown match false proceed (defensive)
any any true proceed: "force=true"

Plus pinned edge cases: empty-string source_hash is distinct from undefined; both empty strings match (documented trade-off).

Skipped (per request — only 3 criticals)

  • Type-design tightening (kept.path literal union + per-variant pathsToStage) — review item Remove automatic collaborator addition on user approval #4
  • Partial-state forensics on metadata-step failure — silent-failure HIGH
  • Comment forensic-detail rot — comment review nit
  • Multi-commit dispatch pin in webhook-github-push.test.ts — test-coverage MEDIUM

These remain as follow-ups if you want them in a separate PR.

Test counts

  • test/import-openneuro.test.ts: 32 → 38 (6 new cases)
  • test/enrich-skip-guard.test.ts: 14 (new file)
  • Full suite: 1639 pass / 41 skip / 0 fail

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR644

Version: 0.8.38-PR644.cc5b137
Commit: cc5b137


🤖 Updated on each push.

@neuromechanist
neuromechanist merged commit edd7f2b into dev May 28, 2026
9 of 10 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-642-import-readme-handling branch May 28, 2026 16:27

This branch was previously deployed

1 inactive deployment
npm — cc5b1378 Deployed May 28, 2026 by neuromechanist via publish #1191
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