Skip to content

Plain-HTTP download fallback for nemar dataset download - #1402

Merged
neuromechanist merged 14 commits into
devfrom
feature/http-download-fallback
Sep 15, 2026
Merged

neuromechanist merged 14 commits into
devfrom
feature/http-download-fallback

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1401.

nemar dataset download exited hard when git-annex was missing. It now falls back to a plain
HTTP download, and --http asks for it outright.

$ nemar dataset download xx099900 --http --subjects sub-01
✔ v1.0.2: 3201 files published

Download plan:
  Dataset: xx099900 v1.0.2
  Method:  HTTP (no git-annex)
  Files:   2822 (674.6 MB)
  subjects: sub-01
  skipping stimuli/ (use --stimuli to include)

Downloaded 20 files (670.6 MB), 2802 already present

How it works

One request to <api>/data/<id>/<version>/manifest.json returns every file's path, size,
checksum and byte URL; a bounded worker pool (-j, default 4) fetches the selection. No git, no
git-annex, no GitHub account.

The data plane is addressed as the configured API origin plus /data, not data.nemar.org,
because that mount exists in every environment while the pretty hostname does not. Environment
selection stays in one place: whichever API the CLI is already pointed at.

The decisions worth reviewing

One filter declaration, two consumers. buildBidsFilterArgs now also returns the selection
as glob groups, with a matchesBidsFilter predicate. Writing a second matcher for the HTTP path
would have been easier and wrong: the two would drift, and the symptom is --subjects sub-01
returning different files depending on whether git-annex happened to be installed, which is
close to undebuggable from a bug report. The emitted args are unchanged and the git-annex path
is untouched; a table test pins every glob shape the builder emits against the matcher.

Metadata is never filtered out. A subject-scoped download that dropped
dataset_description.json and the sidecars would not be a readable BIDS dataset. The git-annex
path gets this for free because those files ride along in the clone; here it is explicit. The
manifest's checksum_algorithm: "git" is what identifies them, which is a reading of the annex
policy (ADR 0015) rather than a guess from the file extension — the extension is not reliable in
either direction (ADR 0031: _motion.tsv is data). The same field is what makes --no-data
honest.

Resume needs no flag. A file present at its declared size is skipped. That makes an
interrupted transfer resumable by re-running the command, and makes widening a filter cheap. A
file present at the wrong size is refetched, which is the half-written file an interruption
leaves behind; skipping it would quietly hand back a truncated dataset.

Failures are collected, not thrown. A dataset with thousands of files should not lose a
two-hour transfer to one 403. --require-complete still exits non-zero.

--update and --prune are refused, not ignored. They reconcile a clone against its remote
and there is no clone; silently doing nothing would look like success and leave stale files.

No external tool. rclone and aws s3 sync were both considered and declined: the URLs here
are plain HTTPS rather than the S3 API, so aws s3 sync cannot use them at all, and rclone
would add a runtime dependency most users do not have to replace 60 lines of worker pool
(ADR 0037).

Tests

test/http-download.unit.test.ts, 20 cases, offline — the pool runs against a local Bun.serve
origin rather than a stubbed fetch, so the real request, the real stream-to-disk and the real
resume decision are what is under test. Covers selection, the filter correspondence table,
resume, truncated-file refetch, partial failure, path traversal, and that concurrency is
actually bounded.

test/http-download-live.test.ts, 4 cases, live tier — walks the staging exemplar fleet
(xx099900, 16 MB, persistent by construction) end to end. This exists because the unit suite
cannot cover the field names in the data plane's manifest.json: that document is produced by
the backend and read here by name, and a rename on either side turns into "downloaded 0 files"
with no error. The file-count assertion is what catches that.

Also verified by hand against production on008701 (3,201 files): metadata-only lands 2,802
files and a valid BIDS root; --subjects sub-01 then adds 20 data files and skips the 2,802
already present.

Note for the anonymous-deposit work

This is the download half of what nemarOrg/website#333 needs, but it is not sufficient on its
own: 2,802 of on008701's 3,201 manifest entries point at raw.githubusercontent.com, so with
a private repository the metadata would 404 while the recordings downloaded fine. That is filed
separately.

Recorded as ADR 0062

The decisions above that outlive this PR are written down: a missing git-annex degrades to a
snapshot rather than exiting, the snapshot is deliberately not a repository, resume is size-only
(the version stamp closes the hazard a checksum would), bytes come from the durable bytes_url,
and a transport fault fails the run while a clean 404 does not.

The transfer itself is shared, not copied: src/lib/file-download.ts holds the bounded pool,
resume, retries, the path-traversal guard and the transport-versus-404 split, and both this path
and the OpenNeuro S3 fallback call it. That extraction fixed a live bug in the older copy, which
had been discarding Bun.write's return value and so landing truncated files as healthy ones.

