Skip to content

feat(enrich): auto-generate participants.tsv when missing at root - #553

Merged
neuromechanist merged 3 commits into
devfrom
feature/auto-participants-tsv
May 22, 2026
Merged

neuromechanist merged 3 commits into
devfrom
feature/auto-participants-tsv

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Problem (architectural)

BIDS treats `participants.tsv` as RECOMMENDED rather than REQUIRED, so the bids-validator passes when it's absent. The NEMAR catalog flow doesn't tolerate that: `subject_count` is read exclusively from participants.tsv. Without it the column stays NULL forever, which then re-traps the row in `--missing-metadata` sweeps (the recency guard in #552 stops the loop but doesn't populate the data).

Two paths fall in the trap:

Per-dataset PRs aren't a scalable fix.

Architectural fix

The enrichment pipeline runs after BOTH paths (including `--trust-upstream`). Hooking the auto-generation there means a single point of repair.

New `backend/src/services/participants-tsv.ts` (pure, ~115 lines):

  • `enumerateBidsSubjects(tree)` — every `sub-*` directory at root, deduplicated and sorted; ignores derivatives / sourcedata / code
  • `buildPlaceholderParticipantsTsv(subjects)` — minimal BIDS-compliant TSV with `n/a` for age and sex; refuses to emit a header-only file
  • `ensureParticipantsTsv(tree)` — pure decision: returns content to commit, or null when the file already exists or when there are no subjects (refuses to fabricate)

`enrich-dataset.ts` Stage 1c: when the tree has no participants.tsv at root, call `ensureParticipantsTsv`. Queue the result for the enrichment commit so it lands alongside `.nemar/metadata.json` in a single batched tree write. Use the generated content for the in-memory subject_count parse too so the catalog gets the right count on this very run.

`commitEnrichmentWithBidsignore` accepts an optional `additionalFiles[]` param; when non-empty, forces the batched-tree commit mode even if .bidsignore didn't change, so metadata + bidsignore + participants.tsv land in one commit.

Doesn't bypass --trust-upstream

The whole point: enrichment IS the path that --trust-upstream uses post-import. The auto-generation lands on on* mirrors that arrive without participants.tsv just as well as nm* datasets where the uploader omitted it.

Tests

14 unit tests cover the three pure helpers across the shapes we actually see:

  • Subjects: file-paths-under-sub, dir-entries, dedupe across many files, sort order, alphanumeric ids (NDARxxx style on005511), derivatives/sourcedata/code ignored, empty-tree case
  • TSV format: header + n/a rows, caller-supplied order preserved, throws on empty
  • Decision rule: already-present (no commit), generate, no-subjects-skip
  • `on005262-shape` end-to-end (12 subjects, no participants.tsv upstream → emits 12-row placeholder)

Out of scope

  • `buildEnrichmentCommitPayload` (clientCommits path where the Action does the commit) doesn't yet thread `additionalFiles` through. Follow-up; the in-process commit path covers the common case.
  • CLI `nemar upload` warning when participants.tsv is missing locally ("will be auto-created during publish"). Cosmetic; backend now does the right thing regardless.

Refs nm000133#3 (per-dataset fix); supersedes the per-dataset approach.

BIDS treats participants.tsv as RECOMMENDED rather than REQUIRED, so the
validator passes when it is absent. The catalog flow doesn't tolerate
that: subject_count is read from participants.tsv, and without it the
column stays NULL forever -- which then re-traps the row in
--missing-metadata sweeps (fixed via the recency guard in #552).

Two paths fall in the trap today:
  - nm* uploaded via 'nemar upload' where the user didn't include the
    file (e.g. nm000133; fixed per-dataset via PR nm000133#3)
  - on* imported via --trust-upstream when the OpenNeuro source itself
    lacks one (e.g. ds005262; OpenNeuro upstream confirmed missing)

Fix structurally in enrichment, which is the single point that runs
after BOTH paths:

1. New backend/src/services/participants-tsv.ts -- pure helpers:
   - enumerateBidsSubjects(tree): finds every sub-* dir at root
   - buildPlaceholderParticipantsTsv(subjects): emits a minimal
     BIDS-compliant TSV with n/a for age and sex (the safe placeholder
     BIDS recognizes for 'not collected / not disclosed')
   - ensureParticipantsTsv(tree): pure decision -- returns the content
     to commit, or null when the file already exists or when the tree
     has no subjects (refusing to fabricate)

2. backend/src/services/enrich-dataset.ts Stage 1c: when the tree has
   no participants.tsv, call ensureParticipantsTsv. Queue the result
   for the enrichment commit so the file lands alongside
   .nemar/metadata.json in a single batched commit. Also use the
   generated content for the in-memory subject_count parse so the
   catalog gets the right number on this very enrichment run.

3. backend/src/services/github.ts commitEnrichmentWithBidsignore:
   accept an optional additionalFiles[] param. When non-empty, force
   the batched-tree commit even if .bidsignore didn't change. Lets the
   enrichment commit batch metadata + bidsignore + participants.tsv in
   a single tree write rather than two commits.

Doesn't bypass --trust-upstream: enrichment runs after the OpenNeuro
import path too, so the auto-generation lands on on* mirrors as well.
The dataset repo retains the file across future enrichments; if real
demographics later become available, a follow-up commit can replace
the placeholder.

The clientCommits path (Action does the commit) doesn't yet thread
additionalFiles through buildEnrichmentCommitPayload -- TODO follow-up,
the in-process path covers the common case.

14 new unit tests cover subject enumeration (derivatives ignored,
alphanumeric ids, dedup, sort order), the TSV formatter, and the
decision rule (already-present / generate / no-subjects-skip).
- commitEnrichmentWithBidsignore: defensive duplicate-path guard. The
  treeFiles array is now checked for repeats before commitFilesAsTree
  is called; throws EnrichmentCommitError('duplicate path ...') instead
  of letting GitHub's tree API silently last-wins. Prevents a future
  caller from accidentally clobbering metadataPath or .bidsignore via
  additionalFiles.
- enrich-dataset.ts: log message now says 'pending commit' to make the
  one-cycle inconsistency window (subject_count derived from in-memory
  TSV before the commit succeeds) explicit in tail logs.
- New unit test pins rejection of hyphenated subject labels
  (sub-PD-01). BIDS strictly defines labels as ^[0-9a-zA-Z]+$; we
  intentionally skip non-conformant datasets rather than fabricate
  partial participants.tsv files. The test documents that decision so
  a future regex tweak can't silently flip it.
- Three new tests for commitEnrichmentWithBidsignore additionalFiles
  path (zero coverage before): bidsignore-unchanged forces batched,
  bidsignore-needs-update batches all three, duplicate-path collision
  is rejected.

42 unit tests pass.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

pr-review-toolkit review (sonnet)

Two reviewers, all actionable findings addressed in 63b6c3c.

code-reviewer (APPROVE w/ suggestion)

Finding Resolution
Same-path collision in commitEnrichmentWithBidsignore (a future caller could clobber metadataPath via additionalFiles) Added explicit duplicate-path guard before commitFilesAsTree; throws EnrichmentCommitError('duplicate path ...') instead of relying on GitHub's last-wins behavior
In-memory subject_count derived from unconfirmed content (one-cycle inconsistency, acceptable) Updated log to say "pending commit" so the window is explicit in tail logs

pr-test-analyzer (NEEDS MORE COVERAGE)

Gap Resolution
commitEnrichmentWithBidsignore additionalFiles path had zero coverage Three new tests in tree-batched-commit.test.ts: bidsignore-unchanged forces batched, bidsignore-needs-update batches all three files, duplicate-path collision throws
Hyphenated subject IDs (sub-PD-01) silently rejected — no test documenting the intent Pinned the rejection with a new test in participants-tsv.unit.test.ts. BIDS strictly defines labels as ^[0-9a-zA-Z]+$; we intentionally skip non-conformant datasets rather than fabricate.
Integration test for Stage 1c wiring Skipped — the codebase has no enrichDataset integration harness; reviewers acknowledged this is structural. The two paths (Stage 1c → cols, Stage 1c → commit) are independently covered now

42 unit tests pass, typecheck clean.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Fresh review pass (pr-review-toolkit:code-reviewer)

The PR has been stable for 4 days while dev moved 30+ commits forward; this re-review confirms no new conflicts surfaced.

Critical: none.

Important (1 actionable):

  • Case-sensitive `participants.tsv` check in both `participants-tsv.ts` and `enrich-dataset.ts`. BIDS spec mandates lowercase so this is correct, but a dataset shipping `Participants.tsv` (Windows uploader artifact) would trigger a duplicate file commit. Either add a code comment documenting the deliberate case-sensitive choice, or guard with `.toLowerCase()`. Not blocking merge since BIDS is the canonical contract.

Already addressed by prior review pass (commit "review: address pr-review-toolkit findings on #553"): all the original-review findings.

Strengths confirmed against current dev:

  • `participants-tsv.ts` is pure (no I/O), trivially testable
  • `commitEnrichmentWithBidsignore` 8th-param addition (`additionalFiles = []`) is backwards-compatible
  • Uses `getDatasetsToken(env)` (GH App, not GITHUB_ADMIN_PAT) — satisfies Epic Epic: migrate GITHUB_ADMIN_PAT to a GitHub App installation token #432 auth requirement
  • No structural conflict with Epic Epic: Centralize manifest generation (PR-1 of #557) #559's additions to `github.ts` (`CENTRAL_WORKFLOW_REPO`, `triggerManifestGeneration` — different parts of the file)
  • Pipeline placement (Stage 1c, before MeSH and judge) is correct: `subject_count` is populated before the judge sees the metadata

Companion to PR #579 (the `--missing-metadata` recency guard). These two solve the same root symptom (`nm000133` reindex loop) from different angles. Land together.

@github-actions

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR553

Version: 0.8.27-PR553.40e2a53
Commit: 40e2a53


🤖 Updated on each push.

neuromechanist added a commit that referenced this pull request May 22, 2026
…#579)

Adds a recency guard to the reindex --missing-metadata filter so datasets whose upstream genuinely lacks required columns (e.g. nm000133 has no participants.tsv → subject_count stays NULL) don't get reindexed every hour with no progress. Default 24h; force-retry via --all. Replaces auto-closed #552. Companion to #553.
@neuromechanist
neuromechanist merged commit 02ba14a into dev May 22, 2026
9 checks passed
@neuromechanist
neuromechanist deleted the feature/auto-participants-tsv branch May 22, 2026 19:04

This branch was previously deployed

1 inactive deployment
npm — 40e2a53b Deployed May 22, 2026 by neuromechanist via publish #1060
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