From Pydantic to LinkML
without changing the schema

migrating the DANDI archive metadata models

Yaroslav O. Halchenko
@yarikoptic @yarikoptic@fosstodon.org
ORCID 0000-0003-3456-2493
for the work of Isaac To, John Lee, and the DANDI team
Center for Open Neuroscience
Department of Psychological and Brain Sciences
Center for Cognitive Neuroscience
Dartmouth College, New Hampshire, USA
Virtual LinkML Symposium 2026 — Session 5: Tools, generators & workflows II — December 3rd, 2026
Live slides/Sources: https://datasets.datalad.org/centerforopenneuroscience/talks/2026-linkml-dandi-schema.html
Archived (PDF + offline slides) on Zenodo: doi:10.5281/zenodo.24789455

In the next 10 minutes

  1. DANDI: an archive you can use
  2. One Pydantic model — many consumers, tangled
  3. LinkML: one declarative source, generated everything
  4. Your feedback: prior art? can LinkML say what we need?
  5. Duplication is evil!

DANDI — BRAIN Initiative archive for neurophysiology

What is in DANDI (stats.dandiarchive.org, 2026-12-02)

How much it is used (usage.dandiarchive.org, 2026-12-02)

One more "Standard": DANDI schema (2021 view)

dandi-schema

  1. Describes Dandisets and Assets
  2. Harmonizes across standards
  3. Serializes to JSON Schema + JSON-LD
  4. Validates
  5. Drives the metadata editor
  6. Presents landing pages
  7. Links data: JSON-LD, DOIs

Describes: Pydantic models in models.py


# https://github.com/dandi/dandi-schema/blob/0.14.0/dandischema/models.py#L1702-L1720
class Dandiset(CommonModel):
    ...
    name: str = Field(
        title="Dandiset title",
        description="A title associated with the Dandiset.",
        max_length=150,
        json_schema_extra={"nskey": "schema"},
    )
    description: str = Field(
        description="A description of the Dandiset",
        max_length=10000,
        json_schema_extra={"nskey": "schema"},
    )
    contributor: List[
        Annotated[Union[Person, Organization], Field(discriminator="schemaKey")]
    ] = Field(
        title="Dandiset contributors",
        description="People or Organizations that have contributed to this Dandiset.",
        json_schema_extra={"nskey": "schema"},
        min_length=1,
    )
	
  • ~2,100 lines: Dandiset, Asset, Person, Organization, Activity, ... — contributors, funding, license, species, approaches, techniques, provenance
  • nskey, title, readOnly: hints for JSON-LD and the web form

One source of truth

Harmonizes: one record across standards

%%{init: {'theme': 'base', 'flowchart': {'htmlLabels': false}, 'themeVariables': {'fontSize': '22px', 'primaryColor': '#fdf6e3', 'lineColor': '#555'}}}%%
flowchart LR
    NWB["NWB files"]
    BIDS["BIDS datasets<br/>+ HED"]
    Z["OME-Zarr"]
    X["dandi-cli<br/>extract + validate"]
    A["Asset records<br/>automatic extracts"]
    R["one validation report<br/>NWB Inspector, BIDS,<br/>HED, OME-Zarr, ..."]
    H["humans + AI<br/>in the Meditor"]
    D["Dandiset record<br/>curated"]
    S["dandi-schema<br/>models"]
    NWB --> X
    BIDS --> X
    Z --> X
    X --> A
    X --> R
    H --> D
    A --> S
    D --> S
    click X href "https://github.com/dandi/dandi-cli/tree/0.84.0/dandi/validate" _blank
    click A href "https://github.com/dandi/dandi-cli/blob/0.84.0/dandi/metadata/nwb.py" _blank
    click S href "https://github.com/dandi/dandi-schema/blob/0.14.0/dandischema/models.py" _blank
    style S fill:#f7dfd3,stroke:#c0392b,stroke-width:2px
	
  • Assets: extracted automatically from the files in their standards (NWB, BIDS)
  • Dandisets: edited by humans (and now AI) in the Meditor
  • The schema validates only those records; the files go through their own validators, whose results we harmonize into one report