The HTTP download path has no git-annex to hand --include/--exclude to,
so the same selection is now also returned as glob groups with a
matchesBidsFilter predicate. One declaration, two consumers: a second
matcher would drift, and the symptom would be --subjects returning
different files depending on whether git-annex happened to be installed.

The args are unchanged; the git-annex path is untouched.
Reads the data plane's manifest (one request: every path, size, checksum
and byte URL) and fetches a selection with a bounded worker pool. No git,
no git-annex, no GitHub account.

Resume is inherent: a file present at its declared size is skipped, so
re-running picks up where an interrupted transfer stopped and widening a
filter only fetches what is new. A failure is collected rather than
thrown, so one 403 does not lose a long transfer.

Addressed through the configured API origin's /data mount rather than
data.nemar.org, because that mount exists in every environment, keeping
environment selection in one place.
A missing git-annex was a hard exit. It now falls back to the HTTP path,
announced rather than silent, and --http asks for it outright. --update
and --prune are refused there rather than silently doing nothing: they
reconcile a clone against its remote and there is no clone.
The unit suite cannot cover the field names of the data plane's
manifest.json, and a rename on either side turns into "downloaded 0
files" with no error. These run the real command against the staging
exemplar fleet and check what landed on disk.
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1402

Version: 0.10.4-PR1402.084e805
Commit: 084e805


🤖 Updated on each push.

neuromechanist added a commit that referenced this pull request Sep 14, 2026
A dataset that has ever been public cannot be made anonymous: the
DataCite record is harvested and permanent, the git history is in every
clone, and the catalog has already served the real authors. Hiding the
fields afterwards changes what NEMAR displays and nothing about what is
known, while telling the depositor they are anonymous.

