Skip to content

feat: add UBERON brain anatomy matching for all species - #1825

Draft
bendichter wants to merge 9 commits into
masterfrom
add-uberon-anatomy
Draft

bendichter wants to merge 9 commits into
masterfrom
add-uberon-anatomy

Conversation

@bendichter

@bendichter bendichter commented Mar 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Adds UBERON ontology-based brain region matching, extending anatomy extraction to all species (not just mouse)
  • For mice: tries Allen CCF first, falls back to UBERON per-token
  • For other species: tries UBERON directly
  • Synonym scope is a settable parameter (frozenset[str]), defaulting to EXACT only
  • Bundles ~2,400 nervous system descendant terms from UBERON as a compact JSON (~479KB)
  • Generation script parses the OBO file directly with no library dependencies

New files

  • dandi/data/generate_uberon_structures.py — downloads and parses uberon.obo, extracts nervous system descendants
  • dandi/data/uberon_brain_structures.json — bundled lookup data (2,408 structures, 9,717 synonyms)

Modified files

  • dandi/metadata/brain_areas.py — UBERON loading, lookup, and matching functions; locations_to_mouse_anatomy() with Allen→UBERON fallback
  • dandi/metadata/util.py — _extract_brain_anatomy() now handles all species
  • dandi/tests/test_brain_areas.py — tests for UBERON matching, synonym scope control, and Allen/UBERON fallback
  • .pre-commit-config.yaml, pyproject.toml — codespell exclusions for new JSON

Test plan

  • All 56 brain area tests pass locally
  • All 179 metadata tests pass (including existing brain anatomy integration tests)
  • Pre-commit passes (black, isort, codespell, flake8)
  • CI passes on all platforms

🤖 Generated with Claude Code

For mice, location tokens are first matched against Allen CCF, then
fall back to UBERON.  For all other species, UBERON is tried directly.
Synonym scope (EXACT, RELATED, NARROW, BROAD) is a settable parameter,
defaulting to EXACT only.

- Add generate_uberon_structures.py to parse the UBERON OBO file and
  produce a bundled JSON of ~2,400 nervous-system descendants
- Add UBERON lookup/matching functions to brain_areas.py
- Update _extract_brain_anatomy in util.py to handle non-mouse species
- Add comprehensive tests for UBERON matching and Allen/UBERON fallback

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@bendichter bendichter added the minor Increment the minor version when merged label Mar 29, 2026
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@bendichter bendichter added enhancement New feature or request minor Increment the minor version when merged and removed enhancement New feature or request minor Increment the minor version when merged labels Mar 29, 2026
@codecov

codecov Bot commented Mar 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.88476% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.90%. Comparing base (3a172c0) to head (2152bd3).

Files with missing lines Patch % Lines
dandi/cli/cmd_service_scripts.py 60.00% 2 Missing ⚠️
dandi/data/generate_uberon_structures.py 98.90% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1825      +/-   ##
==========================================
+ Coverage   90.75%   90.90%   +0.15%     
==========================================
  Files          98      100       +2     
  Lines       15267    15532     +265     
==========================================
+ Hits        13855    14120     +265     
  Misses       1412     1412              