Serializes: JSON Schema + JSON-LD context per release

  • dandi/schema: per schema version, dandiset.json, asset.json, published-*.json, context.json
  • published by CI from models.py (publish_model_schemata())
  • JSON-LD context maps to schema.org, PROV, DataCite, SPDX, ORCID, ROR, PATO, RRID, ...
  • schema version (0.8.0) ≠ library version (0.14.0)

Validates: validate() — on upload and before publish

  • dandi-cli validates asset records before uploading
  • the archive backend validates every record, with Pydantic and JSON Schema (json_validation=True)
  • invalid → Publish is blocked; errors shown next to the Dandiset

Drives the Meditor: a form generated from the JSON Schema

  • vjsf renders the form; tabs, titles and read-only fields come from the schema
  • note the “BETA FEATURE: TRY AI ASSISTED METADATA EDITING”

Presents: Dandiset landing pages

The model “flows” through the whole system

%%{init: {'theme': 'base', 'flowchart': {'htmlLabels': false}, 'themeVariables': {'fontSize': '22px', 'primaryColor': '#fdf6e3', 'lineColor': '#555'}}}%%
flowchart TB
    P["models.py<br/>Pydantic models<br/>+ custom validators"]
    J["dandi/schema<br/>JSON Schema per release<br/>+ JSON-LD context"]
    CLI["dandi-cli<br/>extract, validate, upload"]
    V["dandischema.validate()<br/>Pydantic and/or JSON Schema"]
    BE["archive backend / API<br/>Celery validation → Postgres"]
    ME["Meditor<br/>vjsf web form"]
    DLP["Dataset landing page"]
    LD["JSON-LD on S3,<br/>DataCite DOIs"]
    PUB(["Publish<br/>(blocked if invalid)"])

    P -->|"GitHub CI per release"| J
    P --> CLI
    P --> V
    J -->|"any version"| V
    V --> BE
    CLI -->|"asset metadata"| BE
    J -->|"generates form"| ME
    ME -->|"user edits"| BE
    BE --> DLP
    BE --> LD
    BE --> PUB

    click P href "https://github.com/dandi/dandi-schema/blob/0.14.0/dandischema/models.py" _blank
    click J href "https://github.com/dandi/schema/tree/master/releases" _blank
    click CLI href "https://github.com/dandi/dandi-cli/tree/0.84.0" _blank
    click V href "https://github.com/dandi/dandi-schema/blob/0.14.0/dandischema/metadata.py#L241" _blank
    click BE href "https://github.com/dandi/dandi-archive/blob/v1.2.6/dandiapi/api/services/metadata/__init__.py" _blank
    click ME href "https://github.com/dandi/dandi-archive/tree/v1.2.6/web/src/components/Meditor" _blank
    click DLP href "https://github.com/dandi/dandi-archive/tree/v1.2.6/web/src/components/DLP" _blank
    click LD href "https://dandiarchive.s3.us-east-2.amazonaws.com/dandisets/000003/0.261122.2143/dandiset.jsonld" _blank

    style P fill:#f7dfd3,stroke:#c0392b,stroke-width:2px
    style J fill:#eee8f7,stroke:#6a4b8a
	

boxes are links; adapted from docs.dandiarchive.org → Integrate External Services

Tied together — at times too much

  • Python-only constraints: custom field_validator/model_validators never reach JSON Schema → Meditor happily accepts what the backend then rejects (and blocks publishing)

# https://github.com/dandi/dandi-schema/blob/0.14.0/dandischema/models.py#L1653-L1664
    @field_validator("contributor")
    @classmethod
    def contributor_musthave_contact(
        cls, values: List[Union[Person, Organization]]
    ) -> List[Union[Person, Organization]]:
        contacts = []
        for val in values:
            if val.roleName and RoleType.ContactPerson in val.roleName:
                contacts.append(val)
        if len(contacts) == 0:
            raise ValueError("At least one contributor must have role ContactPerson")
        return values
	