Also records the blocker the download work surfaced: 88 percent of a
dataset's files are served from raw.githubusercontent.com, so a private
repository 404s all the metadata while the recordings download fine
(#1403), and notes that the HTTP download path (#1402) now exists.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review: two independent passes (code quality, silent failures)

Both found the same three things independently, which is the strongest signal in here. Fixes are
in progress on this branch.

Critical

1. A short or wrong body is reported as a complete file. Bun.write(path, response) returns
the true byte count and does not throw on a truncated body; the code discards it and returns the
manifest's declared size, which then feeds the byte total and the green success line. Verified
directly: a 5-byte body against a 1000-byte declaration writes 5, returns 5, no throw. A captive
portal or MITM proxy answering with an HTML login page yields Downloaded 412 files (1.2 GB)
and exit 0, with HTML where the recordings should be. Free to fix.

2. Resume-by-size silently mixes dataset versions. dataset_description.json carries
DatasetVersion, and 1.0.0 → 1.0.1 is byte-identical in length, so it is skipped on a
re-run after a republish. The tree ends up a mix of two versions whose only version marker names
the older one. The command's own printed advice ("re-run to widen the selection; already-present
files are skipped") is the trigger. The git-annex path cannot do this: --resume refuses when
local and remote versions differ.

3. --http still hard-requires the GitHub CLI. COMMAND_TOOLS.download = ["gh"] and
checkPrerequisitesForCommand("download") runs before the --http branch, so the path whose
entire point is "no git, no git-annex, no GitHub account" dies on a slim container with
"GitHub CLI (gh) not installed". Defeats the purpose on exactly the machines it was built for.

Important

  • Every failure exits 0 unless --require-complete. The git-annex path deliberately
    separates transport failure (exit 1) from content genuinely absent upstream (exit 0, ADR 0005);
    this collapsed both. Fill the disk at file 2,001 of 6,000 and download && analyze runs on a
    third of a dataset.
  • No retry or backoff, while most ENTRIES fetch from raw.githubusercontent.com, which
    throttles by address. On nm000103 that is 17,620 of 21,142 entries; one 429 per file becomes
    thousands of permanent failures on a healthy link.
  • The manifest is cast, not validated. The repo validates wire shapes with Zod precisely to
    avoid this (api/client.ts:60-66); a renamed checksum_algorithm makes --no-data select
    nothing and exit 0, and the only guard is a skipIf-able live test.
  • No .git or identity guard on the output directory. The default output path is the same
    one the annex clone uses; writing through a dangling annex symlink corrupts the object store.
    Two different datasets into one -o merges them.
  • Errors lose their file. Only the non-2xx branch prefixes entry.path, so 800 dropped
    connections are 800 pathless messages, ten shown, the rest unrecoverable.
  • .json() sits outside the try, so a captive portal surfaces as
    JSON Parse error: Unrecognized token '<'. No Array.isArray guard on the version listing.
    One 404 message tells a user with a public dataset and a missing manifest to go install
    git-annex. Zero-selection returns before --require-complete is consulted.
  • The metadata-always-survives guarantee rests on an unchecked field name.
  • The worker pool duplicates openneuro.ts:289-335 line for line, and the copy fixes a bug
    the original still has, so the two now differ. ADR 0037 names this shape.

Suggestions

-j silently clamped to 16; new Glob() recompiled per pattern per path (~80k on a large
dataset); help text still says "Requirements: git-annex installed" and never mentions --http;
no ADR for the decisions this PR takes; the "keeps environment selection in one place" comment
is true of the manifest request only, since bytes come from whatever host bytes_url names.

Held up under scrutiny

The worker pool is correct — queue.shift() completes before the first await, so no entry is
taken twice, and the counters are only mutated on the single-threaded event loop. isMetadataEntry
reading checksum_algorithm rather than the file extension is correctly grounded in ADR 0015 and
ADR 0031, and was confirmed against the live manifest. Metadata bypassing the BIDS filter so a
--subjects download still leaves a readable BIDS root. Path traversal guarded before any write,
and tested. --update/--prune refused rather than ignored. The tests are real — a live
Bun.serve origin, real sockets, real writes — and the live test's tier routing and
manifest-derived assertion are right. One reviewer independently probed Bun.Glob against every
pattern shape the filter emits and checked the case-sensitivity question against real git-annex
10.20260901: they agree on everything emitted here. The "one declaration, two consumers" comment
still overclaims — there are two matcher engines, not one — and will be reworded to say what is
actually true.

Critical: Bun.write returns the true byte count and does not throw on a
short body, so returning the manifest's declared size reported a truncated
response or a captive portal's login page as a complete file. Every write
is now compared against the declared size, and a mismatch is removed
rather than left looking healthy.

--http no longer requires the GitHub CLI. checkPrerequisitesForCommand
demands `gh` and ran before the branch, so the path whose point is "no
git, no git-annex, no GitHub account" died on exactly the containers and
login nodes it was built for.

Resume no longer mixes versions: the output directory carries a stamp, and
a git repository, a different dataset, or a different version is refused.
dataset_description.json is byte-identical in length across a patch bump,
so it was being skipped and the tree misreported its own version.

Transport, auth and disk faults now exit non-zero without
--require-complete; a clean 404 stays a reported state per ADR 0005.
Throttled and transient responses retry with backoff. Every error names
its file and the full list is written to the output directory. The
manifest is validated against a shared contract schema rather than cast,
and a manifest with no git-tracked entries is refused instead of silently
dropping every sidecar. Non-JSON and malformed documents surface as typed
errors; a missing manifest no longer reports a public dataset as private.
Globs are compiled once per filter, -j is validated, and the two comments
that overclaimed now say what is actually true.
neuromechanist added a commit that referenced this pull request Sep 14, 2026
Two ADR citations named the wrong decision: 0010 is import-time S3 copy,
not the Worker (that is 0002); 0017 is server-side visibility filtering,
not the publish flip (that is 0001). The manifest canary is not a blocker
either -- production runs the central workflow, passes skipCanary
unconditionally, and that workflow has an escape hatch labelled for
private repos and clones with an App token. A4 stays first, for a
different reason.

Also: .nemar/metadata.json is committed by the backend, not the
depositor, so no depositor-side scrub can suppress it; the website has
two URL-fabrication sites, so nulling the field hides neither; #1402 is
proposed, not merged; owner_github is "nemarAdmin" rather than null, and
the imported git history names real people; ids gap-fill rather than run
sequentially.

Adds what the document missed: two more visibility proxies (fleet drift,
MCP events), the governance gap an unprotected main leaves open for the
whole review window, the website's browser-side GitHub fetches,
enrichment_json and readme on the withhold list, and the ordering
constraint on de-anonymization.
The plain-HTTP dataset path and the OpenNeuro S3 fallback each carried
their own worker pool. Extract lib/file-download.ts and have both call it,
so the pool, resume, retries, path-traversal guard and the
transport-versus-404 split are stated once.

OpenNeuro gains what only the newer copy had: writes verified against the
declared size (Bun.write returns a short count without throwing, so a
truncated body landed as a healthy file), retries with backoff, and errors
that name the file. Its result shape is unchanged; a skipped file still
counts as downloaded there.
Records what this path decided: a missing git-annex degrades to a snapshot
rather than exiting, the snapshot is deliberately not a repository, resume is
size-only with the version stamp closing the hazard checksums would, bytes come
from the durable bytes_url, and a transport fault fails the run while a clean
404 does not.

Also resolves conflict markers that were committed into AGENTS.md on dev; the
ADR list entry is 0060, not 0058.
neuromechanist added a commit that referenced this pull request Sep 15, 2026
* docs: analyze pseudonymous deposit for double-blind review

Works out the five requirements, the twelve-item leak inventory verified
against production, and what each candidate design requires. No decision
taken; the ADR has to answer the collisions with ADR 0002, 0026 and 0041
first.

Refs #1399.

* docs: choose public data with a private repository

Direction taken: serve the dataset on data.nemar.org and the website as
any public dataset, keep the GitHub repository private, and flag the page
as temporarily anonymous. That removes the tokenized review link entirely,
since with no per-reviewer access mechanism there is nothing to conceal in
the other direction.

Also corrects the staleness claim: since #662 the cron warns the owner and
hands off to admins, it does not delete. The hazard is five deletion
warnings mid-review, not data loss.

Records the three predicates the new shape creates: the website's
fabricated clone URL, the CLI download path that clones a private repo,
and the two candidate queries that use D1 visibility as a proxy for
repository visibility.

Refs nemarOrg/website#333, #1399.

* docs: anonymity is only available before first publication

A dataset that has ever been public cannot be made anonymous: the
DataCite record is harvested and permanent, the git history is in every
clone, and the catalog has already served the real authors. Hiding the
fields afterwards changes what NEMAR displays and nothing about what is
known, while telling the depositor they are anonymous.

Also records the blocker the download work surfaced: 88 percent of a
dataset's files are served from raw.githubusercontent.com, so a private
repository 404s all the metadata while the recordings download fine
(#1403), and notes that the HTTP download path (#1402) now exists.

* docs: nm000103-107 are public, not private

* docs: the data plane should keep its own URL

* docs: correct the errors the fact-check found

Two ADR citations named the wrong decision: 0010 is import-time S3 copy,
not the Worker (that is 0002); 0017 is server-side visibility filtering,
not the publish flip (that is 0001). The manifest canary is not a blocker
either -- production runs the central workflow, passes skipCanary
unconditionally, and that workflow has an escape hatch labelled for
private repos and clones with an App token. A4 stays first, for a
different reason.

Also: .nemar/metadata.json is committed by the backend, not the
depositor, so no depositor-side scrub can suppress it; the website has
two URL-fabrication sites, so nulling the field hides neither; #1402 is
proposed, not merged; owner_github is "nemarAdmin" rather than null, and
the imported git history names real people; ids gap-fill rather than run
sequentially.

Adds what the document missed: two more visibility proxies (fleet drift,
MCP events), the governance gap an unprotected main leaves open for the
whole review window, the website's browser-side GitHub fetches,
enrichment_json and readme on the withhold list, and the ordering
constraint on de-anonymization.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Second round of review follow-ups, closing the two findings that were flagged and deferred.

One downloader, not two. The worker pool duplicated src/lib/openneuro.ts line for line, which is the shape ADR 0037 says to settle explicitly rather than let drift. It is now src/lib/file-download.ts, called by both: the bounded pool, resume, retries, the path-traversal guard and the transport-versus-404 split are stated once, and each caller supplies only its own file list and URL mapping.

The copy had already drifted, which is the argument for extracting it. The OpenNeuro path was discarding Bun.write's return value, so a truncated body landed as a healthy file and the run reported success; it now gets the size check, the retries and the file-named errors the newer copy had. Its result shape is unchanged (a skipped file still counts as downloaded there), and the suite passes against real S3.

ADR 0062 records what this path decided: a missing git-annex degrades to a snapshot rather than exiting, the snapshot is deliberately not a repository, resume is size-only with the version stamp closing the hazard checksums would otherwise cover, bytes come from the durable bytes_url, and a transport fault fails the run while a clean 404 does not. It also records why not rclone/wget: this path exists for machines missing a tool, so requiring a different tool trades one prerequisite for another.

Also in this push: AGENTS.md on dev carries committed conflict markers (<<<<<<< HEAD at line 104, ADR 0058 versus 0060). Resolved here since the file was being edited anyway.

The pool reports only what it transferred, which made a resumed OpenNeuro download print '1200 files (0 B)'. It now also reports the declared size of the files it skipped, so that caller can keep stating what is on disk.
The shared pool clamps concurrency to MAX_CONCURRENCY. The NEMAR HTTP path already says so when --jobs exceeds it; the OpenNeuro path did not, so -j 32 silently became 16.
…fallback

# Conflicts:
#	src/commands/dataset.ts
@neuromechanist
neuromechanist merged commit 13c560c into dev Sep 15, 2026
12 checks passed

This branch was previously deployed

1 inactive deployment
npm — 084e805a Deployed Sep 15, 2026 by neuromechanist via publish #2607
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