Flag Coverage Δ
unittests 90.90% <98.88%> (+0.15%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

bendichter and others added 2 commits March 29, 2026 12:44
Instead of passing a flat set of scopes, use a max_synonym_scope
parameter (default "EXACT").  Matching tries tiers in precision order:
EXACT > NARROW > BROAD > RELATED, up to the specified maximum.
Term names are always tried first before any synonym tier.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Thread the scope parameter through so callers can control how
permissive UBERON synonym matching is.  Defaults to EXACT.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

@yarikoptic yarikoptic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

most likely my requests could be handled by an agent quite sensibly

Comment on lines +65 to +66
m = re.match(r'synonym:\s+"(.+?)"\s+(EXACT|RELATED|NARROW|BROAD)', line)
if m:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tend to instruct my AIs to do walrus for such... I guess we need to adjust DEVELOPMENT.md and/or .lad for that to be auto-picked up

Suggested change
m = re.match(r'synonym:\s+"(.+?)"\s+(EXACT|RELATED|NARROW|BROAD)', line)
if m:
if (m := re.match(r'synonym:\s+"(.+?)"\s+(EXACT|RELATED|NARROW|BROAD)', line)):


def main() -> None: # pragma: no cover
url = "http://purl.obolibrary.org/obo/uberon.obo"
print(f"Downloading {url} ...")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

especially when moved into service command - use logging to gain logging control/archival etc

Comment thread dandi/data/uberon_brain_structures.json Resolved
Comment thread pyproject.toml Resolved
Comment thread .pre-commit-config.yaml Resolved
Comment thread dandi/metadata/brain_areas.py Resolved
- Move UBERON generator to service-scripts CLI subcommand
- Use logging instead of print in generator
- Use walrus operators in generator and brain_areas.py
- Pretty-print UBERON JSON (indent=1) for better diffs
- Use glob patterns for codespell/pre-commit excludes
- Exclude *_structures.json from large-file check

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@bendichter

Copy link
Copy Markdown
Member Author

Addressed all review feedback in e40872c:

  1. Service-scripts CLI: UBERON generator is now a dandi service-scripts generate-uberon-structures subcommand (Allen CCF can follow in a separate commit on the parent PR).

  2. Logging: Replaced all print() calls with lgr.info().

  3. Walrus operators: Applied in both the generator (if m := re.match(...)) and brain_areas.py (if (s := _lookup_in_dicts(...)) is not None:).

  4. Pretty-printed JSON: uberon_brain_structures.json now uses indent=1 for human readability and better diffs. Excluded *_structures.json from the large-file check since the indented file is ~700KB.

  5. Glob patterns for codespell/pre-commit: Both pyproject.toml (*_structures.json) and .pre-commit-config.yaml (dandi/data/.*_structures\.json) now use globs so future structure files are automatically covered.

Not yet addressed: weekly CI smoke test for the generator — happy to add a pytest marker for that if you'd like it in this PR.

@yarikoptic

Copy link
Copy Markdown
Member

weekly CI smoke test for the generator — happy to add a pytest marker for that if you'd like it in this PR.

develop the test itself here, and mark with a new (to be added) data_regeneration marker. We will look into adding a dedicated CI (and moving out from the main loop) later for it. also mark with needing network.

Adds a regression test that re-downloads the UBERON OBO file and
verifies the generated output matches the committed JSON.  Marked
with data_regeneration and skipif_no_network for scheduled CI runs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@bendichter

Copy link
Copy Markdown
Member Author

Added in 69a328e:

  • Regression test in dandi/tests/test_data_regeneration.py: re-downloads the UBERON OBO file, runs the generator to a temp path, and asserts the output matches the committed JSON byte-for-byte. This catches both code regressions and upstream UBERON changes.
  • Marked with @pytest.mark.data_regeneration (new marker, registered in pytest_plugin.py) and @mark.skipif_no_network.
  • Run with pytest -m data_regeneration for a scheduled CI job.

@satra

satra commented Apr 2, 2026

Copy link
Copy Markdown
Member

@bendichter

Copy link
Copy Markdown
Member Author

thanks for the pointer, @satra. I'm looking at the URLs of the individual terms inside this owl file, and the ones I tried did not resolve to a term page, e.g. https://purl.brain-bican.org/ontology/HOMBA_12230 and https://purl.brain-bican.org/ontology/HOMBA_12233. Is that intentional?

@satra

satra commented Apr 2, 2026

Copy link
Copy Markdown
Member

url and uri are two different things. an owl doesn't have to resolve to a page. i believe they will fix that though soonish (in a couple of weeks).

@yarikoptic

Copy link
Copy Markdown
Member

@bendichter @satra -- please clarify what exactly yet to be done (by @bendichter and his agents) or should I re-review this?

@bendichter

Copy link
Copy Markdown
Member Author

See new design doc: dandi/dandi-archive#2768, an attempt to understand and plan how we can use all these ontologies together

@yarikoptic

yarikoptic commented Apr 6, 2026 •

Copy link
Copy Markdown
Member

so, this PR is postponed until larger design is finalized? (that PR design is too large to fit into my limited token "context" ATM ;-) )

@yarikoptic

Copy link
Copy Markdown
Member

@bendichter ping on above question since I found no worthy complaining comments of mine, and overall see it as improvement, and green (we might want to retest after updating) so would not mind to proceed I think.