Migration to LinkML: why bother?

  • One declarative source of truth, language-neutral — Pydantic, JSON Schema, JSON-LD context, SHACL/OWL, docs all generated
  • Constraints as data, not code (pattern, required, rules, ...) → the same checks everywhere: CLI, backend, web form
  • Versioned schema artifacts → validate against a specific version, compare versions, tooling for migrations
  • Shared language with neighbors: BICAN, AIND, concepts.datalad.org, ... and the LinkML community

Ground rule: change the representation, not the schema

Done when all three hold (playbook):

  1. Behavioral parity: what today's Pydantic models accept/reject, LinkML-derived validators accept/reject the same way
  2. Generated Pydantic is a drop-in for dandischema, dandi-cli, dandi-archive
  3. Generated JSON Schema validates instances and still drives the web UI (Meditor)

Evidence beyond unit tests: validate the metadata of all archived Dandisets with both (dashboard, Claude skill dandi-linkml-validation-report)

Only then flip: models.yaml becomes the source, models.py is generated.

While others were creating new cool tools,
I was into fruits

LinkML workshop, Berkeley, February 2024

pydantic2linkml: started at that workshop


pydantic2linkml -M dandischema/models_merge.yaml -O dandischema/models_overlay.yaml dandischema.models \
  | sed ... | tools/linkml_conversion_tools/sanitize-yaml > dandischema/models.yaml
	
  • walks the pydantic-core schema of each model and field
  • what it cannot express, it leaves as notes: right in models.yaml — an inventory of the gaps
  • -M/-O: what is not (yet) in Pydantic — prefixes, designates_type, range overrides
  • sanitize-yaml: drop notes we triaged as acceptable
  • gen-pydantic + one Jinja override: enum names without COLON munging

# models_merge.yaml
slots:
  schemaKey:
    designates_type: true
    required: true
classes:
  BareAsset:
    slot_usage:
      wasGeneratedBy:
        range: Any
  Dandiset:
    slot_usage:
      wasGeneratedBy:
        range: Project
	  
Isaac To John Lee Yaroslav O. Halchenko

Setup: a regenerable conversion, not a one-time port

%%{init: {'theme': 'base', 'flowchart': {'htmlLabels': false}, 'themeVariables': {'fontSize': '22px', 'primaryColor': '#fdf6e3', 'lineColor': '#555'}}}%%
flowchart LR
    M["models.py<br/>Pydantic, from master"]
    Q["patch-queue<br/>branches"]
    MG["models_merge.yaml<br/>models_overlay.yaml"]
    P2L["pydantic2linkml<br/>+ sanitize-yaml"]
    Y["models.yaml<br/>LinkML + notes"]
    LK["LinkML<br/>generators"]
    GP["gen-pydantic<br/>+ enum template"]
    GJ["gen-json-schema"]
    CMP(["analyze:<br/>tests, schema diff,<br/>all Dandisets"])
    M --> P2L
    Q --> P2L
    MG --> P2L
    P2L --> Y
    Y --> LK
    LK --> GP --> CMP
    LK --> GJ --> CMP
    CMP -. "make LinkML-friendlier & regenerate" .-> M
    CMP -. "issues & PRs" .-> LK

    click M href "https://github.com/dandi/dandi-schema/blob/master/dandischema/models.py" _blank
    click P2L href "https://github.com/dandi/pydantic2linkml" _blank
    click Y href "https://github.com/dandi/dandi-schema/blob/linkml-auto-converted/dandischema/models.yaml" _blank
    click LK href "https://github.com/linkml/linkml" _blank
    click CMP href "https://github.com/dandi/dandisets-linkml-status/blob/main/reports/linkml_translation/dandi/summary.md" _blank

    style Y fill:#eee8f7,stroke:#6a4b8a,stroke-width:2px
    style P2L fill:#f7dfd3,stroke:#c0392b
    style LK fill:#e3f0e3,stroke:#2e7d32
	