bendichter and others added 2 commits April 30, 2026 14:24
Byte-level comparison against the committed snapshot broke on every
upstream UBERON release. Verify the generator runs and produces
well-formed records instead.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Base automatically changed from add-brain-area-anatomy to master November 2, 2026 21:14

@yarikoptic-gitmate yarikoptic-gitmate left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The feature itself is fine. Most of the bulk comes from code and data that nothing uses yet: the synonym-scope machinery, and the non-EXACT synonyms in the bundled JSON. I prototyped the trimmed version on top of this branch (not pushed):

  • brain_areas.py goes from +206 lines to +43/−18;
  • the JSON goes from 52,482 lines / 708 KB to 2,410 lines / 333 KB;
  • all 61 brain-area and anatomy metadata tests still pass.

1. Drop max_synonym_scope. Nothing but tests passes anything other than "EXACT": _extract_brain_anatomy() is called without it, and nothing exposes it to users. Dropping it also removes _SCOPE_ORDER, _SCOPE_LETTER, _scopes_up_to(), the "_NAME" sentinel and the per-scope _build_uberon_lookup_dicts(). (Its lru_cache(maxsize=4) is also smaller than its 5 possible keys.) The parameter can come back with a caller that needs it.

2. One case-insensitive dict. In the bundled data, no two terms share a name or an EXACT synonym, even ignoring case. So the exact-case and lower-case dicts never disagree, and the lookup collapses to:

@lru_cache(maxsize=1)
def _uberon_lookup() -> dict[str, dict[str, Any]]:
    """Map lower-cased UBERON term names, then EXACT synonyms, to their terms."""
    data_path = (
        Path(__file__).resolve().parent.parent / "data" / "uberon_brain_structures.json"
    )
    with open(data_path) as f:
        structures: list[dict[str, Any]] = json.load(f)
    lookup: dict[str, dict[str, Any]] = {}
    for s in structures:
        lookup.setdefault(s["name"].lower(), s)
    for s in structures:
        for synonym in s.get("synonyms", []):
            lookup.setdefault(synonym.lower(), s)
    return lookup


def match_location_to_uberon(token: str) -> models.Anatomy | None:
    """Match a location token to an UBERON term name or EXACT synonym, ignoring case."""
    if (s := _uberon_lookup().get(token.strip().lower())) is None:
        return None
    return models.Anatomy(identifier=UBERON_URI_TEMPLATE.format(s["id"]), name=s["name"])

3. One locations_to_anatomy() instead of three copies of the same loop. locations_to_uberon_anatomy() and locations_to_mouse_anatomy() repeat the parse/match/dedupe loop of locations_to_ccf_mouse_anatomy(). After this PR, only tests still use the latter. Generalize it to take the matchers to try, in order:

def locations_to_anatomy(
    locations: list[str],
    matchers: tuple[Callable[[str], models.Anatomy | None], ...] = (match_location_to_allen,),
) -> list[models.Anatomy]:
    seen_ids: set[str] = set()
    results: list[models.Anatomy] = []
    for loc in locations:
        for token in _parse_location_string(loc):
            for match in matchers:
                if (anatomy := match(token)) is not None:
                    if (id_str := str(anatomy.identifier)) not in seen_ids:
                        seen_ids.add(id_str)
                        results.append(anatomy)
                    break
    return results

_extract_brain_anatomy() would then pass (match_location_to_allen, match_location_to_uberon) for mouse and (match_location_to_uberon,) otherwise.

4. Bundle only what is used, one term per line. The generator could keep only EXACT synonyms and write one record per line, e.g. {"id": "0000955", "name": "brain", "synonyms": [...]}. Diffs would still be per term, which was the point of indent=1. The file would drop from 708 KB to 333 KB. Being under 500 KB, it would no longer need the check-added-large-files exclusion. The other 4,230 of the 9,717 synonyms (RELATED, BROAD, NARROW) are never matched.

5. test_generate_uberon_structures runs in every CI job. run-tests.yml selects with -m "not obolibrary", which does not exclude the data_regeneration marker; pytest --collect-only -m "not obolibrary" collects this test. So every networked job downloads the 22.5 MB uberon.obo and parses it. Until the dedicated CI exists, either deselect it there (-m "not obolibrary and not data_regeneration") or run it only with the existing --scheduled option, so the daily run covers it.

Not a blocker: a bundled copy of a remote file, plus a regeneration script, is now a recurring pattern. A shared mechanism for it is proposed in dandi/dandi-schema#448.


Generated by Claude Code

yarikoptic-gitmate pushed a commit that referenced this pull request Nov 10, 2026
- Replace tools/check-duplication.sh (npx jscpd 5.3.3) with jscpd's own
  pre-commit hook at v5.4.3, which installs jscpd's PyPI wheel and so
  needs no Node.js; `tox -e duplication` (with --verbose, so that CI logs
  show the numbers) and CI run it via pre-commit.  Its args scan all of
  dandi/ and tools/ rather than the staged files, so it means the same
  everywhere.
- Fail also on a clone missing from the new .jscpd-baseline.json, the
  fingerprints of the 44 clones accepted so far.  The repo-wide threshold
  cannot catch a change adding a few clones: e.g., #1825
  adds three copies of a loop in brain_areas.py, which raise duplication
  from 1.43% to just 1.51%, well under 2%; the baseline flags all three.
  A manual-stage `jscpd-update-baseline` hook accepts clones.
  A committed baseline rather than `--baseline-from-ref origin/master`,
  as this branch's own refactors would then count as 13 new clones
  (jscpd fingerprints a clone by its content), and the result would
  depend on a fresh local origin/master, which a fork may lack.