driver: tools/linkml_conversion · output: models.yaml

Back to LinkML: what we reported and fixed upstream

Merged PRsIssues (selected)
Isaac To linkml#3537 gen-json-schema emits readOnly
linkml#2363 validation results carry the originating error
linkml#2323, linkml-runtime#340 module-level loggers
linkml-runtime#338, linkml-runtime#341 SchemaBuilder fixes
linkml#3604 JSON Schema draft 2020-12
linkml#3719 value_presence: ABSENT in rules
linkml#3377 slot title not emitted to JSON Schema
linkml#2155 nullability in generated Pydantic
linkml#2215 no validation of uri range
linkml#2104 exact_cardinality, linkml#2206 equals_string_in without effect
linkml#3439–3442 JSON vs YAML loader asymmetries
John Lee linkml#3839 uncompactable URI type designators
linkml#3843 gen-json-schema: URI form of uriorcurie
linkml#3836 uriorcurie type designator round-trip
(mostly from ORINOCO-Lite work)

Pydantic gets simpler along the way — the eventual flip becomes boring

Tracked in dandi-schema#382 → sub-issues

state as of 2026-12-01; the links are live

Gotcha #1: LinkML is monotonic, Pydantic subclasses are not

What changed in a subclassHow we handled it
schemaKey: Literal["Person", "Organization", ...] single-value Literals in Pydantic (dandi-schema#437); designates_type: true via merge file; drop the per-class slot_usage
required False → True pydantic2linkml (pydantic2linkml#66) + LinkML contract test (dandi-schema#405)
range narrowed (wasGeneratedBy: Activity → Project) models_merge.yaml + contract test (dandi-schema#406)
pattern replaced (PublishedDandiset.id) consolidated Asset/Dandiset models in Pydantic (dandi-schema#419) — no more Published* classes

Gotcha #2: Pydantic/pydantic-core semantics with no LinkML equivalent

PydanticLinkMLResolution
max_length=150 on strno direct support (linkml#4155, open) separate length pattern under all_of (pydantic2linkml#63, dandi-schema#395); gen-pydantic does not enforce it
datetime microseconds “truncate”no equivalent accepted (dandi-schema#393)
float allowing ±inf / NaNnot supported accepted (dandi-schema#418)
AnyHttpUrl wrap validatorrange: uri open: to test in both generators (dandi-schema#390)
per-field title overrides (used by the Meditor)title on slot / slot_usage translated (dandi-schema#394)
discriminated unionsno construct patch-queue branch remove-discriminated-unions
@field_validator / @model_validator (ensure_contact_person_has_email, digest_check, ...)rules, partially open (dandi-schema#391) — next slide

Gotcha #3: the generators do not agree with each other

  • LinkML rules (e.g. “if datePublished then doi required”): gen-json-schema emits if/then and rejects; gen-pydantic keeps them as inert linkml_meta and accepts → custom template, upstream fix, or hand-written validators
  • Same for all_of slot expressions: the max_length pattern (Gotcha #2) is an allOf in JSON Schema, but only linkml_meta in gen-pydantic output; and its Python-only regex syntax ({,150}, \Z) does not compile in the Meditor's Ajv (/u regexps)
  • Checks reaching into nested objects or dict keys (assetsSummary.numberOfBytes, digest["dandi:sha2-256"]) are not cleanly expressible as rules
  • gen-json-schema hard-codes draft 2019-09; Pydantic and the frontend (Ajv) use 2020-12 — mostly cosmetic, since the Meditor strips $schema, until a tuple array appears
  • Without designates_type, a superclass-typed slot downcasts a Project to Activity (Pydantic) or rejects its extra fields (JSON Schema)

details, evidence and confidence: playbook findings.md

Where we are, and next

Take home: duplication is evil

Acknowledgements

Isaac To John Lee Satrajit Ghosh Yaroslav O. Halchenko

Thank you!

Questions?


https://datasets.datalad.org/centerforopenneuroscience/talks/2026-linkml-dandi-schema.html