- Ignore dandi/data/*.json: bundled data is not code, and a large file
  such as #1825's 52,000-line UBERON JSON dilutes the percentage.
- Document all this in DEVELOPMENT.md (whose hook list also lacked
  reuse), and add `duplication` to the linters in the contributing guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw
CodyCBakerPhD added a commit that referenced this pull request Nov 12, 2026
* Add code duplication analysis to the dev workflow

Wire jscpd (pinned to 5.3.3) in as a `tox -e duplication` env, backed by
tools/check-duplication.sh. Config lives in .jscpd.json, scanning dandi/
and tools/ with sensible ignores for vendored/generated files, test
fixture data, and build artifacts.

Threshold is temporarily set to 5% (above the measured 4.38% baseline)
so this lands green; a follow-up commit tightens it after mitigating
the duplication found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Run duplication check in CI

Add .github/workflows/duplication.yml, mirroring the existing
typing.yml/lint.yml pattern: a dedicated job that installs tox and
runs `tox -e duplication`.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate _bids_validate docstring by referencing bids_validate

The private _bids_validate() implementation repeated the full
Parameters/Returns docstring of its public wrapper bids_validate().
Since _bids_validate is internal-only, point its docstring at the
public function instead of duplicating the parameter docs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate flatten_meta_to_pyout_v1 docstring

Its docstring repeated flatten_meta_to_pyout()'s prose almost
verbatim; point it at the sibling function and describe only how
it differs (recursive flattening of nested dicts).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate RemoteDandiset asset-listing and raw-asset-upload methods

get_assets, get_assets_with_path_prefix, and get_assets_by_glob shared
the same paginate/except/yield body, differing only in the request
params; extract it into _iter_version_assets().

upload_raw_asset and iter_upload_raw_asset shared the same
dandi_file()/isinstance check for resolving a LocalAsset; extract it
into _local_asset_file().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate asset download streaming and set_raw_metadata

BaseRemoteAsset.get_download_file_iter and RemoteZarrEntry.get_download_file_iter
shared the same GET-with-Range-header/raise_for_status logic; extract it
into module-level _get_download_response().

RemoteBlobAsset.set_raw_metadata and RemoteZarrAsset.set_raw_metadata
were identical apart from the blob_id/zarr_id key; extract the shared
PUT + in-place field update into RemoteAsset._put_raw_metadata().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate LocalAsset.upload/iter_upload docstrings and BIDS asset methods

LocalAsset.upload, the abstract LocalAsset.iter_upload, LocalFileAsset's
concrete override, ZarrAsset's override, and the deprecated
DandiAPIClient.iter_upload_raw_asset all repeated the same
Parameters/Returns prose. Keep the full docs on upload() (the one
method every subclass inherits unchanged) and have the others
reference it, keeping only what's actually specific to each override.

NWBBIDSAsset.get_validation_errors and ZarrBIDSAsset.get_validation_errors
had identical bodies apart from which sibling class's method they
combined with BIDSAsset's; extract _bids_combined_validation_errors().
ZarrBIDSAsset.get_metadata duplicated BIDSAsset.get_metadata's body
plus one extra line; have it delegate instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate path-like helpers between BasePath and RemoteZarrEntry

RemoteZarrEntry deliberately stopped inheriting from
`misctypes.BasePath` (0.48.0), but its suffix/suffixes/stem/match
implementations were copy-pasted from BasePath verbatim. Extract the
underlying logic into module-level helpers in misctypes.py
(_path_suffix, _path_suffixes, _path_stem, _match_parts, _split_path)
that both classes delegate to, without re-establishing the inheritance
that was intentionally removed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate MultiAssetURL.get_assets overrides

AssetPathPrefixURL, AssetFolderURL, and AssetGlobURL's get_assets()
shared the same "look up the dandiset, iterate assets, track whether
any were found, raise NotFoundError if strict and none were" body,
differing only in the query method called and the error message.
Extract it into _iter_multi_assets().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate Mover/LocalizedMover abstract-method docstrings

calculate_moves, calculate_moves_by_regex, get_assets, get_path, and
move are declared abstractly on Mover/LocalizedMover with a full
docstring, then re-implemented with the same docstring copy-pasted
verbatim in LocalMover, RemoteMover, and (for the calculate_moves*
pair) LocalRemoteMover. Keep the docs on the abstract declarations and
have every concrete override point back at them instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate NWB fixture builders in tests/fixtures.py

simple4_nwb/simple5_nwb built near-identical NWBFile+TimeSeries+Subject
structures differing only in the TimeSeries unit and subject_id;
extract _make_ambiguous_orientation_nwb().

organized_nwb_dir/organized_nwb_dir3 both ran `organize -f copy` on a
given NWB fixture into a fresh dandiset dir; extract _organize_copy().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_move.py setup boilerplate

Every test function repeated the same three lines (snapshot starting
assets, monkeypatch.chdir to some directory, monkeypatch the API key
env var). Extract _setup_move() and call it from all 34 test
functions; the chdir target still varies per test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Parametrize near-duplicate test_move.py scenarios

- Merge test_move_skip/test_move_overwrite into test_move_existing,
  parametrized on the existing= value and expected remapping.
- Merge test_move_pyout/test_move_pyout_dry_run into one test
  parametrized on dry_run and the expected remapping.
- Merge test_move_file_slash_src/test_move_file_slash_dest into
  test_move_file_slash, parametrized on which path (src or dest) gets
  the trailing slash.

Remaining near-identical pairs in this file (dandiset-by-path vs
dandiset-by-URL addressing, and the AssetMismatchError scenarios under
work_on=BOTH) test genuinely different setups/expected messages; merging
them would obscure what each case actually asserts, so they're left as
intrinsic test duplication.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_download.py setup/assertion boilerplate

- test_download_sync/test_download_sync_do: extract the shared
  "delete file.txt, move dandiset dir into tmp_path, patch
  abbrev_prompt" setup into _prep_sync_download().
- test_download_sync_folder/test_download_sync_glob: extract the
  shared "delete two assets, patch abbrev_prompt" setup into
  _prep_sync_delete_two_assets().
- test_download_glob_option/test_download_glob_url: extract the
  shared post-download assertions into _assert_glob_download().
- test__check_attempts_and_sleep_retries: two inline scenarios only
  differed in the Retry-After/now timestamps and whether a sleep was
  expected; factor into a local check_retry_after() helper.

The remaining duplication in this file is a large existing
@pytest.mark.parametrize data table for progress-event aggregation
(intrinsic to the parametrize pattern itself, not code duplication)
plus one small residual signature/call overlap between two tests that
exercise genuinely different URL addressing schemes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_dandiapi.py assertion boilerplate

- test_get_content_url/test_get_content_url_regex: extract the shared
  "stream the content URL to asset.nwb" tail into _fetch_content().
- test_get_dandiset_lazy/non_lazy/no_version_id/published/
  published_no_version_id/published_draft/published_other_version:
  extract the shared post-fetch field assertions (version_id, created,
  modified, version, most_recent_published_version, draft_version,
  contact_person -- including dropping an accidentally
  double-asserted `isinstance(dandiset.created, datetime)` line) into
  _assert_dandiset_fields().

The remaining duplication is mock-setup scaffolding across the
test_authenticate_* variants, each exercising a genuinely different
keyring/input code path, plus small residual call-site overlap between
tests whose only real content is a differing (version_id,
most_recent_published) pair.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate "no such asset/dandiset" tests in test_dandiarchive.py

The 10 test_get_nonexistent_* tests all parsed a URL, asserted
get_assets() returns empty, and asserted strict=True raises a
NotFoundError with a specific message; extract this into
_assert_no_assets(). Also factor the repeated "No such Dandiset:
'999999'..." message into NO_SUCH_DANDISET_999999.

test_utils.py: test_get_instance_dandi_with_api and
test_get_instance_url mocked an identical server-info JSON payload;
factor it into the SERVER_INFO constant.

The remaining cross-file overlap between test_dandiarchive.py and
test_utils.py is two mock server-info payloads that happen to share
structural JSON keys but carry different actual data (different
version/services) -- coincidental, not real duplication.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_metadata.py session-duration and nwb2asset tests

- The 5 test_session_duration_with_* tests shared the same
  "session_start_time/session_end_time present, duration within 1s of
  expected" check; extract _assert_session_duration(). Two of them
  additionally shared the same "Session activity has matching
  start/end dates" check; extract _assert_session_activity_dates().
- test_nwb2asset and test_nwb2asset_remote_asset asserted against the
  same large BareAsset.model_construct(...) golden object, differing
  only in contentSize/digest/path/blobDateModified/strain; extract
  _expected_simple2_asset().

The remaining duplication is the metadata2asset @pytest.mark.parametrize
data table (literal test-fixture dicts covering distinct corner cases,
explicitly labeled as such in a comment) -- intrinsic to the
parametrize pattern, not code duplication.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate cli/tests/test_download.py mock-call assertions

Every test asserted dandi.download.download() was called with the
same 10-kwarg set (existing/format/jobs/.../path_type), varying only
one or two values. Factor the defaults into DEFAULT_DOWNLOAD_KWARGS
and assert with `**{**DEFAULT_DOWNLOAD_KWARGS, "some_key": override}`.

test_download_gui_instance_in_dandiset and
test_download_api_instance_in_dandiset additionally shared their
whole setup/invoke/assert body apart from the instance name and
expected URL; extract _invoke_in_dandiset().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_delete.py setup/assertion boilerplate

Most tests repeated "monkeypatch the API key env var, grab instance_id,
spy on RESTFullAPIClient.delete"; extract _setup_delete_spy(), taking
either a text_dandiset.api or local_dandi_api (both DandiAPI
instances). The skip_missing variants additionally repeated a
"download and compare remaining asset paths" tail; extract
_assert_remaining_assets().

The 3 remaining pairs (single-path vs whole-dandiset delete;
path-confirm vs dandiset-confirm; missing-asset vs missing-folder) only
share the mechanical call shape around genuinely different scenarios
and assertions, so they're left as intrinsic duplication.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate expected-asset literals in test_files.py

test_find_dandi_files asserted three overlapping find_dandi_files()
result lists that repeated the same VideoAsset/ImageAsset/ZarrAsset/
NWBAsset/DandisetMetadataFile literals; factor them into local
variables reused across the three assertions.

test_find_dandi_files_with_bids similarly repeated each BIDS asset
literal between the top-level files list and the per-dataset
dataset_files checks; factor into local variables (bidsignore,
bids1_dd, bids1_file, ..., bids2_subdd). Equality is value-based
(dataclasses), so reusing the same instance across multiple
assertions is safe.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_keyring.py "no keyring" mock setup

6 tests repeated "delenv PYTHON_KEYRING_BACKEND, patch
dandi.keyring_utils.get_keyring" with only the returned backend
instance varying; extract _mock_no_keyring().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate test_upload.py zarr/dandidownload test bodies

- test_upload_different_zarr/test_upload_loose_zarr shared the
  "replace the local zarr, re-upload, verify same zarr id, download
  and compare" tail; extract _replace_zarr_and_check().
- test_upload_rejects_dandidownload_paths's "Test 1" sub-case and
  test_upload_rejects_dandidownload_nwb_file both built an NWB file
  and expected upload() to reject it with the same message; extract
  _assert_upload_rejects_dandidownload().
- test_upload_zarr_patch_mode_no_delete/test_upload_zarr_full_mode_delete
  shared the "find and remove a local zarr data file" setup; extract
  _remove_a_zarr_data_file().

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Deduplicate sample ValidationResult issues in test_cmd_validate.py

test_render_text_grouping and test_render_text_multilevel_grouping
built the same two-issue ValidationResult list; extract
_sample_validation_issues() and have the multilevel test append its
extra ERROR-severity issue on top.

The remaining test_cmd_validate.py/test_core.py overlap
(test_validate_bids_error vs test_validate_bids_errors) exercises the
same BIDS error-example scenario through two different entry points
(the CLI command vs the underlying validate() function) with different
assertions; left as intrinsic duplication across module/layer
boundaries rather than merging two different-layer tests together.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Tighten duplication threshold to 2% after cleanup

Baseline was 4.38% (133 clones) across dandi/ + tools/. After the
mitigation commits on this branch, duplication is down to 1.46%
(42 clones), all now residual and documented:

- Intrinsic @pytest.mark.parametrize data tables (test_download.py's
  progress-event table, test_metadata.py's metadata2asset corner
  cases) -- literal fixture data, not code duplication.
- Intentional parallel-layer test coverage (public bids_validate() vs
  private _bids_validate(); CLI `validate` command vs core validate()
  function; single-path vs whole-dandiset delete scenarios) where
  merging would conflate independent test layers.
- Python-level unavoidable boilerplate (method-override signatures
  repeating parameter lists; Sphinx `.. versionchanged::` directives
  that must appear on each documented method).
- One deliberately-decoupled duck-typing case (RemoteZarrEntry
  explicitly stopped inheriting misctypes.BasePath in 0.48.0; the
  residual is just per-class property-delegation boilerplate).

Threshold set to 2% (just above the current 1.46%) rather than 0% to
leave headroom for this residual without treating it as a bug.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Run jscpd as a pre-commit hook gated on a committed clone baseline

- Replace tools/check-duplication.sh (npx jscpd 5.3.3) with jscpd's own
  pre-commit hook at v5.4.3, which installs jscpd's PyPI wheel and so
  needs no Node.js; `tox -e duplication` (with --verbose, so that CI logs
  show the numbers) and CI run it via pre-commit.  Its args scan all of
  dandi/ and tools/ rather than the staged files, so it means the same
  everywhere.
- Fail also on a clone missing from the new .jscpd-baseline.json, the
  fingerprints of the 44 clones accepted so far.  The repo-wide threshold
  cannot catch a change adding a few clones: e.g., #1825
  adds three copies of a loop in brain_areas.py, which raise duplication
  from 1.43% to just 1.51%, well under 2%; the baseline flags all three.
  A manual-stage `jscpd-update-baseline` hook accepts clones.
  A committed baseline rather than `--baseline-from-ref origin/master`,
  as this branch's own refactors would then count as 13 new clones
  (jscpd fingerprints a clone by its content), and the result would
  depend on a fresh local origin/master, which a fork may lack.
- Ignore dandi/data/*.json: bundled data is not code, and a large file
  such as #1825's 52,000-line UBERON JSON dilutes the percentage.
- Document all this in DEVELOPMENT.md (whose hook list also lacked
  reuse), and add `duplication` to the linters in the contributing guide.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Test the path helpers that BasePath and RemoteZarrEntry now share

_split_path, _match_parts, _path_suffix, _path_suffixes and _path_stem
moved out of BasePath and RemoteZarrEntry into module-level helpers in
dandi/misctypes.py, where Codecov showed them as untested, and project
coverage 0.03% below master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Make all pre-commit hooks pass on all files, for pre-commit.ci

pre-commit.ci runs every hook on every file, while `tox -e lint` and
pre-commit at commit time cover only some.  Fix what that turned up:
whitespace and end-of-file newlines, black on test_helptext.py, and an
over-long line in a docs example.  Exclude CHANGELOG.md, which `auto`
generates from pull request descriptions, from the whitespace hooks and
codespell (it quotes "TE" from an old pull request title).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Run the duplication check through pre-commit.ci instead of a workflow

pre-commit.ci is now enabled for the repository and runs all hooks,
including jscpd, on every pull request, so the dedicated
duplication.yml workflow is redundant.  `tox -e duplication` stays for
running the check locally.  Add the pre-commit.ci badge to README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Bump the black hook to 22.12.0, which runs on Python 3.14

pre-commit.ci builds hook environments with Python 3.14, where black
22.3.0 crashes formatting more than one file ("There is no current event
loop").  22.12.0 is the newest release with the same style: it leaves all
Python files unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Keep master's docstrings, and do not count docstrings as duplication

As agreed in review, deduplicating docstrings is left to a separate PR:
restore master's docstrings on the 11 overriding methods that this branch
had reduced to "See `Base.method`." redirects (10 in dandi/move.py,
LocalFileAsset.iter_upload in dandi/files/bases.py).  The published API
docs again show LocalFileAsset.iter_upload's full docstring.

So that such repeated docstrings are not flagged as clones, exclude
docstrings from jscpd with an `ignorePattern` matching a triple-quoted
string right after a line ending in `:`.  In dandi/ and tools/ it matches
all 718 function and class docstrings and nothing else.

With the restored docstrings, the baseline now holds 40 clones (1.33% of
lines; master, measured the same way: 113 clones, 3.59%).  Its 4 changed
fingerprints:
- dandiapi.py 203-216 / 911-924: an accepted clone, less its docstring;
- dandiarchive.py 251-258 / 372-383 and 421-437 / 536-548: the
  `get_assets()` signature and `_maybe_strict` body that several URL
  classes share, so far hidden by their differing docstrings;
- tests/test_upload.py 732-740 / 785-792: likewise, between two tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Restore master's docstrings on the 5 remaining rewritten functions

As agreed in review, this branch leaves docstrings alone; deduplicating
them is for a later PR.  79da79b restored the 11 "See `X`" redirects;
these 5 docstrings had been shortened to refer to another function:

- bids_validator_deno._validator._bids_validate
- cli.cmd_ls.flatten_meta_to_pyout_v1
- dandiapi.RemoteDandiset.iter_upload_raw_asset
- files.bases.LocalAsset.iter_upload
- files.zarr.ZarrAsset.iter_upload

No function or class that exists on master now has a docstring that
differs from master's.  jscpd ignores docstrings, so the baseline is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Update a remote asset's fields in BaseRemoteAsset, which defines __eq__

CodeQL flagged RemoteAsset with py/missing-equals ("`__eq__` not
overridden when adding attributes") once #1944 moved the code that
refreshes an asset after a metadata update from RemoteBlobAsset and
RemoteZarrAsset into RemoteAsset._put_raw_metadata().  The query only
checks a class whose direct base defines __eq__: BaseRemoteAsset does,
while the direct bases of RemoteBlobAsset and RemoteZarrAsset do not,
so master was not flagged.  The attributes are not new either: they are
BaseRemoteAsset's fields, which its __eq__ compares, and its private
`_metadata`, which __eq__ leaves out on purpose.

Move the assignments into a BaseRemoteAsset._update_from_data() method,
next to the fields and __eq__ they belong with, and call it from
_put_raw_metadata().  No change in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

* Keep the get_assets*() methods generator functions, as on master

Factoring out _iter_version_assets() and _iter_multi_assets() turned
RemoteDandiset.get_assets(), .get_assets_with_path_prefix() and
.get_assets_by_glob(), and the get_assets() of AssetPathPrefixURL,
AssetFolderURL and AssetGlobURL, into plain functions that return a
generator.  Their arguments were therefore processed at call time
rather than on first iteration: e.g. get_assets_with_path_prefix(None)
raised TypeError immediately instead of when iterated, and
inspect.isgeneratorfunction() returned False for all six.

`yield from` the helpers instead of returning them, so these methods
behave exactly as on master again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx7zsNtBdYZ6YyZCPgkaDw

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Cody Baker <51133164+CodyCBakerPhD@users.noreply.github.com>
@yarikoptic

Copy link
Copy Markdown
Member

@bendichter I am moving this to draft as seems fell of your radar and my review was not addressed and a tiny conflict to handle

@yarikoptic
yarikoptic marked this pull request as draft November 23, 2026 12:16
@satra

satra commented Nov 23, 2026

Copy link
Copy Markdown
Member

some process is already doing this at the level of dandiset metadata with homba ontology (which was also recently published). something should coordinate between cli and that so we don't get conflicting or unaligned approaches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request minor Increment the minor version when merged

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants